text:
"""Tests for grr.client.client_actions.cloud."""

import os
import platform
import subprocess

import mock
import requests

from grr.client.client_actions import cloud
from grr.lib import config_lib
from grr.lib import flags
from grr.lib import test_lib
from grr.lib.rdfvalues import cloud as rdf_cloud

class GetCloudVMMetadataTest(test_lib.EmptyActionTest):
  ZONE_URL = "http://metadata.google.internal/computeMetadata/v1/instance/zone"
  PROJ_URL = ("http://metadata.google.internal/computeMetadata/"
              "v1/project/project-id")

  def testBIOSCommandRaises(self):
    with mock.patch.object(
        cloud.GetCloudVMMetadata, "BIOS_VERSION_COMMAND", new="/bin/false"):
      with self.assertRaises(subprocess.CalledProcessError):
        self.RunAction(
            cloud.GetCloudVMMetadata, arg=rdf_cloud.CloudMetadataRequest())

  def testNonMatchingBIOS(self):
    zone = mock.Mock(text="projects/123456789733/zones/us-central1-a")
    arg = rdf_cloud.CloudMetadataRequests(requests=[
        rdf_cloud.CloudMetadataRequest(
            bios_version_regex="Google",
            instance_type="GOOGLE",
            url=self.ZONE_URL,
            label="zone",
            headers={"Metadata-Flavor": "Google"})
    ])
    with mock.patch.object(
        cloud.GetCloudVMMetadata,
        "BIOS_VERSION_COMMAND",
        new=["/bin/echo", "Gaagle"]):
      with mock.patch.object(requests, "request") as mock_requests:
        mock_requests.side_effect = [zone]
        results = self.RunAction(cloud.GetCloudVMMetadata, arg=arg)

      self.assertFalse(results)

  def testWindowsServiceQuery(self):
    project = mock.Mock(text="myproject")
    sc_query_output = open(
        os.path.join(config_lib.CONFIG["Test.data_dir"],
                     "scquery_output.txt")).read()
    arg = rdf_cloud.CloudMetadataRequests(requests=[
        rdf_cloud.CloudMetadataRequest(
            bios_version_regex=".*amazon",
            instance_type="AMAZON",
            service_name_regex="SERVICE_NAME: AWSLiteAgent",
            url="http://169.254.169.254/latest/meta-data/ami-id",
            label="amazon-ami"), rdf_cloud.CloudMetadataRequest(
                bios_version_regex="Google",
                instance_type="GOOGLE",
                service_name_regex="SERVICE_NAME: GCEAgent",
                url=self.PROJ_URL,
                label="Google-project-id",
                headers={"Metadata-Flavor": "Google"})
    ])

    with mock.patch.object(platform, "system", return_value="Windows"):
      with mock.patch.object(
          subprocess, "check_output", return_value=sc_query_output):
        with mock.patch.object(requests, "request") as mock_requests:
          mock_requests.side_effect = [project]
          results = self.RunAction(cloud.GetCloudVMMetadata, arg=arg)

    responses = list(results[0].responses)
    self.assertEqual(len(responses), 1)
    self.assertEqual(results[0].instance_type, "GOOGLE")
    for response in responses:
      if response.label == "Google-project-id":
        self.assertEqual(response.text, project.text)
      else:
        self.fail("Bad response.label: %s" % response.label)

  def testMultipleBIOSMultipleURLs(self):
    ami = mock.Mock(text="ami-12345678")
    arg = rdf_cloud.CloudMetadataRequests(requests=[
        rdf_cloud.CloudMetadataRequest(
            bios_version_regex=".*amazon",
            instance_type="AMAZON",
            url="http://169.254.169.254/latest/meta-data/ami-id",
            label="amazon-ami"), rdf_cloud.CloudMetadataRequest(
                bios_version_regex="Google",
                instance_type="GOOGLE",
                url=self.PROJ_URL,
                label="Google-project-id",
                headers={"Metadata-Flavor": "Google"})
    ])
    with mock.patch.object(
        cloud.GetCloudVMMetadata,
        "BIOS_VERSION_COMMAND",
        new=["/bin/echo", "4.2.amazon"]):
      with mock.patch.object(requests, "request") as mock_requests:
        mock_requests.side_effect = [ami]
        results = self.RunAction(cloud.GetCloudVMMetadata, arg=arg)

    responses = list(results[0].responses)
    self.assertEqual(len(responses), 1)
    self.assertEqual(results[0].instance_type, "AMAZON")
    for response in responses:
      if response.label == "amazon-ami":
        self.assertEqual(response.text, ami.text)
      else:
        self.fail("Bad response.label: %s" % response.label)

  def testMatchingBIOSMultipleURLs(self):
    zone = mock.Mock(text="projects/123456789733/zones/us-central1-a")
    project = mock.Mock(text="myproject")
    arg = rdf_cloud.CloudMetadataRequests(requests=[
        rdf_cloud.CloudMetadataRequest(
            bios_version_regex="Google",
            instance_type="GOOGLE",
            url=self.ZONE_URL,
            label="zone",
            headers={"Metadata-Flavor": "Google"}),
        rdf_cloud.CloudMetadataRequest(
            bios_version_regex="Google",
            instance_type="GOOGLE",
            url=self.PROJ_URL,
            label="project-id",
            headers={"Metadata-Flavor": "Google"})
    ])

    with mock.patch.object(
        cloud.GetCloudVMMetadata,
        "BIOS_VERSION_COMMAND",
        new=["/bin/echo", "Google"]):
      with mock.patch.object(requests, "request") as mock_requests:
        mock_requests.side_effect = [zone, project]
        results = self.RunAction(cloud.GetCloudVMMetadata, arg=arg)

      responses = list(results[0].responses)
      self.assertEqual(len(responses), 2)
      self.assertEqual(results[0].instance_type, "GOOGLE")
      for response in responses:
        if response.label == "zone":
          self.assertEqual(response.text, zone.text)
        elif response.label == "project-id":
          self.assertEqual(response.text, project.text)
        else:
          self.fail("Bad response.label: %s" % response.label)

def main(argv):
  test_lib.main(argv)

if __name__ == "__main__":
  flags.StartMain(main)


text:
namespace sentencepiece {

template <typename K, typename V>
std::vector<std::pair<K, V>> Sorted(const std::vector<std::pair<K, V>> &m) {
  std::vector<std::pair<K, V>> v = m;
  std::sort(v.begin(), v.end(),
            [](const std::pair<K, V> &p1, const std::pair<K, V> &p2) {
              return (p1.second > p2.second ||
                      (p1.second == p2.second && p1.first < p2.first));
            });
  return v;
}

template <typename K, typename V>
std::vector<std::pair<K, V>> Sorted(const absl::flat_hash_map<K, V> &m) {
  std::vector<std::pair<K, V>> v(m.begin(), m.end());
  return Sorted(v);
}

class MultiFileSentenceIterator : public SentenceIterator {
 public:
  explicit MultiFileSentenceIterator(const std::vector<std::string> &files);
  ~MultiFileSentenceIterator() {}

  bool done() const override;
  void Next() override;
  const std::string &value() const override { return value_; }
  util::Status status() const override;

 private:
  void TryRead();

  bool read_done_ = false;
  size_t file_index_ = 0;
  std::vector<std::string> files_;
  std::string value_;
  std::unique_ptr<filesystem::ReadableFile> fp_;
};

// Base trainer class
class TrainerInterface {
 public:
  using Sentence = std::pair<std::string, int64>;
  using Sentences = std::vector<Sentence>;

  static const char32 kWSChar;
  static const char32 kUNKChar;
  static const char32 kUPPBoundaryChar;
  static const char kWSStr[];
  static const char kUNKStr[];
  static const char kUPPBoundaryStr[];

  TrainerInterface(const TrainerSpec &trainer_spec,
                   const NormalizerSpec &normalizer_spec,
                   const NormalizerSpec &denormalizer_spec);

  virtual ~TrainerInterface();

  // Loads sentence from `sentence_iterator` and stores the model
  // to `output_model_proto`.
  virtual util::Status Train(SentenceIterator *sentence_iterator,
                             ModelProto *output_model_proto) {
    sentence_iterator_ = sentence_iterator;
    output_model_proto_ = output_model_proto;
    return Train();
  }

  virtual util::Status Train() { return status(); }

  virtual util::Status status() const { return status_; }

  FRIEND_TEST(TrainerInterfaceTest, IsValidSentencePieceTest);
  FRIEND_TEST(TrainerInterfaceTest, OverrideSpecialPiecesTest);
  FRIEND_TEST(TrainerInterfaceTest, BytePiecesTest);
  FRIEND_TEST(TrainerInterfaceTest, SerializeTest);
  FRIEND_TEST(TrainerInterfaceTest, CharactersTest);

  // Loads all sentences from spec.input() or SentenceIterator.
  // It loads at most input_sentence_size sentences.
  util::Status LoadSentences();

 protected:
  // Returns true if |piece| is valid sentence piece.
  // The result is affected by
  // max_sentencepiece_length, split_by_whiespace, split_by_unicode_script.
  bool IsValidSentencePiece(const string_util::UnicodeText &piece) const;

  // Splits all sentencecs by whitespaces and
  // replace the |sentences_| with tokenized string.
  // e.g.,
  //  [ ["hello world ", 1], ["hi world]" ] =>
  //  [ ["hello", 1], ["hi", 1], ["world", 2] ]
  void SplitSentencesByWhitespace();

  // Save model files into spec.model_prefix().
  util::Status Save() const;

  // Set of characters which must be included in the final vocab.
  // The value of this map stores the frequency.
  absl::flat_hash_map<char32, int64> required_chars_;

  // Final output pieces
  std::vector<std::pair<std::string, float>> final_pieces_;

  // All sentences.
  Sentences sentences_;

  // Trainer spec.
  TrainerSpec trainer_spec_;

  // Normalizer spec
  NormalizerSpec normalizer_spec_;

  // Denormalizer spec
  NormalizerSpec denormalizer_spec_;

  // Reserved control pieces. e.g., <unk>, <s>, </s>.
  // key is vocab id.
  std::map<int, std::pair<std::string, ModelProto::SentencePiece::Type>>
      meta_pieces_;

  // Detect errors on initialization.
  util::Status status_;

  // Loads sentences from SentenceIterator if not null.
  SentenceIterator *sentence_iterator_ = nullptr;

  // Emits model to this proto instead of file.
  ModelProto *output_model_proto_ = nullptr;

 private:
  // Serialize final_pieces_ to |model_proto|.
  util::Status Serialize(ModelProto *model_proto) const;

  // Saves the best sentence split with the current model for debugging.
  util::Status SaveSplits(absl::string_view filename) const;

  // Saves model file.
  util::Status SaveModel(absl::string_view filename) const;

  // Saves vocabulary file for NMT.
  util::Status SaveVocab(absl::string_view filename) const;

  // Initializes `meta_pieces_` from TrainerSpec.
  util::Status InitMetaPieces();

  // Randomly sampled raw sentences for self-testing.
  std::vector<std::string> self_test_samples_;
};
}  // namespace sentencepiece
#endif  // TRAINER_INTERFACE_H_

redpajama_set_name: RedPajamaGithub


text:
package sample.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/file")
public class FileProcessingSampleController {

	@RequestMapping({"/", "/index"})
	public String index() {
		return "/file/index";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload(Model model) throws IOException {
		model.addAttribute("uploaded", false);
		return "/file/upload";
	}

	/**
	 * アップロードされたファイルの情報を読み取って画面に表示する例.
	 * アップロードされたファイルの情報にアクセスするには{@link RequestParam}と
	 * {@link MultipartFile}の組み合わせでハンドラの引数を宣言する。
	 *
	 * @param file アップロードされたファイルにアクセスするためのオブジェクト
	 * @param model モデル
	 * @return ビュー名
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam("file") MultipartFile file,
			Model model) throws IOException {
		// 実際にファイルがアップロードされたかチェック
		if (file.isEmpty()) {
			// 画面表示を制御するためのフラグを設定
			model.addAttribute("uploaded", false);
		} else {
			// 画面表示を制御するためのフラグを設定
			model.addAttribute("uploaded", true);
			// MultipartFileを通じてファイル情報にアクセス
			model.addAttribute("fileName", file.getOriginalFilename());
			model.addAttribute("firstLine", readFirstLine(file));
		}
		return "/file/upload";
	}

	private String readFirstLine(MultipartFile file) throws IOException {
		try {
			final BufferedReader br = new BufferedReader(
				new InputStreamReader(file.getInputStream(), Charset.forName("utf-8")));
			return br.readLine();
		} catch (IOException ex) {
			ex.printStackTrace();
			return "???";
		}
	}

}


text:
class Translate

	# This method is called when the plugin is first loaded
	def initialize( status, config, output, irc, timer )
		@status    = status
		@config    = config
		@output    = output
		@irc       = irc
		@timer     = timer

		@appid     = ""
		@filename  = "translate.appid"

		# Load AppId
		loadid
	end

	# Default method, alias for 'to'
	def main( nick, user, host, from, msg, arguments, con )
		to( nick, user, host, from, msg, arguments, con )
	end

	# Function to translate from one language to another
	def to( nick, user, host, from, msg, arguments, con )
		if( !arguments.nil? && !arguments.empty? )
			to, string = arguments.split( ' ', 2 )

			if( !string.nil? )
				string.gsub!( / /, "%20" ) # Replace spaces
				string.gsub!( /&/, "" ) # Sanitize GET variables

				# Send GET request
				line = Net::HTTP.get( 'api.microsofttranslator.com', '/v2/Http.svc/Translate?appId=' + @appid + '&to=' + to + '&text=' + string + '&contentType=text/plain' )

				# Catching some common errors
				if( line =~ /'to' must be a valid language/ )
					line = "Error: Invalid language code specified."
				elsif( line =~ /'from' must be a valid language/ )
					line = "Error: Could not detect language to translate from."
				end

				# Clean up output
				line.gsub!( /(<string(.+?)>)|(<\/string>)|(\n)|(\r)/, "" )
				line.gsub!( /(<(.+?)>)|(<\/(.+?))/, " " )
				line.gsub!( /  /, " " )
			else
				line = "Not valid input. Please see the help function for valid commands."
			end

			if( line.nil? || line.empty? )
				line = "Error: No result. (Probably wrong language code.)"
			end

			if( con )
				@output.c( line + "\n" )
			else
				@irc.message( from, line )
			end
		end
	end

	# Function to detect the language of a provided string
	def detect( nick, user, host, from, msg, arguments, con )
		if( !arguments.nil? && !arguments.empty? )
			arguments.gsub!( / /, "%20" ) # Replace spaces
			arguments.gsub!( /&/, "" ) # Sanitize GET variables

			# Send request
			line = Net::HTTP.get( 'api.microsofttranslator.com', '/v2/Http.svc/Detect?appId=' + @appid + '&text=' + arguments )

			# Clean up output
			line.gsub!( /(<string(.+?)>)|(<\/string>)|(\n)|(\r)/, "" )
			line.gsub!( /(<(.+?)>)|(<\/(.+?))/, " " )
			line.gsub!( /  /, " " )
		else
			line = "Not valid input. Please see the help function for valid commands."
		end

		if( line.nil? || line.empty? )
			line = "Error: No result. (Language not detectable.)"
		end

		if( con )
			@output.c( line + "\n" )
		else
			@irc.message( from, line )
		end
	end

	# Function to send help about this plugin
	def help( nick, user, host, from, msg, arguments, con )
		help = [
			"This plugin provides an interface to the Bing! translate API.",
			"  translate to [lang] [phrase]         - Translate a given phrase into another language.",
			"  translate detect [prase]             - Detect the language of the provided phrase.",
			"  translate help                       - Show this help.",
			" ",
			"  Valid language codes available here: http://wiki.insomnia247.nl/wiki/Nanobot_translate"
		]

		# Print out help
		help.each do |line|
			if( con )
				@output.c( line + "\n" )
			else
				@irc.notice( nick, line )
			end
		end
	end

	private

	# Load the AppId from a file
	def loadid
		# Check if a appid is stored on disk
		if File.exists?( @config.datadir + '/' + @filename )

			# Read database from file
        	file = File.open( @config.datadir + '/' + @filename )

			file.each do |line|
				@appid << line
			end
			@appid.gsub!( /[:blank:\n\r]/, "" )

			file.close
		else
			@output.bad( "Could not load AppId from #{@config.datadir}/#{@filename} for translate plugin." )
		end
	end
end


text:
using LitJson;
using System;
using System.Text;

namespace LuviKunG.Web.Socket
{
    public struct WebSocketEventData
    {
        public string code;
        public string eventName;
        public JsonData data;

        public WebSocketEventData(string code, string eventName, JsonData data)
        {
            this.code = code;
            this.eventName = eventName;
            this.data = data;
        }

        public WebSocketEventData(string parse) : this()
        {
            for (int i = 0; i < parse.Length; i++)
            {
                if (parse[i] == '[' || parse[i] == '{')
                {
                    code = parse.Substring(0, i);
                    string rEventData = parse.Substring(i);
                    JsonData json = JsonMapper.ToObject(rEventData);
                    if (json.IsArray && json.Count > 1)
                    {
                        if (json[0].IsString)
                            eventName = (string)json[0];
                        else
                            throw new Exception($"Cannot parse {nameof(eventName)} because it's wrong type.");
                        data = json[1];
                    }
                    else if (json.IsObject)
                    {
                        data = json;
                    }
                    break;
                }
                else continue;
            }
            if (string.IsNullOrEmpty(code))
            {
                code = parse;
            }
        }

        public string ToSocketData()
        {
            StringBuilder sb = new StringBuilder();
            if (!string.IsNullOrEmpty(code))
                sb.Append(code);
            if (string.IsNullOrEmpty(eventName))
            {
                if (data == null)
                    throw new Exception($"Cannot create string socket data from null data.");
                else
                    sb.Append(data.ToJson());
            }
            else
            {
                JsonData json = new JsonData();
                json.SetJsonType(JsonType.Array);
                json.Add(eventName);
                json.Add(data);
                sb.Append(json.ToJson());
            }
            return sb.ToString();
        }

        public override string ToString()
        {
            JsonData json = new JsonData();
            json.SetJsonType(JsonType.Object);
            json["code"] = code;
            json["eventName"] = eventName;
            json["data"] = data;
            return json.ToJson();
        }
    }
}


text:
import bson
import pymongo
import json
from bson import ObjectId
from pymongo import MongoClient
import string
import tangelo

def run():
    # Create an empty response object.
    response = {}
    response['datasource'] = 'remote'
    response['file'] = "http://localhost:8080/service/dataset-content-nano-one/nano/nano0826"
    response['name'] = "Nano Database Prototype"
    response['separator'] = ','
    response['skip'] = 0
    response['meta'] = [
        { "type": "id", "name": "OpenEye Name" },
        {'name':'Bmean','type':'float'},
        {'name':'Solvent','type':'float'},
        {'name':'nheavy_atoms','type':'integer','index':7}]
    response['sets'] = [
        { "format": "binary", "start": 1, "end": 5}]
    response['setlist'] = ['Aromatic','Macrocyclic','Sugar','VHQ-R subset', 'UHQ-R subset']
    response['attributelist'] = []
    response['author'] = 'KnowledgeVis, LLC'
    response['description'] = 'created by Tangelo service'
    response['source'] = "ABCC Imaging and Visualization Group"

    #tangelo.log(str(response))
    return json.dumps(response)


text:
package org.apache.flink.kubernetes.highavailability;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesConfigMap;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesException;
import org.apache.flink.kubernetes.kubeclient.resources.KubernetesLeaderElector;
import org.apache.flink.runtime.persistence.PossibleInconsistentStateException;
import org.apache.flink.runtime.persistence.RetrievableStateStorageHelper;
import org.apache.flink.runtime.persistence.StateHandleStore;
import org.apache.flink.runtime.persistence.StringResourceVersion;
import org.apache.flink.runtime.state.RetrievableStateHandle;
import org.apache.flink.runtime.state.StateObject;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.InstantiationUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static org.apache.flink.runtime.util.StateHandleStoreUtils.deserialize;
import static org.apache.flink.runtime.util.StateHandleStoreUtils.serializeOrDiscard;
import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * Class which stores state via the provided {@link RetrievableStateStorageHelper} and writes the
 * returned state handle to ConfigMap.
 *
 *
Added state is persisted via {@link RetrievableStateHandle RetrievableStateHandles}, which in
 * turn are written to ConfigMap. This level of indirection is necessary to keep the amount of data
 * in ConfigMap small. ConfigMap is build for data less than 1MB whereas state can grow to multiple
 * MBs and GBs.
 *
 *
This is a very different implementation with {@link
 * org.apache.flink.runtime.zookeeper.ZooKeeperStateHandleStore}. Benefit from the {@link
 * FlinkKubeClient#checkAndUpdateConfigMap} transactional operation, we could guarantee that only
 * the leader could update the store. Then we will completely get rid of the lock-and-release in
 * Zookeeper implementation.
 *
 * @param <T> Type of the state we're storing.
 */
public class KubernetesStateHandleStore<T extends Serializable>
        implements StateHandleStore<T, StringResourceVersion> {

    private static final Logger LOG = LoggerFactory.getLogger(KubernetesStateHandleStore.class);

    private static <T extends Serializable> StateHandleWithDeleteMarker<T> deserializeStateHandle(
            String content) throws IOException {
        checkNotNull(content, "Content should not be null.");
        final byte[] data = Base64.getDecoder().decode(content);
        try {
            return deserialize(data);
        } catch (IOException | ClassNotFoundException e) {
            throw new IOException(
                    String.format(
                            "Failed to deserialize state handle from ConfigMap data %s.", content),
                    e);
        }
    }

    private static String toBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

    @VisibleForTesting
    static String serializeStateHandle(StateHandleWithDeleteMarker<?> stateHandle)
            throws IOException {
        return toBase64(InstantiationUtil.serializeObject(stateHandle));
    }

    /**
     * Wrapper around state object that allows us to implement idempotent {@link
     * #releaseAndTryRemove(String)} and {@link #releaseAndTryRemoveAll()}.
     *
     * @param <T> Type of the state we're storing.
     */
    @VisibleForTesting
    static class StateHandleWithDeleteMarker<T extends Serializable> implements StateObject {

        private final RetrievableStateHandle<T> inner;
        private final boolean markedForDeletion;

        StateHandleWithDeleteMarker(RetrievableStateHandle<T> inner) {
            this(inner, false);
        }

        private StateHandleWithDeleteMarker(
                RetrievableStateHandle<T> inner, boolean markedForDeletion) {
            this.inner = inner;
            this.markedForDeletion = markedForDeletion;
        }

        @Override
        public void discardState() throws Exception {
            inner.discardState();
        }

        @Override
        public long getStateSize() {
            return inner.getStateSize();
        }

        RetrievableStateHandle<T> getInner() {
            return inner;
        }

        boolean isMarkedForDeletion() {
            return markedForDeletion;
        }

        StateHandleWithDeleteMarker<T> toDeleting() {
            return new StateHandleWithDeleteMarker<>(inner, true);
        }
    }

    private final FlinkKubeClient kubeClient;

    private final String configMapName;

    private final RetrievableStateStorageHelper<T> storage;

    private final Predicate<String> configMapKeyFilter;

    @Nullable private final String lockIdentity;

    /**
     * Creates a {@link KubernetesStateHandleStore}.
     *
     * @param kubeClient The Kubernetes client.
     * @param storage To persist the actual state and whose returned state handle is then written to
     *     ConfigMap
     * @param configMapName ConfigMap to store the state handle store pointer
     * @param configMapKeyFilter filter to get the expected keys for state handle
     * @param lockIdentity lock identity of current HA service
     */
    public KubernetesStateHandleStore(
            FlinkKubeClient kubeClient,
            String configMapName,
            RetrievableStateStorageHelper<T> storage,
            Predicate<String> configMapKeyFilter,
            @Nullable String lockIdentity) {

        this.kubeClient = checkNotNull(kubeClient, "Kubernetes client");
        this.storage = checkNotNull(storage, "State storage");
        this.configMapName = checkNotNull(configMapName, "ConfigMap name");
        this.configMapKeyFilter = checkNotNull(configMapKeyFilter);
        this.lockIdentity = lockIdentity;
    }

    /**
     * Creates a state handle, stores it in ConfigMap. We could guarantee that only the leader could
     * update the ConfigMap. Since "Get(check the leader)-and-Update(write back to the ConfigMap)"
     * is a transactional operation.
     *
     * @param key Key in ConfigMap
     * @param state State to be added
     * @throws AlreadyExistException if the name already exists
     * @throws PossibleInconsistentStateException if the write-to-Kubernetes operation failed. This
     *     indicates that it's not clear whether the new state was successfully written to
     *     Kubernetes or not. No state was discarded. Proper error handling has to be applied on the
     *     caller's side.
     * @throws Exception if persisting state or writing state handle failed
     */
    @Override
    public RetrievableStateHandle<T> addAndLock(String key, T state)
            throws PossibleInconsistentStateException, Exception {
        checkNotNull(key, "Key in ConfigMap.");
        checkNotNull(state, "State.");

        final RetrievableStateHandle<T> storeHandle = storage.store(state);

        final byte[] serializedStoreHandle =
                serializeOrDiscard(new StateHandleWithDeleteMarker<>(storeHandle));

        // initialize flag to serve the failure case
        boolean discardState = true;
        try {
            // a successful operation will result in the state not being discarded
            discardState =
                    !updateConfigMap(
                                    cm -> {
                                        try {
                                            return addEntry(cm, key, serializedStoreHandle);
                                        } catch (Exception e) {
                                            throw new CompletionException(e);
                                        }
                                    })
                            .get();
            return storeHandle;
        } catch (Exception ex) {
            final Optional<PossibleInconsistentStateException> possibleInconsistentStateException =
                    ExceptionUtils.findThrowable(ex, PossibleInconsistentStateException.class);
            if (possibleInconsistentStateException.isPresent()) {
                // it's unclear whether the state handle metadata was written to the ConfigMap -
                // hence, we don't discard the data
                discardState = false;
                throw possibleInconsistentStateException.get();
            }

            throw ExceptionUtils.findThrowable(ex, AlreadyExistException.class)
                    .orElseThrow(() -> ex);
        } finally {
            if (discardState) {
                storeHandle.discardState();
            }
        }
    }

    /**
     * Replaces a state handle in ConfigMap and discards the old state handle. Wo do not lock
     * resource version and then replace in Kubernetes. Since the ConfigMap is periodically updated
     * by leader, the resource version changes very fast. We use a "check-existence and update"
     * transactional operation instead.
     *
     * @param key Key in ConfigMap
     * @param resourceVersion resource version when checking existence via {@link #exists}.
     * @param state State to be added
     * @throws NotExistException if the name does not exist
     * @throws PossibleInconsistentStateException if a failure occurred during the update operation.
     *     It's unclear whether the operation actually succeeded or not. No state was discarded. The
     *     method's caller should handle this case properly.
     * @throws Exception if persisting state or writing state handle failed
     */
    @Override
    public void replace(String key, StringResourceVersion resourceVersion, T state)
            throws Exception {
        checkNotNull(key, "Key in ConfigMap.");
        checkNotNull(state, "State.");

        final RetrievableStateHandle<T> newStateHandle = storage.store(state);

        final byte[] serializedStateHandle =
                serializeOrDiscard(new StateHandleWithDeleteMarker<>(newStateHandle));

        // initialize flags to serve the failure case
        boolean discardOldState = false;
        boolean discardNewState = true;
        // We don't want to greedily pull the old state handle as we have to do that anyway in
        // replaceEntry method for check of delete markers.
        final AtomicReference<RetrievableStateHandle<T>> oldStateHandleRef =
                new AtomicReference<>();
        try {
            final boolean success =
                    updateConfigMap(
                                    cm -> {
                                        try {
                                            return replaceEntry(
                                                    cm,
                                                    key,
                                                    serializedStateHandle,
                                                    oldStateHandleRef);
                                        } catch (NotExistException e) {
                                            throw new CompletionException(e);
                                        }
                                    })
                            .get();

            // swap subject for deletion in case of success
            discardOldState = success;
            discardNewState = !success;
        } catch (Exception ex) {
            final Optional<PossibleInconsistentStateException> possibleInconsistentStateException =
                    ExceptionUtils.findThrowable(ex, PossibleInconsistentStateException.class);
            if (possibleInconsistentStateException.isPresent()) {
                // it's unclear whether the state handle metadata was written to the ConfigMap -
                // hence, we don't discard any data
                discardNewState = false;
                throw possibleInconsistentStateException.get();
            }

            throw ExceptionUtils.findThrowable(ex, NotExistException.class).orElseThrow(() -> ex);
        } finally {
            if (discardNewState) {
                newStateHandle.discardState();
            }

            if (discardOldState) {
                Objects.requireNonNull(
                                oldStateHandleRef.get(),
                                "state handle should have been set on success")
                        .discardState();
            }
        }
    }

    /**
     * Returns the resource version of the ConfigMap.
     *
     * @param key Key in ConfigMap
     * @return resource version in {@link StringResourceVersion} format.
     * @throws Exception if the check existence operation failed
     */
    @Override
    public StringResourceVersion exists(String key) throws Exception {
        checkNotNull(key, "Key in ConfigMap.");

        return kubeClient
                .getConfigMap(configMapName)
                .map(
                        configMap -> {
                            final String content = configMap.getData().get(key);
                            if (content != null) {
                                try {
                                    final StateHandleWithDeleteMarker<T> stateHandle =
                                            deserializeStateHandle(content);
                                    if (stateHandle.isMarkedForDeletion()) {
                                        return StringResourceVersion.notExisting();
                                    }
                                } catch (IOException e) {
                                    // Any calls to add or replace will try to remove this resource,
                                    // so we can simply treat it as non-existent.
                                    return StringResourceVersion.notExisting();
                                }
                                return StringResourceVersion.valueOf(
                                        configMap.getResourceVersion());
                            }
                            return StringResourceVersion.notExisting();
                        })
                .orElseThrow(this::getConfigMapNotExistException);
    }

    /**
     * Gets the {@link RetrievableStateHandle} stored in the given ConfigMap.
     *
     * @param key Key in ConfigMap
     * @return The retrieved state handle from the specified ConfigMap and key
     * @throws IOException if the method failed to deserialize the stored state handle
     * @throws NotExistException when the name does not exist
     * @throws Exception if get state handle from ConfigMap failed
     */
    @Override
    public RetrievableStateHandle<T> getAndLock(String key) throws Exception {
        checkNotNull(key, "Key in ConfigMap.");

        final Optional<KubernetesConfigMap> optional = kubeClient.getConfigMap(configMapName);
        if (optional.isPresent()) {
            final KubernetesConfigMap configMap = optional.get();
            if (configMap.getData().containsKey(key)) {
                final StateHandleWithDeleteMarker<T> result =
                        deserializeStateHandle(configMap.getData().get(key));
                if (result.isMarkedForDeletion()) {
                    throw getKeyMarkedAsDeletedException(key);
                }
                return result.getInner();
            } else {
                throw getKeyNotExistException(key);
            }
        } else {
            throw getConfigMapNotExistException();
        }
    }

    /**
     * Gets all available state handles from Kubernetes.
     *
     * @return All state handles from ConfigMap.
     */
    @Override
    public List<Tuple2<RetrievableStateHandle<T>, String>> getAllAndLock() {

        return kubeClient
                .getConfigMap(configMapName)
                .map(
                        configMap -> {
                            final List<Tuple2<RetrievableStateHandle<T>, String>> stateHandles =
                                    new ArrayList<>();
                            configMap.getData().entrySet().stream()
                                    .filter(entry -> configMapKeyFilter.test(entry.getKey()))
                                    .forEach(
                                            entry -> {
                                                try {
                                                    final StateHandleWithDeleteMarker<T> result =
                                                            deserializeStateHandle(
                                                                    entry.getValue());
                                                    if (!result.isMarkedForDeletion()) {
                                                        stateHandles.add(
                                                                new Tuple2<>(
                                                                        result.getInner(),
                                                                        entry.getKey()));
                                                    }
                                                } catch (IOException e) {
                                                    LOG.warn(
                                                            "ConfigMap {} contained corrupted data. Ignoring the key {}.",
                                                            configMapName,
                                                            entry.getKey());
                                                }
                                            });
                            return stateHandles;
                        })
                .orElse(Collections.emptyList());
    }

    /**
     * Return a list of all valid keys for state handles.
     *
     * @return List of valid state handle keys in Kubernetes ConfigMap
     * @throws Exception if get state handle names from ConfigMap failed.
     */
    @Override
    public Collection<String> getAllHandles() throws Exception {

        return kubeClient
                .getConfigMap(configMapName)
                .map(
                        configMap ->
                                configMap.getData().keySet().stream()
                                        .filter(configMapKeyFilter)
                                        .filter(
                                                k -> {
                                                    try {
                                                        final String content =
                                                                Objects.requireNonNull(
                                                                        configMap.getData().get(k));
                                                        return !deserializeStateHandle(content)
                                                                .isMarkedForDeletion();
                                                    } catch (IOException e) {
                                                        return false;
                                                    }
                                                })
                                        .collect(Collectors.toList()))
                .orElseThrow(this::getConfigMapNotExistException);
    }

    /**
     * Remove the key in state config map. As well as the state on external storage will be removed.
     * It returns the {@link RetrievableStateHandle} stored under the given state node if any.
     *
     * @param key Key to be removed from ConfigMap
     * @return True if the state handle is removed successfully
     * @throws Exception if removing the key or discarding the state failed
     */
    @Override
    public boolean releaseAndTryRemove(String key) throws Exception {
        checkNotNull(key, "Key in ConfigMap.");
        final AtomicReference<RetrievableStateHandle<T>> stateHandleRefer = new AtomicReference<>();
        return updateConfigMap(
                        configMap -> {
                            final String content = configMap.getData().get(key);
                            if (content != null) {
                                try {
                                    final StateHandleWithDeleteMarker<T> result =
                                            deserializeStateHandle(content);
                                    if (!result.isMarkedForDeletion()) {
                                        // Mark the ConfigMap entry as deleting. This basically
                                        // starts a "removal transaction" that allows us to retry
                                        // the removal if needed.
                                        configMap
                                                .getData()
                                                .put(
                                                        key,
                                                        serializeStateHandle(result.toDeleting()));
                                    }
                                    stateHandleRefer.set(result.getInner());
                                } catch (IOException e) {
                                    logInvalidEntry(key, configMapName, e);
                                    // Remove entry from the config map as we can't recover from
                                    // this (the serialization would fail on the retry as well).
                                    Objects.requireNonNull(configMap.getData().remove(key));
                                }
                                return Optional.of(configMap);
                            }
                            return Optional.empty();
                        })
                .thenCompose(
                        updated -> {
                            if (updated && stateHandleRefer.get() != null) {
                                try {
                                    stateHandleRefer.get().discardState();
                                    return updateConfigMap(
                                            configMap -> {
                                                // Now we can safely commit the "removal
                                                // transaction" by removing the entry from the
                                                // ConfigMap.
                                                configMap.getData().remove(key);
                                                return Optional.of(configMap);
                                            });
                                } catch (Exception e) {
                                    throw new CompletionException(e);
                                }
                            }
                            return CompletableFuture.completedFuture(updated);
                        })
                .get();
    }

    /**
     * Remove all the state handle keys in the ConfigMap and discard the states.
     *
     * @throws Exception when removing the keys or discarding the state failed
     */
    @Override
    public void releaseAndTryRemoveAll() throws Exception {
        final Map<String, RetrievableStateHandle<T>> validStateHandles = new HashMap<>();
        updateConfigMap(
                        configMap -> {
                            final Map<String, String> updateData =
                                    new HashMap<>(configMap.getData());
                            for (String key : configMap.getData().keySet()) {
                                if (configMapKeyFilter.test(key)) {
                                    try {
                                        final StateHandleWithDeleteMarker<T> result =
                                                deserializeStateHandle(
                                                        Objects.requireNonNull(
                                                                configMap.getData().get(key)));
                                        validStateHandles.put(key, result.getInner());
                                        // Start the "removal transaction" by marking the entries in
                                        // the ConfigMap as deleting.
                                        updateData.put(
                                                key, serializeStateHandle(result.toDeleting()));
                                    } catch (IOException e) {
                                        // Just log the invalid entry. It will be implicitly removed
                                        // because it hasn't been added into the update map.
                                        logInvalidEntry(key, configMapName, e);
                                    }
                                }
                            }
                            configMap.getData().clear();
                            configMap.getData().putAll(updateData);
                            return Optional.of(configMap);
                        })
                .thenCompose(
                        updated -> {
                            if (updated && !validStateHandles.isEmpty()) {
                                Exception exception = null;
                                for (RetrievableStateHandle<T> stateHandle :
                                        validStateHandles.values()) {
                                    try {
                                        stateHandle.discardState();
                                    } catch (Exception e) {
                                        exception = ExceptionUtils.firstOrSuppressed(e, exception);
                                    }
                                }
                                if (exception != null) {
                                    throw new CompletionException(
                                            new KubernetesException(
                                                    "Could not properly remove all state handles.",
                                                    exception));
                                }
                                // Commit the "removal transaction" by removing the entries from the
                                // ConfigMap.
                                return updateConfigMap(
                                        configMap -> {
                                            for (String key : validStateHandles.keySet()) {
                                                configMap.getData().remove(key);
                                            }
                                            return Optional.of(configMap);
                                        });
                            }
                            return CompletableFuture.completedFuture(updated);
                        })
                .get();
    }

    /**
     * Remove all the filtered keys in the ConfigMap.
     *
     * @throws Exception when removing the keys failed
     */
    @Override
    public void clearEntries() throws Exception {
        updateConfigMap(
                        configMap -> {
                            configMap.getData().keySet().removeIf(configMapKeyFilter);
                            return Optional.of(configMap);
                        })
                .get();
    }

    @Override
    public void release(String name) {
        // noop
    }

    @Override
    public void releaseAll() {
        // noop
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + "{configMapName='" + configMapName + "'}";
    }

    private boolean isValidOperation(KubernetesConfigMap c) {
        return lockIdentity == null || KubernetesLeaderElector.hasLeadership(c, lockIdentity);
    }

    @VisibleForTesting
    CompletableFuture<Boolean> updateConfigMap(
            Function<KubernetesConfigMap, Optional<KubernetesConfigMap>> updateFn) {
        return kubeClient.checkAndUpdateConfigMap(
                configMapName,
                configMap -> {
                    if (isValidOperation(configMap)) {
                        return updateFn.apply(configMap);
                    }
                    return Optional.empty();
                });
    }

    /**
     * Adds entry into the ConfigMap. If the entry already exists and contains delete marker, we try
     * to finish the removal before the actual update.
     */
    private Optional<KubernetesConfigMap> addEntry(
            KubernetesConfigMap configMap, String key, byte[] serializedStateHandle)
            throws Exception {
        final String content = configMap.getData().get(key);
        if (content != null) {
            try {
                final StateHandleWithDeleteMarker<T> stateHandle = deserializeStateHandle(content);
                if (stateHandle.isMarkedForDeletion()) {
                    // This might be a left-over after the fail-over. As the remove operation is
                    // idempotent let's try to finish it.
                    if (!releaseAndTryRemove(key)) {
                        throw new IllegalStateException(
                                "Unable to remove the marked as deleting entry.");
                    }
                } else {
                    throw getKeyAlreadyExistException(key);
                }
            } catch (IOException e) {
                // Just log the invalid entry, it will be overridden
                // by the update code path below.
                logInvalidEntry(key, configMapName, e);
            }
        }
        configMap.getData().put(key, toBase64(serializedStateHandle));
        return Optional.of(configMap);
    }

    /**
     * Replace the entry in the ConfigMap. If the entry already exists and contains delete marker,
     * we treat it as non-existent and perform the best effort removal.
     */
    private Optional<KubernetesConfigMap> replaceEntry(
            KubernetesConfigMap configMap,
            String key,
            byte[] serializedStateHandle,
            AtomicReference<RetrievableStateHandle<T>> oldStateHandleRef)
            throws NotExistException {
        final String content = configMap.getData().get(key);
        if (content != null) {
            try {
                final StateHandleWithDeleteMarker<T> stateHandle = deserializeStateHandle(content);
                oldStateHandleRef.set(stateHandle.getInner());
                if (stateHandle.isMarkedForDeletion()) {
                    final NotExistException exception = getKeyNotExistException(key);
                    try {
                        // Try to finish the removal. We don't really care whether this succeeds or
                        // not, from the "replace" point of view, the entry doesn't exist.
                        releaseAndTryRemove(key);
                    } catch (Exception e) {
                        exception.addSuppressed(e);
                    }
                    throw exception;
                }
            } catch (IOException e) {
                // Just log the invalid entry, it will be removed by the update code path below.
                logInvalidEntry(key, configMapName, e);
            }
            configMap.getData().put(key, toBase64(serializedStateHandle));
            return Optional.of(configMap);
        }
        throw getKeyNotExistException(key);
    }

    private KubernetesException getConfigMapNotExistException() {
        return new KubernetesException(
                "ConfigMap "
                        + configMapName
                        + " does not exists. "
                        + "It may be deleted externally.");
    }

    private NotExistException getKeyNotExistException(String key) {
        return new NotExistException("Could not find " + key + " in ConfigMap " + configMapName);
    }

    private NotExistException getKeyMarkedAsDeletedException(String key) {
        return new NotExistException(
                "Already marked for deletion " + key + " in ConfigMap " + configMapName);
    }

    private AlreadyExistException getKeyAlreadyExistException(String key) {
        return new AlreadyExistException(key + " already exists in ConfigMap " + configMapName);
    }

    private static void logInvalidEntry(String key, String configMapName, Throwable e) {
        LOG.warn(
                "Could not retrieve the state handle of '{}' from ConfigMap '{}'. Removing the entry as we don't have any way to recover.",
                key,
                configMapName,
                e);
    }
}


text:
(function (angular) {
    'use strict';

    angular
        .module('refigureApp', [
            // libs
            'ui.router',
            'ngSanitize',
            'ngMaterial',
            'router.helper',
            'ui.ap.auto-focus',
            'dibari.angular-ellipsis',
            // custom modules
            'refigureAuth',
            'refigureProfile',
            'refigureShared',
            'angular-google-analytics'
        ])
        .constant('MESSAGES', {
            MSG_TYPE_REFIGURE_IMAGES_COLLECTED: 100,
            MSG_TYPE_USER_LOGGED_IN_ON_SITE: 41,
            MSG_TYPE_USER_LOGGED_OUT_ON_SITE: 51,
            MSG_TYPE_IS_EXTENSION_INSTALLED: 120
        })
        .constant('CONST', {
            extensionId: 'EXTENSION_ID',
            parseRefigureSite: 'PARSE_REFIGURE_SITE'
        })
        .config(appConfig)
        .config(themeConfig)
        .run(appRun);

    appConfig.$inject = [
        '$httpProvider',
        '$locationProvider',
        'AnalyticsProvider'
    ];

    function appConfig($httpProvider, $locationProvider, AnalyticsProvider) {
        $locationProvider.html5Mode(true);
        $httpProvider.interceptors.push('authInterceptor');
        $httpProvider.interceptors.push('authErrorInterceptor');
        $httpProvider.interceptors.push('errorInterceptor');

        AnalyticsProvider.setAccount('UA-116092391-1');
        AnalyticsProvider.setPageEvent('$stateChangeSuccess');
        AnalyticsProvider.trackUrlParams(true);
        // AnalyticsProvider.setDomainName(
        //     window.location.host.indexOf('localhost') === -1 ? window.location.host : 'none'
        // );
    }

    appRun.$inject = [
        '$rootScope',
        'auth',
        'Analytics'
    ];

    function appRun($rootScope, auth, Analytics) {
        $rootScope.projectName = 'Refigure';
        $rootScope.mobileBrowser = utils.mobileBrowser();
        if (auth.isAuthenticated()) {
            auth.usrInfo();
        }
    }

    themeConfig.$inject = [
        '$mdThemingProvider'
    ];

    function themeConfig($mdThemingProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('blue-grey')
            .accentPalette('orange');
    }
})(window.angular);


text:
"""
==================
A simple Fill plot
==================

This example showcases the most basic fill plot a user can do with matplotlib.
"""
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
plt.style.use('ggplot')

x = np.linspace(0, 1, 500)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

fig, ax = plt.subplots()

ax.fill(x, y, zorder=10)
ax.grid(True, zorder=5)
plt.show()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Helix: Helix::Logic::dev::ProjectDataTest Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Helix

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
Static Public Member Functions |
Private Member Functions |
Static Private Attributes |
List of all members

Helix::Logic::dev::ProjectDataTest Class Reference

#include <ProjectData_test.h>

Inheritance diagram for Helix::Logic::dev::ProjectDataTest:

  <map id="Helix::Logic::dev::ProjectDataTest_map" name="Helix::Logic::dev::ProjectDataTest_map">
<area href="classHelix_1_1Glob_1_1DataObjectTestClass.html" alt="Helix::Glob::DataObjectTestClass" shape="rect" coords="0,0,199,24"/>
</map>

Public Member Functions

 	ProjectDataTest ()

 	Standard Constructor.  More...

virtual 	~ProjectDataTest ()

 	Standard Destructor.  More...

virtual void 	runTests (IOConn &ioc, xmlNodePtr node)

 	Runs the tests contained in the given xmlNode.  More...

void 	insert (IOConn &ioc, xmlNodePtr node)

void 	update (IOConn &ioc, xmlNodePtr node)

void 	deleteByID (IOConn &ioc, xmlNodePtr node)

void 	selectAllForProj (IOConn &ioc, xmlNodePtr node)

void 	selectByID (IOConn &ioc, xmlNodePtr node)

 Public Member Functions inherited from Helix::Glob::DataObjectTestClass

virtual 	~DataObjectTestClass ()

virtual void 	setRecordMode (bool tf)

Static Public Member Functions

static bool 	compareObjects (ProjectData *first, ProjectData *second)

 	Compare two objects to see if they are the same.  More...

static bool 	compareLists (vector< ProjectData * > *first, vector< ProjectData * > *second)

 	Compare two lists of objects to see if they are the same.  More...

Private Member Functions

 	ProjectDataTest (const ProjectDataTest &c)

 	Copy constructor is private to prevent use.  More...

ProjectDataTest & 	operator= (const ProjectDataTest &c)

 	Assignment operator is private to prevent use.  More...

Static Private Attributes

static DataObjectTestClassRegister< ProjectDataTest > 	reg

 	Registers us with the global factory map.  More...

Additional Inherited Members

 Public Attributes inherited from Helix::Glob::DataObjectTestClass

bool 	m_recordMode

 	Are we running in record mode or not?  More...

Detailed Description

This is a generated data object test class that is used for testing the data object called ProjectData.

Constructor & Destructor Documentation

          Helix::Logic::dev::ProjectDataTest::ProjectDataTest
          (
          const ProjectDataTest &
          c	)

inlineprivate

Copy constructor is private to prevent use.

          ProjectDataTest::ProjectDataTest
          (
          	)

Standard Constructor.

          ProjectDataTest::~ProjectDataTest
          (
          	)

virtual

Standard Destructor.

Member Function Documentation

          bool ProjectDataTest::compareLists
          (
          vector< ProjectData * > *
          first,

          vector< ProjectData * > *
          second

          )

static

Compare two lists of objects to see if they are the same.

          bool ProjectDataTest::compareObjects
          (
          ProjectData *
          first,

          ProjectData *
          second

          )

static

Compare two objects to see if they are the same.

          void ProjectDataTest::deleteByID
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

This method will use our input XML document to prepare for and test the " + doName + "." + methodName + " method. We will use our list of output xml documents to verify the output of this method. If the list of ourput documents is empty, we will simply ensure that no exceptions are thrown using the given XML input document.

          void ProjectDataTest::insert
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

This method will use our input XML document to prepare for and test the ProjectData.insert method. We will use our list of output xml documents to verify the output of this method. If the list of ourput documents is empty, we will simply ensure that no exceptions are thrown using the given XML input document.

          ProjectDataTest& Helix::Logic::dev::ProjectDataTest::operator=
          (
          const ProjectDataTest &
          c	)

inlineprivate

Assignment operator is private to prevent use.

          void ProjectDataTest::runTests
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

virtual

Runs the tests contained in the given xmlNode.

Implements Helix::Glob::DataObjectTestClass.

          void ProjectDataTest::selectAllForProj
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

This method will use our input XML document to prepare for and test the ProjectData.selectAllForProj method. We will use our list of output xml documents to verify the output of this method. If the list of ourput documents is empty, we will simply ensure that no exceptions are thrown using the given XML input document.

          void ProjectDataTest::selectByID
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

This method will use our input XML document to prepare for and test the ProjectData.selectByID method. We will use our list of output xml documents to verify the output of this method. If the list of ourput documents is empty, we will simply ensure that no exceptions are thrown using the given XML input document.

          void ProjectDataTest::update
          (
          IOConn &
          ioc,

          xmlNodePtr
          node

          )

This method will use our input XML document to prepare for and test the " + doName + "." + methodName + " method. We will use our list of output xml documents to verify the output of this method. If the list of ourput documents is empty, we will simply ensure that no exceptions are thrown using the given XML input document.

Member Data Documentation

          DataObjectTestClassRegister< ProjectDataTest > ProjectDataTest::reg

staticprivate

Registers us with the global factory map.

The documentation for this class was generated from the following files:

logic/dev/ProjectData_test.h

logic/dev/ProjectData_test.cpp

Helix

Logic

dev

ProjectDataTest

Generated on Wed Jan 14 2015 12:23:31 for Helix by

     1.8.9.1


text:
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

$layout_defs['ProjectTask'] = array(
	// list of what Subpanels to show in the DetailView
	'subpanel_setup' => array(

	'activities' => array(
			'order' => 20,
			'sort_order' => 'desc',
			'sort_by' => 'date_start',
			'title_key' => 'LBL_ACTIVITIES_SUBPANEL_TITLE',
			'type' => 'collection',
			'subpanel_name' => 'activities',   //this values is not associated with a physical file.
			'module'=>'Activities',

			'top_buttons' => array(
				array('widget_class' => 'SubPanelTopCreateTaskButton'),
				array('widget_class' => 'SubPanelTopScheduleMeetingButton'),
				array('widget_class' => 'SubPanelTopScheduleCallButton'),
				array('widget_class' => 'SubPanelTopComposeEmailButton'),
			),

			'collection_list' => array(
				'meetings' => array(
					'module' => 'Meetings',
					'subpanel_name' => 'ForActivities',
					'get_subpanel_data' => 'meetings',
				),
				'tasks' => array(
					'module' => 'Tasks',
					'subpanel_name' => 'ForActivities',
					'get_subpanel_data' => 'tasks',
				),
				'calls' => array(
					'module' => 'Calls',
					'subpanel_name' => 'ForActivities',
					'get_subpanel_data' => 'calls',
				),
			)
		),

		'history' => array(
			'order' => 30,
			'sort_order' => 'desc',
			'sort_by' => 'date_entered',
			'title_key' => 'LBL_HISTORY_SUBPANEL_TITLE',
			'type' => 'collection',
			'subpanel_name' => 'history',   //this values is not associated with a physical file.
			'module'=>'Activities',

			'top_buttons' => array(
			array('widget_class' => 'SubPanelTopCreateNoteButton'),
			array('widget_class' => 'SubPanelTopArchiveEmailButton'),
            array('widget_class' => 'SubPanelTopSummaryButton'),
			),

			'collection_list' => array(
				'meetings' => array(
					'module' => 'Meetings',
					'subpanel_name' => 'ForHistory',
					'get_subpanel_data' => 'meetings',
				),
				'tasks' => array(
					'module' => 'Tasks',
					'subpanel_name' => 'ForHistory',
					'get_subpanel_data' => 'tasks',
				),
				'calls' => array(
					'module' => 'Calls',
					'subpanel_name' => 'ForHistory',
					'get_subpanel_data' => 'calls',
				),
				'notes' => array(
					'module' => 'Notes',
					'subpanel_name' => 'ForHistory',
					'get_subpanel_data' => 'notes',
				),
				'emails' => array(
					'module' => 'Emails',
					'subpanel_name' => 'ForHistory',
					'get_subpanel_data' => 'emails',
				),
			)
		),
	),
);
?>


text:
<?php

class acf_field_font_awesome extends acf_field {

	var	$stylesheet, // will hold fontawesome stylesheet url
		$version; // will hold fontawesome version number

	/*
	*  __construct
	*
	*  This function will setup the field type data
	*
	*  @type	function
	*  @date	5/03/2014
	*  @since	5.0.0
	*
	*  @param	n/a
	*  @return	n/a
	*/

	function __construct() {

		$this->name = 'font-awesome';
		$this->label = __('Font Awesome Icon');
		$this->category = __("Content",'acf'); // Basic, Content, Choice, etc
		$this->defaults = array(
			'enqueue_fa' 	=>	0,
			'allow_null' 	=>	0,
			'save_format'	=>  'element',
			'default_value'	=>	'',
			'fa_live_preview'	=>	'',
			'choices'		=>	$this->get_icons()
		);
		$this->l10n = array();

		$this->settings = array(
			'path' => dirname(__FILE__),
			'dir' => $this->helpers_get_dir( __FILE__ ),
			'version' => '1.5'
		);

		add_filter('acf/load_field', array( $this, 'maybe_enqueue_font_awesome' ) );

		parent::__construct();
	}

	function get_icons()
	{
		require_once ( dirname( __FILE__ ) . '/better-font-awesome-library/better-font-awesome-library.php' );

		$args = array(
			'version'				=> 'latest',
			'minified'				=> true,
			'remove_existing_fa'	=> false,
			'load_styles'			=> false,
			'load_admin_styles'		=> false,
			'load_shortcode'		=> false,
			'load_tinymce_plugin'	=> false
		);

		$bfa 		= Better_Font_Awesome_Library::get_instance( $args );
		$bfa_icons	= $bfa->get_icons();
		$bfa_prefix	= $bfa->get_prefix() . '-';
		$new_icons	= array();

		$this->stylesheet	= $bfa->get_stylesheet_url();
		$this->version		= $bfa->get_version();

		foreach ( $bfa_icons as $hex => $class ) {
			$unicode = '&#x' . ltrim( $hex, '\\') . ';';
			$new_icons[ $bfa_prefix . $class ] = $unicode . ' ' . $bfa_prefix . $class;
		}

		$new_icons = array_merge( array( 'null' => '- Select -' ), $new_icons );

		return $new_icons;
	}

	/*
	*  maybe_enqueue_font_awesome()
	*
	*  If Enqueue FA is set to true, enqueue it in the footer. We cannot enqueue in the header because wp_head has already been called
	*
	*/

	function maybe_enqueue_font_awesome( $field )
	{
		if( 'font-awesome' == $field['type'] && $field['enqueue_fa'] ) {
			add_action( 'wp_footer', array( $this, 'frontend_enqueue_scripts' ) );
		}

		return $field;
	}

	/*
	*  frontend_enqueue_scripts()
	*
	*  This action is called in the wp_enqueue_scripts action on the front end.
	*
	*  $info	http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
	*  @type	action
	*/

	function frontend_enqueue_scripts()
	{
		wp_register_style('font-awesome', $this->stylesheet, array(), $this->version);

		wp_enqueue_style( array( 'font-awesome' ) );
	}

	/*
	*  render_field_settings()
	*
	*  Create extra settings for your field. These are visible when editing a field
	*
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$field (array) the $field being edited
	*  @return	n/a
	*/

	function render_field_settings( $field )
	{
		/*
		*  acf_render_field_setting
		*
		*  This function will create a setting for your field. Simply pass the $field parameter and an array of field settings.
		*  The array of settings does not require a `value` or `prefix`; These settings are found from the $field array.
		*
		*  More than one setting can be added by copy/paste the above code.
		*  Please note that you must also have a matching $defaults value for the field name (font_size)
		*/

		acf_render_field_setting( $field, array(
			'label'			=> __('Live Preview','acf-font-awesome'),
			'instructions'	=> '',
			'type'			=> 'message',
			'name'			=> 'fa_live_preview',
			'class'			=> 'live-preview'
		));

		acf_render_field_setting( $field, array(
			'label'			=> __('Default Icon','acf-font-awesome'),
			'instructions'	=> '',
			'type'			=> 'select',
			'name'			=> 'default_value',
			'class'	  		=>  'fontawesome',
			'choices'		=>	$field['choices']
		));

		acf_render_field_setting( $field, array(
			'label'			=> __('Return Value','acf-font-awesome'),
			'instructions'	=> __('Specify the returned value on front end','acf-font-awesome'),
			'type'			=> 'radio',
			'name'			=> 'save_format',
			'choices'	=>	array(
				'element'	=>	__('Icon Element','acf-font-awesome'),
				'class'		=>	__('Icon Class','acf-font-awesome'),
				'unicode'	=>	__('Icon Unicode','acf-font-awesome'),
				'object'	=>	__('Icon Object','acf-font-awesome'),
			)
		));

		acf_render_field_setting( $field, array(
			'label'			=> __('Allow Null?','acf-font-awesome'),
			'instructions'	=> '',
			'type'			=> 'radio',
			'name'			=> 'allow_null',
			'choices'	=>	array(
				1	=>	__('Yes','acf-font-awesome'),
				0	=>	__('No','acf-font-awesome')
			)
		));

		acf_render_field_setting( $field, array(
			'label'			=> __('Enqueue FontAwesome?','acf-font-awesome'),
			'instructions'	=> __('Set to \'Yes\' to enqueue FA in the footer on any pages using this field.','acf-font-awesome'),
			'type'			=> 'radio',
			'name'			=> 'enqueue_fa',
			'choices'	=>	array(
				1	=>	__('Yes','acf-font-awesome'),
				0	=>	__('No','acf-font-awesome')
			)
		));
	}

	/*
	*  render_field()
	*
	*  Create the HTML interface for your field
	*
	*  @param	$field (array) the $field being rendered
	*
	*  @type	action
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$field (array) the $field being edited
	*  @return	n/a
	*/

	function render_field( $field )
	{
		if( 'object' == $field['save_format'] && 'null' !== $field['value'] )
			$field['value'] = array( $field['value']->class );

		// value must be array
		if( !is_array($field['value']) )
		{
			// perhaps this is a default value with new lines in it?
			if( strpos($field['value'], "\n") !== false )
			{
				// found multiple lines, explode it
				$field['value'] = explode("\n", $field['value']);
			}
			else
			{
				$field['value'] = array( $field['value'] );
			}
		}

		// trim value
		$field['value'] = array_map('trim', $field['value']);

		// html
		echo '
';
		echo '

';
		echo '<select id="' . $field['id'] . '" class="' . $field['class'] . ' fa-select2-field" name="' . $field['name'] . '" >';

		// null
		if( $field['allow_null'] )
		{
			echo '<option value="null">- ' . __("Select",'acf') . ' -</option>';
		}

		// loop through values and add them as options
		if( is_array($field['choices']) )
		{
			unset( $field['choices']['null'] );

			foreach( $field['choices'] as $key => $value )
			{
				$selected = $this->find_selected( $key, $field['value'], $field['save_format'], $field['choices'] );
				echo '<option value="'.$key.'" '.$selected.'>'.$value.'</option>';
			}
		}

		echo '</select>';
		echo '
';
	}

	function find_selected( $needle, $haystack, $type, $choices )
	{
		switch( $type )
		{
			case 'object':
			case 'element':
				$search = array( '' );
				$string = str_replace( $search, '', $haystack[0] );
				break;

			case 'unicode':
				$index = $choices[ $needle ];
				if ( stristr( $index, $haystack[0] ) ) {
					return 'selected="selected"';
				}
				return '';

			case 'class':
				$string = $haystack[0];
				break;
		}

		if( $string == $needle )
			return 'selected="selected"';

		return '';
	}

	/*
	*  input_admin_enqueue_scripts()
	*
	*  This action is called in the admin_enqueue_scripts action on the edit screen where your field is created.
	*  Use this action to add CSS + JavaScript to assist your render_field() action.
	*
	*  @type	action (admin_enqueue_scripts)
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	n/a
	*  @return	n/a
	*/

	function input_admin_enqueue_scripts() {

		// register acf scripts
		wp_enqueue_script('acf-input-font-awesome-edit-input', $this->settings['dir'] . 'js/edit_input.js', array(), $this->settings['version']);
		wp_enqueue_style('acf-input-font-awesome-input', $this->settings['dir'] . 'css/input.css', array(), $this->settings['version']);
		wp_enqueue_style('acf-input-font-awesome-fa', $this->stylesheet, array(), $this->version);
	}

	/*
	*  field_group_admin_enqueue_scripts()
	*
	*  This action is called in the admin_enqueue_scripts action on the edit screen where your field is edited.
	*  Use this action to add CSS + JavaScript to assist your render_field_options() action.
	*
	*  @type	action (admin_enqueue_scripts)
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	n/a
	*  @return	n/a
	*/

	function field_group_admin_enqueue_scripts() {

		// register acf scripts
		wp_enqueue_script('font-awesome-create-input', $this->settings['dir'] . 'js/create_input.js', array(), $this->settings['version']);
		wp_enqueue_style('acf-input-font-awesome-input', $this->settings['dir'] . 'css/input.css', array(), $this->settings['version']);
		wp_enqueue_style('acf-input-font-awesome-fa', $this->stylesheet, array(), $this->version);
	}

	/*
	*  load_value()
	*
	*  This filter is applied to the $value after it is loaded from the db
	*
	*  @type	filter
	*  @since	3.6
	*  @date	23/01/13
	*
	*  @param	$value (mixed) the value found in the database
	*  @param	$post_id (mixed) the $post_id from which the value was loaded
	*  @param	$field (array) the field array holding all the field options
	*  @return	$value
	*/

	function load_value( $value, $post_id, $field ) {

		if ( 'null' == $value ) {
			return;
		}

		switch( $field['save_format'] )
		{
			case 'object':
				$icon_unicode_string = $this->defaults['choices'][ $value ];
				$icon_unicode_arr = explode( ' ', $icon_unicode_string );
				$icon_unicode = $icon_unicode_arr[0];
				$value = (object) array(
						'unicode' => $icon_unicode,
						'class'	  => $value,
						'element' => ''
					);
				break;

			case 'unicode':
				$icon_unicode_string = $this->defaults['choices'][ $value ];
				$icon_unicode_arr = explode( ' ', $icon_unicode_string );
				$value = $icon_unicode_arr[0];
				break;

			case 'element':
				$value = '';
				break;
		}

		return $value;
	}

	/*
	*  helpers_get_dir()
	*
	*  Helper function taken from ACF 4.x to allow finding of asset paths when plugin is included from outside the plugins directory
	*
	*/

	function helpers_get_dir( $file ) {

		$dir = trailingslashit( dirname( $file ) );
		$count = 0;

		// sanitize for Win32 installs
		$dir = str_replace('\\' ,'/', $dir);

		// if file is in plugins folder
		$wp_plugin_dir = str_replace( '\\' ,'/', WP_PLUGIN_DIR );
		$dir = str_replace( $wp_plugin_dir, plugins_url(), $dir, $count );

		if ( $count < 1 ) {
			// if file is in wp-content folder
			$wp_content_dir = str_replace( '\\' ,'/', WP_CONTENT_DIR );
			$dir = str_replace( $wp_content_dir, content_url(), $dir, $count );
		}

		if ( $count < 1 ) {
			// if file is in ??? folder
			$wp_dir = str_replace( '\\' ,'/', ABSPATH );
			$dir = str_replace( $wp_dir, site_url( '/' ), $dir );
		}

		return $dir;
	}

}

// create field
new acf_field_font_awesome();


text:
namespace Merchello.Tests.UnitTests.TreeNode
{
    public class CollectionCountTreeNodeTests
    {

    }
}


text:
package edu.uci.ics.jung.algorithms.cluster;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections15.Transformer;

import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Pair;

/**
 * An algorithm for computing clusters (community structure) in graphs based on edge betweenness.
 * The betweenness of an edge is defined as the extent to which that edge lies along
 * shortest paths between all pairs of nodes.
 *
 * This algorithm works by iteratively following the 2 step process:
 *

 *
 Compute edge betweenness for all edges in current graph
 *
 Remove edge with highest betweenness
 *

 *

 * Running time is: O(kmn) where k is the number of edges to remove, m is the total number of edges, and
 * n is the total number of vertices. For very sparse graphs the running time is closer to O(kn^2) and for
 * graphs with strong community structure, the complexity is even lower.
 *

 * This algorithm is a slight modification of the algorithm discussed below in that the number of edges
 * to be removed is parameterized.
 * @author Scott White
 * @author Tom Nelson (converted to jung2)
 * @see "Community structure in social and biological networks by Michelle Girvan and Mark Newman"
 */
public class EdgeBetweennessClusterer<V,E> implements Transformer<Graph<V,E>,Set<Set<V>>> {
    private int mNumEdgesToRemove;
    private Map<E, Pair<V>> edges_removed;

   /**
    * Constructs a new clusterer for the specified graph.
    * @param numEdgesToRemove the number of edges to be progressively removed from the graph
    */
    public EdgeBetweennessClusterer(int numEdgesToRemove) {
        mNumEdgesToRemove = numEdgesToRemove;
        edges_removed = new LinkedHashMap<E, Pair<V>>();
    }

    /**
    * Finds the set of clusters which have the strongest "community structure".
    * The more edges removed the smaller and more cohesive the clusters.
    * @param graph the graph
    */
    public Set<Set<V>> transform(Graph<V,E> graph) {

        if (mNumEdgesToRemove < 0 || mNumEdgesToRemove > graph.getEdgeCount()) {
            throw new IllegalArgumentException("Invalid number of edges passed in.");
        }

        edges_removed.clear();

        for (int k=0;k<mNumEdgesToRemove;k++) {
            BetweennessCentrality<V,E> bc = new BetweennessCentrality<V,E>(graph);
            E to_remove = null;
            double score = 0;
            for (E e : graph.getEdges())
                if (bc.getEdgeScore(e) > score)
                {
                    to_remove = e;
                    score = bc.getEdgeScore(e);
                }
            edges_removed.put(to_remove, graph.getEndpoints(to_remove));
            graph.removeEdge(to_remove);
        }

        WeakComponentClusterer<V,E> wcSearch = new WeakComponentClusterer<V,E>();
        Set<Set<V>> clusterSet = wcSearch.transform(graph);

        for (Map.Entry<E, Pair<V>> entry : edges_removed.entrySet())
        {
            Pair<V> endpoints = entry.getValue();
            graph.addEdge(entry.getKey(), endpoints.getFirst(), endpoints.getSecond());
        }
        return clusterSet;
    }

    /**
     * Retrieves the list of all edges that were removed
     * (assuming extract(...) was previously called).
     * The edges returned
     * are stored in order in which they were removed.
     *
     * @return the edges in the original graph
     */
    public List<E> getEdgesRemoved()
    {
        return new ArrayList<E>(edges_removed.keySet());
    }
}


text:
#include "CommentDiagramConnector.h"

#include "ModelBase/src/nodes/TypedListDefinition.h"
DEFINE_TYPED_LIST(Comments::CommentDiagramConnector)

namespace Comments {

COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(CommentDiagramConnector)
COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(CommentDiagramConnector)

REGISTER_ATTRIBUTE(CommentDiagramConnector, startShape, Integer, false, false, true)
REGISTER_ATTRIBUTE(CommentDiagramConnector, startPoint, Integer, false, false, true)
REGISTER_ATTRIBUTE(CommentDiagramConnector, endShape, Integer, false, false, true)
REGISTER_ATTRIBUTE(CommentDiagramConnector, endPoint, Integer, false, false, true)

// references for primitive types?
CommentDiagramConnector::CommentDiagramConnector(int startShape, int startPoint, int endShape, int endPoint)
: Super{nullptr, CommentDiagramConnector::getMetaData()}
{
	setStartShape(startShape);
	setStartPoint(startPoint);
	setEndShape(endShape);
	setEndPoint(endPoint);
}

} /* namespace Comments */


text:
$(document).ready(function() {
  $('.nav--toggle').click(function() {
    "use strict";
    document.getElementById("nav--mobile").style.width = "100%";
    $('body').addClass('noScroll');
  });

  $('.nav--overlay-closebtn').click(function() {
    "use strict";
    document.getElementById("nav--mobile").style.width = "0%";
    $('body').removeClass('noScroll');
  });
});


text:
namespace Xceed.Wpf.Toolkit.Core
{
  public delegate void PropertyChangedEventHandler<T>( object sender, PropertyChangedEventArgs<T> e );
}


text:
<?php

namespace Respect\Validation\Exceptions\SubdivisionCode;

use Respect\Validation\Exceptions\SubdivisionCodeException;

/**
 * Exception class for Cayman Islands subdivision code.
 *
 * ISO 3166-1 alpha-2: KY
 */
class KySubdivisionCodeException extends SubdivisionCodeException
{
    public static $defaultTemplates = [
        self::MODE_DEFAULT => [
            self::STANDARD => '{{name}} must be a subdivision code of Cayman Islands',
        ],
        self::MODE_NEGATIVE => [
            self::STANDARD => '{{name}} must not be a subdivision code of Cayman Islands',
        ],
    ];
}


text:
function(doc) {
    if (doc.doc_type === "FormExportInstance" || doc.doc_type === "CaseExportInstance") {
        emit([doc.domain, doc.doc_type, doc.is_deidentified], null);
    }
}


text:
<?php

function manage_content(&$a) {

	if((! get_account_id()) || ($_SESSION['delegate'])) {
		notice( t('Permission denied.') . EOL);
		return;
	}

	require_once('include/security.php');

	$change_channel = ((argc() > 1) ? intval(argv(1)) : 0);

	if((argc() > 2) && (argv(2) === 'default')) {
		$r = q("select channel_id from channel where channel_id = %d and channel_account_id = %d limit 1",
			intval($change_channel),
			intval(get_account_id())
		);
		if($r) {
			q("update account set account_default_channel = %d where account_id = %d",
				intval($change_channel),
				intval(get_account_id())
			);
		}
		goaway(z_root() . '/manage');
	}

	if($change_channel) {
		$r = change_channel($change_channel);

		if((argc() > 2) && !(argv(2) === 'default')) {
			goaway(z_root() . '/' . implode('/',array_slice($a->argv,2))); // Go to whatever is after /manage/, but with the new channel
		}
		else {
			if($r && $r['channel_startpage'])
				goaway(z_root() . '/' . $r['channel_startpage']); // If nothing extra is specified, go to the default page
		}
		goaway(z_root());
	}

	$channels = null;

	if(local_channel()) {
		$r = q("select channel.*, xchan.* from channel left join xchan on channel.channel_hash = xchan.xchan_hash where channel.channel_account_id = %d and channel_removed = 0 order by channel_name ",
			intval(get_account_id())
		);

		$account = get_app()->get_account();

		if($r && count($r)) {
			$channels = $r;
			for($x = 0; $x < count($channels); $x ++) {
				$channels[$x]['link'] = 'manage/' . intval($channels[$x]['channel_id']);
				$channels[$x]['default'] = (($channels[$x]['channel_id'] == $account['account_default_channel']) ? "1" : '');
				$channels[$x]['default_links'] = '1';

				$c = q("SELECT id, item_wall FROM item
					WHERE item_unseen = 1 and uid = %d " . item_normal(),
					intval($channels[$x]['channel_id'])
				);

				if($c) {
					foreach ($c as $it) {
						if(intval($it['item_wall']))
							$channels[$x]['home'] ++;
						else
							$channels[$x]['network'] ++;
					}
				}

				$intr = q("SELECT COUNT(abook.abook_id) AS total FROM abook left join xchan on abook.abook_xchan = xchan.xchan_hash where abook_channel = %d and abook_pending = 1 and abook_self = 0 and abook_ignored = 0 and xchan_deleted = 0 and xchan_orphan = 0 ",
					intval($channels[$x]['channel_id'])
				);

				if($intr)
					$channels[$x]['intros'] = intval($intr[0]['total']);

				$mails = q("SELECT count(id) as total from mail WHERE channel_id = %d AND mail_seen = 0 and from_xchan != '%s' ",
					intval($channels[$x]['channel_id']),
					dbesc($channels[$x]['channel_hash'])
				);

				if($mails)
					$channels[$x]['mail'] = intval($mails[0]['total']);

				$events = q("SELECT type, start, adjust FROM `event`
					WHERE `event`.`uid` = %d AND start < '%s' AND start > '%s' and `ignore` = 0
					ORDER BY `start` ASC ",
					intval($channels[$x]['channel_id']),
					dbesc(datetime_convert('UTC', date_default_timezone_get(), 'now + 7 days')),
					dbesc(datetime_convert('UTC', date_default_timezone_get(), 'now - 1 days'))
				);

				if($events) {
					$channels[$x]['all_events'] = count($events);

					if($channels[$x]['all_events']) {
						$str_now = datetime_convert('UTC', date_default_timezone_get(), 'now', 'Y-m-d');
						foreach($events as $e) {
							$bd = false;
							if($e['type'] === 'birthday') {
								$channels[$x]['birthdays'] ++;
								$bd = true;
							}
							else {
								$channels[$x]['events'] ++;
							}
							if(datetime_convert('UTC', ((intval($e['adjust'])) ? date_default_timezone_get() : 'UTC'), $e['start'], 'Y-m-d') === $str_now) {
								$channels[$x]['all_events_today'] ++;
								if($bd)
									$channels[$x]['birthdays_today'] ++;
								else
									$channels[$x]['events_today'] ++;
							}
						}
					}
				}
			}
		}

	    $r = q("select count(channel_id) as total from channel where channel_account_id = %d and channel_removed = 0",
			intval(get_account_id())
		);
		$limit = account_service_class_fetch(get_account_id(),'total_identities');
		if($limit !== false) {
			$channel_usage_message = sprintf( t("You have created %1$.0f of %2$.0f allowed channels."), $r[0]['total'], $limit);
		}
		else {
			$channel_usage_message = '';
 		}
	}

	$links = array(
		array( 'new_channel', t('Create a new channel'), t('Create a new channel'))
	);

	$delegates = q("select * from abook left join xchan on abook_xchan = xchan_hash where
		abook_channel = %d and (abook_their_perms & %d) > 0",
		intval(local_channel()),
		intval(PERMS_A_DELEGATE)
	);

	if($delegates) {
		for($x = 0; $x < count($delegates); $x ++) {
			$delegates[$x]['link'] = 'magic?f=&dest=' . urlencode($delegates[$x]['xchan_url'])
			. '&delegate=' . urlencode($delegates[$x]['xchan_addr']);
		}
	}
	else {
		$delegates = null;
	}

	$o = replace_macros(get_markup_template('channels.tpl'), array(
		'$header'           => t('Channel Manager'),
		'$msg_selected'     => t('Current Channel'),
		'$selected'         => local_channel(),
		'$desc'             => t('Switch to one of your channels by selecting it.'),
		'$msg_default'      => t('Default Channel'),
		'$msg_make_default' => t('Make Default'),
		'$links'            => $links,
		'$all_channels'     => $channels,
		'$mail_format'      => t('%d new messages'),
		'$intros_format'    => t('%d new introductions'),
		'$channel_usage_message' => $channel_usage_message,
		'$delegate_header'  => t('Delegated Channels'),
		'$delegates'        => $delegates,

	));

	return $o;

}


text:
Originally written by Daniel Stelljes, but his whole account dissapeared without a trace.
Will try to keep it up-to-date with the Snapchat API.

This library is built to communicate with the Snapchat API. It is nearly
feature complete but still lacks some functionality available in the latest
versions of the official apps (namely Stories).

It's similar to the [excellent Snaphax library](http://github.com/tlack/snaphax)
built by Thomas Lackner <[@tlack](http://twitter.com/tlack)>, but the approach
is different enough that I figured it deserved its own repo.

## Class Methods

```php
require 'snapchat.php';

$snapchat = new Snapchat('username', 'password');
$snapchat->logout();
```

- #### getSnaps()

    ```php
    echo $snapchat->getSnaps();
    ```

- #### getMedia($snap_id)

    ```php
    $data = $snapchat->getMedia('122FAST2FURIOUS334r');
    file_put_contents('/home/dan/snap.jpg', $data);
    ```

- #### markSnapViewed($snap_id)

    ```php
    echo $snapchat->markSnapViewed('122FAST2FURIOUS334r');
    ```

- #### uploadImage($image_path)

    ```php
    echo $snapchat->uploadImage('../test.jpg');
    ```

- #### uploadVideo($video_path)

    ```php
    echo $snapchat->uploadVideo('../test.mp4');
    ```

- #### send($snap_id, $friends_array, $seconds)

    ```php
    $id = $snapchat->uploadImage('../test.jpg');
    echo $snapchat->send($id, array('kartiktalwar'), 8);
    ```

- #### getFriends()

    ```php
    echo $snapchat->getFriends();
    ```

- #### addFriends($friends_array)

    ```php
    echo $snapchat->addFriends(array('bill', 'bob', 'bart'));
    ```

- #### getBests($friends_array)

    ```php
    echo $snapchat->getBests(array('bill', 'bob'));
    ```

- #### deleteFriends($friends_array)

    ```php
    echo $snapchat->deleteFriends(array('bart'));
    ```

- #### updatePrivacy($privacy)

    ```php
    echo $snapchat->updatePrivacy(Snapchat::PRIVACY_FRIENDS);
    ```

## Usage

Include src/snapchat.php via require_once or Composer or whatever, then:

```php
<?php

// Log in:
$snapchat = new Snapchat('username', 'password');

// Get your feed:
$snaps = $snapchat->getSnaps();

// Get your friends' stories:
$snaps = $snapchat->getFriendStories();

// Download a specific snap:
$data = $snapchat->getMedia('122FAST2FURIOUS334r');
file_put_contents('/home/dan/snap.jpg', $data);

// Download a specific story:
$data = $snapchat->getStory('[story_media_id]', '[story_key]', '[story_iv]');

// Download a specific story's thumbnail:
$data = $snapchat->getStoryThumb('[story_media_id]', '[story_key]', '[thumbnail_iv]');

// Mark the snap as viewed:
$snapchat->markSnapViewed('122FAST2FURIOUS334r');

// Mark the story as viewed:
$snapchat->markStoryViewed('[story_id]');

// Screenshot!
$snapchat->markSnapShot('122FAST2FURIOUS334r');

// Upload a snap and send it to me for 8 seconds:
$id = $snapchat->upload(
	Snapchat::MEDIA_IMAGE,
	file_get_contents('/home/dan/whatever.jpg')
);
$snapchat->send($id, array('stelljes'), 8);

// Upload a video story:
$id = $snapchat->upload(
	Snapchat::MEDIA_VIDEO,
	file_get_contents('/home/dan/whatever.mov')
);
$snapchat->setStory($id, Snapchat::MEDIA_VIDEO);

// Destroy the evidence:
$snapchat->clearFeed();

// Find friends by phone number:
$friends = $snapchat->findFriends(array('18006492568', '7183876962'));

// Get a list of your friends:
$friends = $snapchat->getFriends();

// Add some people as friends:
$snapchat->addFriends(array('bill', 'bob'));

// Add someone you forgot:
$snapchat->addFriend('bart');

// Get a list of the people you've added:
$added = $snapchat->getAddedFriends();

// Find out who Bill and Bob snap the most:
$bests = $snapchat->getBests(array('bill', 'bob'));

// Set Bart's display name:
$snapchat->setDisplayName('bart', 'Barty');

// Block Bart:
$snapchat->block('bart');

// Unblock Bart:
$snapchat->unblock('bart');

// Delete Bart entirely:
$snapchat->deleteFriend('bart');

// You only want your friends to be able to snap you:
$snapchat->updatePrivacy(Snapchat::PRIVACY_FRIENDS);

// You want to change your email:
$snapchat->updateEmail('dan@example.com');

// Log out:
$snapchat->logout();

?>
```

## License

MIT


text:
import React from "react";
import styled, { keyframes } from "styled-components";

const Loader = () => {
  return (
    <>
      <Grid>
        {Array(6)
          .fill()
          .map((_, i) => {
            const column = i + 1;
            return <GridColumn key={column} column={column} />;
          })}
      </Grid>
    </>
  );
};

export default Loader;

const FoldUp = keyframes`
  0% {
    height: 100vh;
  }

  100% {
    height: 0;
  }
`;

const Grid = styled.div`
  display: grid;
  grid-template-columns: 60px 15% 1fr 1fr 15% 60px;
  grid-template-rows: 1fr;
  min-height: 100vh;
  width: 100%;
  position: fixed;
  z-index: 9999;
  pointer-events: none;
`;

const GridColumn = styled.div`
  grid-column: ${(props) => props.column};

  &::before {
    content: "";
    display: block;
    width: 100%;
    height: 100vh;
    background-color: ${(props) => props.theme.colors.primary};
    border-right: 1px solid ${(props) => props.theme.colors.primary};
    animation: ${FoldUp} 1000ms normal forwards;
    animation-delay: ${(props) => props.column * 100}ms;
  }

  &::after {
    content: "";
    display: block;
    width: 100%;
    height: 100vh;
    background-color: white;
    border-right: 1px solid white;
    animation: ${FoldUp} 1000ms normal forwards;
    animation-delay: ${(props) => props.column * 100}ms;
  }
`;


text:
package scal.io.liger.widget;

import timber.log.Timber;

/**
 * Created by mnbogner on 7/11/14.
 */
public class ImageWidget extends Widget {
    public String path;

    public ImageWidget() {
        this.type = this.getClass().getName();
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
}


text:
Rem
Rem $Header: cord_v3.sql 29-aug-2002.11:44:54 hyeh Exp $
Rem
Rem cord_v3.sql
Rem
Rem Copyright (c) 2002, 2015, Oracle Corporation.  All rights reserved.
Rem
Rem Permission is hereby granted, free of charge, to any person obtaining
Rem a copy of this software and associated documentation files (the
Rem "Software"), to deal in the Software without restriction, including
Rem without limitation the rights to use, copy, modify, merge, publish,
Rem distribute, sublicense, and/or sell copies of the Software, and to
Rem permit persons to whom the Software is furnished to do so, subject to
Rem the following conditions:
Rem
Rem The above copyright notice and this permission notice shall be
Rem included in all copies or substantial portions of the Software.
Rem
Rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
Rem EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
Rem MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
Rem NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
Rem LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
Rem OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
Rem WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Rem
Rem    NAME
Rem      cord_v3.sql - <one-line expansion of the name>
Rem
Rem    DESCRIPTION
Rem      <short description of component this file declares/defines>
Rem
Rem    NOTES
Rem      <other useful comments, qualifications, etc.>
Rem
Rem    MODIFIED   (MM/DD/YY)
Rem    hyeh        08/29/02 - hyeh_mv_comschema_to_rdbms
Rem    ahunold     07/22/02 - echo
Rem    ahunold     07/15/02 - ahunold_versions01
Rem    ahunold     07/15/02 - Created
Rem

CREATE TABLE orders
    ( order_id           NUMBER(12)
    , order_date         TIMESTAMP WITH LOCAL TIME ZONE
CONSTRAINT order_date_nn NOT NULL
    , order_mode         VARCHAR2(8)
    , customer_id        NUMBER(6) CONSTRAINT order_customer_id_nn NOT NULL
    , order_status       NUMBER(2)
    , order_total        NUMBER(8,2)
    , sales_rep_id       NUMBER(6)
    , promotion_id       NUMBER(6)
    , CONSTRAINT         order_mode_lov
                         CHECK (order_mode in ('direct','online'))
    , constraint         order_total_min
                         check (order_total >= 0)
    ) ;


text:
require "hotel_beds"
require "securerandom"

RSpec.describe "ordering a hotel room" do
  describe "#response" do
    before(:all) do
      @client = HotelBeds::Client.new({
        endpoint: :test,
        username: ENV.fetch("HOTEL_BEDS_USERNAME"),
        password: ENV.fetch("HOTEL_BEDS_PASSWORD"),
        proxy: ENV.fetch("HOTEL_BEDS_PROXY", nil)
      })
      @check_in_date = Date.today + 28 + rand(10)
      @check_out_date = @check_in_date + rand(3) + rand(2) + 1
      @search_operation = @client.perform_hotel_search({
        check_in_date: @check_in_date,
        check_out_date: @check_out_date,
        rooms: [{ adult_count: 2 }],
        destination_code: "SYD"
      })
      if @search_operation.errors.any?
        raise StandardError, @search_operation.errors.full_messages.join("\n")
      end
      @search_response = @search_operation.response

      hotel = @search_response.hotels.first
      rooms = hotel.available_rooms.first

      @basket_operation = @client.add_hotel_room_to_basket({
        service: {
          check_in_date: @check_in_date,
          check_out_date: @check_out_date,
          availability_token: hotel.availability_token,
          hotel_code: hotel.code,
          destination_code: hotel.destination.code,
          contract_name: hotel.contract.name,
          contract_incoming_office_code: hotel.contract.incoming_office_code,
          rooms: rooms
        }
      })
      if @basket_operation.errors.any?
        raise StandardError, @basket_operation.errors.full_messages.join("\n")
      end
      @basket_response = @basket_operation.response

      @flush_operation = @client.flush_purchase({
        purchase_token: @basket_response.purchase.token
      })
      if @flush_operation.errors.any?
        raise StandardError, @flush_operation.errors.full_messages.join("\n")
      end
      @flush_operation = @flush_operation.response
    end

    let(:response) { @flush_operation }

    subject { response }

    it "should be a success" do
      expect(subject).to be_success
    end
  end
end


text:
package com.ray3k.skincomposer.dialog.scenecomposer.undoables;

import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerModel.SimScrollPane;

public class ScrollPaneVisibleUndoable implements SceneComposerUndoable {
    private SimScrollPane scrollPane;
    private DialogSceneComposer dialog;
    private boolean visible;
    private boolean previousVisible;

    public ScrollPaneVisibleUndoable(boolean visible) {
        this.visible = visible;
        dialog = DialogSceneComposer.dialog;
        scrollPane = (SimScrollPane) dialog.simActor;
        previousVisible = scrollPane.visible;
    }

    @Override
    public void undo() {
        scrollPane.visible = previousVisible;

        if (dialog.simActor != scrollPane) {
            dialog.simActor = scrollPane;
            dialog.populateProperties();
            dialog.populatePath();
        }
        dialog.model.updatePreview();
    }

    @Override
    public void redo() {
        scrollPane.visible = visible;

        if (dialog.simActor != scrollPane) {
            dialog.simActor = scrollPane;
            dialog.populateProperties();
            dialog.populatePath();
        }
        dialog.model.updatePreview();
    }

    @Override
    public String getRedoString() {
        return "Redo \"ScrollPane visible " + visible + "\"";
    }

    @Override
    public String getUndoString() {
        return "Undo \"ScrollPane visible " + visible + "\"";
    }
}