text:
package renderer

import (
	"bytes"
	"os/exec"
	"strings"

	"github.com/fgrehm/go-san/model"
	"github.com/fgrehm/sls-web/src/core/compiler"

	"github.com/awalterschulze/gographviz"
)

type Service interface {
	Render(m *sanmodel.Model) ([]byte, error)
	RenderFromSource(source []byte) ([]byte, error)
}

type service struct {
	cs compiler.Service
}

func (s *service) Render(m *sanmodel.Model) ([]byte, error) {
	dot, err := s.graph(m)
	if err != nil {
		return nil, err
	}

	return s.png(dot)
}

func (s *service) RenderFromSource(source []byte) ([]byte, error) {
	parseResult, err := s.cs.Parse(source)
	if err != nil {
		return nil, err
	}

	return s.Render(parseResult.ParsedModel)
}

func (s *service) graph(m *sanmodel.Model) (string, error) {
	g := gographviz.NewGraph()
	g.SetName(m.Network.Name)
	g.SetDir(true)

	for i := 0; i < len(m.Network.Automata); i++ {
		aut := m.Network.Automata[i]
		g.AddSubGraph(m.Network.Name, "cluster_"+aut.Name, map[string]string{
			"label": aut.Name,
		})
		for _, state := range s.extractStates(aut) {
			g.AddNode("cluster_"+aut.Name, aut.Name+"_"+state, map[string]string{
				"label": state,
			})
		}
		for _, transition := range aut.Transitions {
			for _, event := range transition.Events {
				g.AddEdge(aut.Name+"_"+transition.From, aut.Name+"_"+transition.To, true, map[string]string{
					"label": event.EventName,
				})
			}
		}
	}
	return g.String(), nil
}

func (s *service) extractStates(aut *sanmodel.Automaton) []string {
	statesMap := make(map[string]*struct{})
	states := []string{}
	for _, transition := range aut.Transitions {
		if statesMap[transition.From] == nil {
			statesMap[transition.From] = &struct{}{}
			states = append(states, transition.From)
		}
		if statesMap[transition.To] == nil {
			statesMap[transition.To] = &struct{}{}
			states = append(states, transition.To)
		}
	}
	return states
}

func (s *service) png(dotGraph string) ([]byte, error) {
	cmd := exec.Command("dot", "-T", "png")
	cmd.Stdin = strings.NewReader(dotGraph)
	var out bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &out
	err := cmd.Run()
	if err != nil {
		println(out.String())
		return nil, err
	}
	return out.Bytes(), nil
}

func NewService(cs compiler.Service) Service {
	return &service{cs}
}


text:
package com.corejsf;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class LuhnCheckValidator implements ConstraintValidator<LuhnCheck, String> {
   public void initialize(LuhnCheck constraintAnnotation) {
   }

   public boolean isValid(String value, ConstraintValidatorContext context) {
      return luhnCheck(value.replaceAll("\\D", "")); // remove non-digits
   }

   private static boolean luhnCheck(String cardNumber) {
      int sum = 0;

      for(int i = cardNumber.length() - 1; i >= 0; i -= 2) {
         sum += Integer.parseInt(cardNumber.substring(i, i + 1));
         if(i > 0) {
            int d = 2 * Integer.parseInt(cardNumber.substring(i - 1, i));
            if(d > 9) d -= 9;
            sum += d;
         }
      }

      return sum % 10 == 0;
   }
}

redpajama_set_name: RedPajamaGithub


text:
using Com.Ctrip.Framework.Apollo.ConfigAdapter;
using Com.Ctrip.Framework.Apollo.Core;
using Com.Ctrip.Framework.Apollo.Core.Utils;
using Com.Ctrip.Framework.Apollo.Enums;
using Com.Ctrip.Framework.Apollo.Logging;

namespace Com.Ctrip.Framework.Apollo;

public interface IConfigAdapter
{
    Properties GetProperties(Properties properties);
}

public abstract class ContentConfigAdapter : IConfigAdapter
{
    private static readonly Func<Action<LogLevel, string, Exception?>> Logger = () => LogManager.CreateLogger(typeof(ContentConfigAdapter));

    public Properties GetProperties(Properties properties)
    {
        var content = properties.GetProperty(ConfigConsts.ConfigFileContentKey);
        if (string.IsNullOrWhiteSpace(content))
        {
            Logger().Warn("找不到" + ConfigConsts.ConfigFileContentKey);

            return properties;
        }

        return GetProperties(content!);
    }

    public abstract Properties GetProperties(string content);
}

public static class ConfigAdapterRegister
{
    private static readonly IDictionary<ConfigFileFormat, IConfigAdapter> Dic;

    static ConfigAdapterRegister()
    {
        Dic = new Dictionary<ConfigFileFormat, IConfigAdapter>();

        AddAdapter(ConfigFileFormat.Json, new JsonConfigAdapter());
        AddAdapter(ConfigFileFormat.Xml, new XmlConfigAdapter());
    }

    public static void AddAdapter(ConfigFileFormat format, IConfigAdapter adapter) =>
        Dic[format] = adapter ?? throw new ArgumentNullException(nameof(adapter));

    internal static bool TryGetAdapter(ConfigFileFormat format, out IConfigAdapter adapter) =>
        Dic.TryGetValue(format, out adapter);
}


text:
{% extends "frame.html" %}
{% block body %}

 Click to install your mitmproxy certificate:

Apple

Windows

Android

Other

    Other mitmproxy users cannot intercept your connection.

    This page is served by your local mitmproxy instance. The certificate you are about to install has been uniquely generated on mitmproxy's first run and is not shared
    between mitmproxy installations.

{% end %}


text:
(function(tinymce) {
	/**#@+
	 * @class This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed.
	 * @member tinymce.UndoManager
	 */
	tinymce.create('tinymce.UndoManager', {
		index : 0,
		data : null,
		typing : 0,

		/**
		 * Constructs a new UndoManager instance.
		 *
		 * @constructor
		 * @param {tinymce.Editor} ed Editor instance to undo/redo in.
		 */
		UndoManager : function(ed) {
			var t = this, Dispatcher = tinymce.util.Dispatcher;

			t.editor = ed;
			t.data = [];
			t.onAdd = new Dispatcher(this);
			t.onUndo = new Dispatcher(this);
			t.onRedo = new Dispatcher(this);
		},

		/**#@+
		 * @method
		 */

		/**
		 * Adds a new undo level/snapshot to the undo list.
		 *
		 * @param {Object} l Optional undo level object to add.
		 * @return {Object} Undo level that got added or null it a level wasn't needed.
		 */
		add : function(l) {
			var t = this, i, ed = t.editor, b, s = ed.settings, la;

			l = l || {};
			l.content = l.content || ed.getContent({format : 'raw', no_events : 1});

			// Add undo level if needed
			l.content = l.content.replace(/^\s*|\s*$/g, '');
			la = t.data[t.index > 0 && (t.index == 0 || t.index == t.data.length) ? t.index - 1 : t.index];
			if (!l.initial && la && l.content == la.content)
				return null;

			// Time to compress
			if (s.custom_undo_redo_levels) {
				if (t.data.length > s.custom_undo_redo_levels) {
					for (i = 0; i < t.data.length - 1; i++)
						t.data[i] = t.data[i + 1];

					t.data.length--;
					t.index = t.data.length;
				}
			}

			if (s.custom_undo_redo_restore_selection && !l.initial)
				l.bookmark = b = l.bookmark || ed.selection.getBookmark();

			if (t.index < t.data.length)
				t.index++;

			// Only initial marked undo levels should be allowed as first item
			// This to workaround a bug with Firefox and the blur event
			if (t.data.length === 0 && !l.initial)
				return null;

			// Add level
			t.data.length = t.index + 1;
			t.data[t.index++] = l;

			if (l.initial)
				t.index = 0;

			// Set initial bookmark use first real undo level
			if (t.data.length == 2 && t.data[0].initial)
				t.data[0].bookmark = b;

			t.onAdd.dispatch(t, l);
			ed.isNotDirty = 0;

			//console.dir(t.data);

			return l;
		},

		/**
		 * Undoes the last action.
		 *
		 * @return {Object} Undo level or null if no undo was performed.
		 */
		undo : function() {
			var t = this, ed = t.editor, l = l, i;

			if (t.typing) {
				t.add();
				t.typing = 0;
			}

			if (t.index > 0) {
				// If undo on last index then take snapshot
				if (t.index == t.data.length && t.index > 1) {
					i = t.index;
					t.typing = 0;

					if (!t.add())
						t.index = i;

					--t.index;
				}

				l = t.data[--t.index];
				ed.setContent(l.content, {format : 'raw'});
				ed.selection.moveToBookmark(l.bookmark);

				t.onUndo.dispatch(t, l);
			}

			return l;
		},

		/**
		 * Redoes the last action.
		 *
		 * @return {Object} Redo level or null if no redo was performed.
		 */
		redo : function() {
			var t = this, ed = t.editor, l = null;

			if (t.index < t.data.length - 1) {
				l = t.data[++t.index];
				ed.setContent(l.content, {format : 'raw'});
				ed.selection.moveToBookmark(l.bookmark);

				t.onRedo.dispatch(t, l);
			}

			return l;
		},

		/**
		 * Removes all undo levels.
		 */
		clear : function() {
			var t = this;

			t.data = [];
			t.index = 0;
			t.typing = 0;
			t.add({initial : true});
		},

		/**
		 * Returns true/false if the undo manager has any undo levels.
		 *
		 * @return {bool} true/false if the undo manager has any undo levels.
		 */
		hasUndo : function() {
			return this.index != 0 || this.typing;
		},

		/**
		 * Returns true/false if the undo manager has any redo levels.
		 *
		 * @return {bool} true/false if the undo manager has any redo levels.
		 */
		hasRedo : function() {
			return this.index < this.data.length - 1;
		}

		/**#@-*/
	});
})(tinymce);


text:
module Floskell.Buffer
    ( Buffer
    , empty
    , newline
    , write
    , line
    , column
    , toLazyByteString
    ) where

import qualified Data.ByteString         as BS
import           Data.ByteString.Builder ( Builder )
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Lazy    as BL

data Buffer =
    Buffer { bufferData        :: !Builder -- ^ The current output.
           , bufferDataNoSpace :: !Builder -- ^ The current output without trailing spaces.
           , bufferLine        :: !Int     -- ^ Current line number.
           , bufferColumn      :: !Int     -- ^ Current column number.
           }

-- | An empty output buffer.
empty :: Buffer
empty = Buffer { bufferData        = mempty
               , bufferDataNoSpace = mempty
               , bufferLine        = 0
               , bufferColumn      = 0
               }

-- | Append a ByteString to the output buffer.  It is an error for the
-- string to contain newlines.
write :: BS.ByteString -> Buffer -> Buffer
write str buf =
    buf { bufferData        = newBufferData
        , bufferDataNoSpace =
              if BS.all (== 32) str then bufferData buf else newBufferData
        , bufferColumn      = bufferColumn buf + BS.length str
        }
  where
    newBufferData = bufferData buf `mappend` BB.byteString str

-- | Append a newline to the output buffer.
newline :: Buffer -> Buffer
newline buf = buf { bufferData        = newBufferData
                  , bufferDataNoSpace = newBufferData
                  , bufferLine        = bufferLine buf + 1
                  , bufferColumn      = 0
                  }
  where
    newBufferData = bufferDataNoSpace buf `mappend` BB.char7 '\n'

-- | Return the current line number, counting from 0.
line :: Buffer -> Int
line = bufferLine

-- | Return the column number, counting from 0.
column :: Buffer -> Int
column = bufferColumn

-- | Return the contents of the output buffer as a lazy ByteString.
toLazyByteString :: Buffer -> BL.ByteString
toLazyByteString = BB.toLazyByteString . bufferData


text:
<?php

  session_start();

  function connectDB($username, $password, $host) {
    $db = new mysqli($host, $username, $password);

    session_regenerate_id();

    // check if conn'd successfully
    if($db->connect_error) {
      return $db->connect_error;
    } else {
      $_SESSION["username"] = $username;
      $_SESSION["password"] = $password;
      $_SESSION["host"] = $host;
      return "true";
    }
  }

  function resumeConnection() {
    // check if variables are actually set or not before using them
    if(isset($_SESSION["username"]) && isset($_SESSION["password"]) && isset($_SESSION["host"])) {
      $u = $_SESSION["username"];
      $p = $_SESSION["password"];
      $h = $_SESSION["host"];
    } else {
      $u = "";
      $p = "";
      $h = "";
    }

    if($u == "" || $h == "") {
      return "Not stored";
    } else {
      // conn and post back
      $db = new mysqli($h, $u, $p);
      if($db ->connect_error) {
        return $db->connect_error;
      } else {
        return $db;
      }
    }
  }

  // test connection and respond back with true/false based on status
  function testConn() {
    // check variables
    if(isset($_SESSION["username"]) && isset($_SESSION["password"]) && isset($_SESSION["host"])) {
      $u = $_SESSION["username"];
      $p = $_SESSION["password"];
      $h = $_SESSION["host"];
    } else {
      $u = "";
      $p = "";
      $h = "";
    }

    if($u == "" || $h == "") {
      return "Not stored";
    } else {
      // conn and post back
      $conn = new mysqli($h, $u, $p);
      if($conn->connect_error) {
        return "Error: [".$conn->connect_errno."] ".$conn->connect_error;
      } else {
        return "Success";
      }
    }
  }

  function logout() {
    session_unset();
    session_regenerate_id();
  }

?>


text:
<!DOCTYPE html>

  <wicket:panel>

No links or relations connect to this annotation.

  </wicket:panel>


text:
package com.caseystella.analytics.converters.csv;

import com.caseystella.analytics.converters.Converter;
import com.caseystella.analytics.converters.MappingConverter;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class CSVConverter implements MappingConverter, Serializable {
    static final long serialVersionUID = 1L;
    public static final String COLUMN_MAP_CONF = "columnMap";
    public static final String DELIMITER_CONF = "delim";
    private CSVParser parser;
    private Map< String, Integer> columnMap = new HashMap<>();
    public CSVConverter() {

    }

    private void initialize(Map<String, Object> config) {
        char separator = config.containsKey(DELIMITER_CONF)?config.get(DELIMITER_CONF).toString().charAt(0):',';
        parser = new CSVParserBuilder().withSeparator(separator)
                .build();
        columnMap = (Map<String, Integer>) config.get(COLUMN_MAP_CONF);
    }

    @Override
    public Map<String, Object> convert(byte[] in, Map<String, Object> config) {
        if(parser == null) {
           initialize(config) ;
        }
        String line = Bytes.toString(in);
        if(line.trim().startsWith("#")) {
           return null;
        }
        Map<String, Object> ret = new HashMap<>();
        try {
            String[] tokens = parser.parseLine(line);
            for(Map.Entry<String, Integer> kv : columnMap.entrySet()) {
                ret.put(kv.getKey(), tokens[kv.getValue()]);
            }
        } catch (IOException e) {
            return null;
        }
        return ret;
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".LauncherActivity" >

    <ExpandableListView
        android:id="@+id/expandPromoList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ACB317" />

</LinearLayout>


text:
package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
)

const VERSION = "v1.2.1"

var logger = log.New(os.Stderr, "", 0)

type OriginConfig struct {
	Addr   string
	Direct bool
}

func main() {
	port := flag.String("p", "443", "")
	ip := flag.String("i", "127.0.0.1", "")
	direct := flag.Bool("d", false, "")
	originPort := flag.String("P", "", "")
	originHost := flag.String("H", "", "")
	originDirect := flag.Bool("D", false, "")
	certPath := flag.String("c", "", "")
	keyPath := flag.String("k", "", "")
	outputLogFormat := flag.String("o", "default", "")
	version := flag.Bool("version", false, "")

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [OPTIONS]\n\n", os.Args[0])
		fmt.Println("Options:")
		fmt.Println("  -p:        Port (Default: 443)")
		fmt.Println("  -i:        IP Address (Default: 127.0.0.1)")
		fmt.Println("  -d:        Use HTTP/2 direct mode")
		fmt.Println("  -P:        Origin port")
		fmt.Println("  -H:        Origin host")
		fmt.Println("  -D:        Use HTTP/2 direct mode to connect origin")
		fmt.Println("  -c:        Certificate file")
		fmt.Println("  -k:        Certificate key file")
		fmt.Println("  -o:        Output log format (default or json, Default: default)")
		fmt.Println("  --version: Display version information and exit.")
		fmt.Println("  --help:    Display this help and exit.")
		os.Exit(1)
	}

	flag.Parse()

	if *version {
		logger.Printf("h2a %s\n", VERSION)
		os.Exit(0)
	}

	addr := net.JoinHostPort(*ip, *port)

	if *originPort == "" {
		logger.Fatalln("Origin port is not specified")
	}
	if *originHost == "" {
		logger.Fatalln("Origin host is not specified")
	}
	originConfig := OriginConfig{
		Addr:   net.JoinHostPort(*originHost, *originPort),
		Direct: *originDirect,
	}

	var formatter Formatter
	if *outputLogFormat == "json" {
		formatter = JSONFormatter
	} else {
		formatter = DefaultFormatter
	}

	var server net.Listener
	var err error
	if *direct {
		server, err = net.Listen("tcp", addr)
	} else {
		cert, err := tls.LoadX509KeyPair(*certPath, *keyPath)
		if err != nil {
			logger.Fatalln("Invalid certificate file")
		}

		config := &tls.Config{}
		config.Certificates = []tls.Certificate{cert}
		config.NextProtos = append(config.NextProtos, "h2", "h2-16", "h2-15", "h2-14", "http/1.1")

		server, err = tls.Listen("tcp", addr, config)
	}

	if err != nil {
		logger.Fatalf("Could not bind address - %s\n", addr)
	}

	defer server.Close()

	for {
		remoteConn, err := server.Accept()
		if err != nil {
			logger.Printf("Unable to accept: %s", err)
			continue
		}

		go handlePeer(remoteConn, originConfig, formatter)
	}
}

func handlePeer(remoteConn net.Conn, originConfig OriginConfig, formatter Formatter) {
	var originConn net.Conn
	var err error
	h2 := true
	_, useTls := remoteConn.(*tls.Conn)

	defer remoteConn.Close()

	dumper := NewFrameDumper(remoteConn.RemoteAddr(), formatter)
	defer dumper.Close()

	remoteCh, remoteErrCh := handleConnection(remoteConn)
	dumpDataCh, dumpDoneCh := handleFrameDumper(dumper)
	defer func() {
		dumpDoneCh <- true
	}()

	select {
	case chunk := <-remoteCh:
		var connState tls.ConnectionState

		if useTls {
			connState = remoteConn.(*tls.Conn).ConnectionState()

			if connState.NegotiatedProtocol == "" {
				connState.NegotiatedProtocol = "http/1.1"
			}
			if connState.NegotiatedProtocol == "http/1.1" {
				h2 = true
			}

			dumper.DumpConnectionState(connState)
		}

		if originConfig.Direct {
			originConn, err = net.Dial("tcp", originConfig.Addr)
		} else {
			config := &tls.Config{}
			if useTls {
				config.CipherSuites = []uint16{connState.CipherSuite}
				config.ServerName = connState.ServerName
			}
			config.InsecureSkipVerify = true
			config.NextProtos = append(config.NextProtos, connState.NegotiatedProtocol)

			originConn, err = tls.Dial("tcp", originConfig.Addr, config)
		}
		if err != nil {
			logger.Printf("Unable to connect to the origin: %s", err)
			return
		}

		defer originConn.Close()

		_, err = originConn.Write(chunk)
		if err != nil {
			logger.Printf("Unable to write data to the origin: %s", err)
			return
		}

		if h2 {
			dumpDataCh <- &DumpData{chunk, true}
		}

	case err := <-remoteErrCh:
		if err != io.EOF {
			logger.Printf("Connection error: %s", err)
		}
		return
	}

	originCh, originErrCh := handleConnection(originConn)

	for {
		select {
		case chunk := <-remoteCh:
			_, err := originConn.Write(chunk)
			if err != nil {
				logger.Printf("Unable to write data to the origin: %s", err)
				return
			}

			if h2 {
				dumpDataCh <- &DumpData{chunk, true}
			}

		case err := <-remoteErrCh:
			if err != io.EOF {
				logger.Printf("Connection error: %s", err)
			}

			return

		case chunk := <-originCh:
			_, err := remoteConn.Write(chunk)
			if err != nil {
				logger.Printf("Unable to write data to the connection: %s", err)
				return
			}

			if h2 {
				dumpDataCh <- &DumpData{chunk, false}
			}

		case err := <-originErrCh:
			if err != io.EOF {
				logger.Printf("Origin error: %s", err)
			}
			return
		}
	}
}

func handleConnection(conn net.Conn) (<-chan []byte, <-chan error) {
	dataCh := make(chan []byte)
	errCh := make(chan error, 1)

	go func() {
		for {
			buf := make([]byte, 262144)

			n, err := conn.Read(buf)
			if err != nil {
				errCh <- err
				break
			}

			dataCh <- buf[:n]
		}
	}()

	return dataCh, errCh
}

func handleFrameDumper(dumper *FrameDumper) (chan *DumpData, chan bool) {
	dataCh := make(chan *DumpData, 1024)
	doneCh := make(chan bool, 1)

	go func() {
		for {
			select {
			case d := <-dataCh:
				dumper.DumpFrame(d.Chunk, d.Remote)
			case <-doneCh:
				break
			}
		}
	}()

	return dataCh, doneCh
}

type DumpData struct {
	Chunk  []byte
	Remote bool
}


text:
package tarehart.alter;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Line;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
import java.util.ArrayList;
import java.util.List;

/**
 * Some code borrowed from this tutorial:
 * http://www.technogumbo.com/tutorials/Java-Microphone-Selection-And-Level-Monitoring/Java-Microphone-Selection-And-Level-Monitoring.php
 */
public class AudioSystemHelper {

    public static final Line.Info targetDLInfo = new Line.Info(TargetDataLine.class);

    public static List<Mixer.Info> ListAudioInputDevices() {
        List<Mixer.Info> returnList = new ArrayList<Mixer.Info>();
        Mixer.Info[] mixerInfo;

        mixerInfo = AudioSystem.getMixerInfo();

        for(int i = 0; i < mixerInfo.length; i++) {
            Mixer currentMixer = AudioSystem.getMixer(mixerInfo[i]);

            if( currentMixer.isLineSupported(targetDLInfo) ) {
                returnList.add( mixerInfo[i] );
            }
        }

        return returnList;
    }
}


text:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Alphaleonis.Win32.Filesystem
{
   public static partial class Directory
   {
      /// <summary>Enables/disables encryption of the specified directory and the files in it.
      ///   <para>This method only creates/modifies the file "Desktop.ini" in the root of <paramref name="path"/> and  enables/disables encryption by writing: "Disable=0" or "Disable=1".</para>
      ///   <para>This method does not affect encryption of files and subdirectories below the indicated directory.</para>
      /// </summary>
      /// <exception cref="ArgumentException"/>
      /// <exception cref="ArgumentNullException"/>
      /// <exception cref="DirectoryReadOnlyException"/>
      /// <exception cref="FileReadOnlyException"/>
      /// <exception cref="IOException"/>
      /// <exception cref="NotSupportedException"/>
      /// <exception cref="UnauthorizedAccessException"/>
      /// <param name="path">The name of the directory for which to enable encryption.</param>
      /// <param name="enable"><c>true</c> enabled encryption, <c>false</c> disables encryption.</param>
      /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
      [SecurityCritical]
      internal static void EnableDisableEncryptionCore(string path, bool enable, PathFormat pathFormat)
      {
         if (Utils.IsNullOrWhiteSpace(path))
            throw new ArgumentNullException("path");

         var pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

         // EncryptionDisable()
         // 2013-01-13: MSDN does not confirm LongPath usage and no Unicode version of this function exists.

         var success = NativeMethods.EncryptionDisable(pathLp, !enable);

         var lastError = Marshal.GetLastWin32Error();
         if (!success)
            NativeError.ThrowException(lastError, true, pathLp);
      }
   }
}


text:
'use strict';

define('brthur-chunklist',[
  'jquery',
  'EventEmitter'
], function (
  $, EventEmitter
) {

var defaults = {
  multiline: true
};

function ChunkList(options) {
  this.options = $.extend(defaults, options || {});
  this.chunks = [];
  this.observers = [];
  this.events = new EventEmitter();
  this.events.defineEvents(['chunkInserted', 'chunkChanged', 'chunkRemoved']);
}

ChunkList.prototype.getHtml = function () {
  var html = '';
  for (var i = 0; i < this.chunks.length; i++) {
    var chunk = this.chunks[i];
    html += chunk.getHtml();
  }
  return html;
};

ChunkList.prototype.appendChunk = function (chunk) {
  this.insertChunk(chunk, this.chunks.length);
};

ChunkList.prototype.insertChunk = function (chunk, index) {
  if (this.chunkIndex(chunk) === -1) {
    index = Math.max(0, Math.min(index, this.chunks.length));
    this.chunks.splice(index, 0, chunk);
    chunk.added(this);
    this.events.emitEvent('chunkInserted', [chunk, index]);
  }
};

ChunkList.prototype.removeChunk = function (chunk) {
  var index = this.chunkIndex(chunk)
  if (index !== -1) {
    this.chunks.splice(index, 1);
    chunk.removed();
    this.events.emitEvent('chunkRemoved', [chunk]);
  }
};

ChunkList.prototype.chunkIndex = function (chunk) {
  return this.chunks.indexOf(chunk);
};

return ChunkList;

});


text:
package com.badlogic.gdx.tools.texturepacker;

import com.badlogic.gdx.tools.texturepacker.TexturePacker.Packer;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Page;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.ProgressListener;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Rect;
import com.badlogic.gdx.tools.texturepacker.TexturePacker.Settings;
import com.badlogic.gdx.utils.Array;

/** @author Nathan Sweet */
public class GridPacker implements Packer {
	private final Settings settings;

	public GridPacker (Settings settings) {
		this.settings = settings;
	}

	public Array<Page> pack (Array<Rect> inputRects) {
		return pack(null, inputRects);
	}

	public Array<Page> pack (ProgressListener progress, Array<Rect> inputRects) {
		if (!settings.silent) System.out.print("Packing");

		// Rects are packed with right and top padding, so the max size is increased to match. After packing the padding is
		// subtracted from the page size.
		int paddingX = settings.paddingX, paddingY = settings.paddingY;
		int adjustX = paddingX, adjustY = paddingY;
		if (settings.edgePadding) {
			if (settings.duplicatePadding) {
				adjustX -= paddingX;
				adjustY -= paddingY;
			} else {
				adjustX -= paddingX * 2;
				adjustY -= paddingY * 2;
			}
		}
		int maxWidth = settings.maxWidth + adjustX, maxHeight = settings.maxHeight + adjustY;

		int n = inputRects.size;
		int cellWidth = 0, cellHeight = 0;
		for (int i = 0; i < n; i++) {
			Rect rect = inputRects.get(i);
			cellWidth = Math.max(cellWidth, rect.width);
			cellHeight = Math.max(cellHeight, rect.height);
		}
		cellWidth += paddingX;
		cellHeight += paddingY;

		inputRects.reverse();

		Array<Page> pages = new Array();
		while (inputRects.size > 0) {
			progress.count = n - inputRects.size + 1;
			if (progress.update(progress.count, n)) break;

			Page page = packPage(inputRects, cellWidth, cellHeight, maxWidth, maxHeight);
			page.width -= paddingX;
			page.height -= paddingY;
			pages.add(page);
		}
		return pages;
	}

	private Page packPage (Array<Rect> inputRects, int cellWidth, int cellHeight, int maxWidth, int maxHeight) {
		Page page = new Page();
		page.outputRects = new Array();

		int n = inputRects.size;
		int x = 0, y = 0;
		for (int i = n - 1; i >= 0; i--) {
			if (x + cellWidth > maxWidth) {
				y += cellHeight;
				if (y > maxHeight - cellHeight) break;
				x = 0;
			}
			Rect rect = inputRects.removeIndex(i);
			rect.x = x;
			rect.y = y;
			rect.width += settings.paddingX;
			rect.height += settings.paddingY;
			page.outputRects.add(rect);
			x += cellWidth;
			page.width = Math.max(page.width, x);
			page.height = Math.max(page.height, y + cellHeight);
		}

		// Flip so rows start at top.
		for (int i = page.outputRects.size - 1; i >= 0; i--) {
			Rect rect = page.outputRects.get(i);
			rect.y = page.height - rect.y - rect.height;
		}
		return page;
	}
}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../科/index.html">
<meta http-equiv=refresh content="0; url='../科/index.html'">

Redirecting...

Click here if you are not redirected.


text:
class Cask::Artifact::NestedContainer < Cask::Artifact::Base
  def install_phase
    @cask.artifacts[:nested_container].each { |container| extract(container) }
  end

  def uninstall_phase
    # no need to take action; we will get removed by rmtree of parent
  end

  def extract(container_relative_path)
    source = @cask.destination_path.join(container_relative_path)
    container = Cask::Container.for_path(source, @command)
    unless container
      raise CaskError.new "Aw dang, could not identify nested_container at '#{source}'"
    end
    ohai "Extracting nested container #{source.basename}"
    container.new(@cask, source, @command).extract
  end
end


text:
package demo.jz2013.korreksjon.core;

import java.util.List;

/**
 * Interface for KorreksjonTilstand instances that have an history of KorreksjonTilstand
 * User: eim
 * Date: 09.02.11
 * Time: 15:55
 */
public interface KorreksjonTilstandHistory extends KorreksjonTilstand {

    List<KorreksjonTilstand> getHistory();

}


text:
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommunicationLib.Communication.MarionetteComands
{
    public class IsElementSelectedCommand : MarionetteDebuggerCommand
    {
        public IsElementSelectedCommand(string elementId, int id = 0, string commandName = "isElementSelected") : base(id, commandName)
        {
            ElementId = elementId;
        }

        public string ElementId { get; set; }

        public override void ProcessResponse(JToken response)
        {
            base.ProcessResponse(response);
        }

        public override string ToString()
        {
            return JsonConvert.SerializeObject(
             new object[]
             {
                   0,
                   Id,
                   CommandName,
                   new {
                       id = ElementId,
                   }

             });

        }
    }
}


text:
package plugin // import "github.com/docker/docker/daemon/cluster/controllers/plugin"

import (
	"context"
	"errors"
	"io"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/docker/distribution/reference"
	enginetypes "github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/swarm/runtime"
	"github.com/docker/docker/pkg/pubsub"
	"github.com/docker/docker/plugin"
	v2 "github.com/docker/docker/plugin/v2"
	"github.com/sirupsen/logrus"
)

const (
	pluginTestName          = "test"
	pluginTestRemote        = "testremote"
	pluginTestRemoteUpgrade = "testremote2"
)

func TestPrepare(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, false)
	ctx := context.Background()

	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}

	if b.p == nil {
		t.Fatal("pull not performed")
	}

	c = newTestController(b, false)
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if b.p == nil {
		t.Fatal("unexpected nil")
	}
	if b.p.PluginObj.PluginReference != pluginTestRemoteUpgrade {
		t.Fatal("upgrade not performed")
	}

	c = newTestController(b, false)
	c.serviceID = "1"
	if err := c.Prepare(ctx); err == nil {
		t.Fatal("expected error on prepare")
	}
}

func TestStart(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, false)
	ctx := context.Background()

	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}

	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	if !b.p.IsEnabled() {
		t.Fatal("expected plugin to be enabled")
	}

	c = newTestController(b, true)
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}
	if b.p.IsEnabled() {
		t.Fatal("expected plugin to be disabled")
	}

	c = newTestController(b, false)
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}
	if !b.p.IsEnabled() {
		t.Fatal("expected plugin to be enabled")
	}
}

func TestWaitCancel(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, true)
	ctx := context.Background()
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	ctxCancel, cancel := context.WithCancel(ctx)
	chErr := make(chan error, 1)
	go func() {
		chErr <- c.Wait(ctxCancel)
	}()
	cancel()
	select {
	case err := <-chErr:
		if err != context.Canceled {
			t.Fatal(err)
		}
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for cancelation")
	}
}

func TestWaitDisabled(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, true)
	ctx := context.Background()
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	chErr := make(chan error, 1)
	go func() {
		chErr <- c.Wait(ctx)
	}()

	if err := b.Enable("test", nil); err != nil {
		t.Fatal(err)
	}
	select {
	case err := <-chErr:
		if err == nil {
			t.Fatal("expected error")
		}
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}

	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	ctxWaitReady, cancelCtxWaitReady := context.WithTimeout(ctx, 30*time.Second)
	c.signalWaitReady = cancelCtxWaitReady
	defer cancelCtxWaitReady()

	go func() {
		chErr <- c.Wait(ctx)
	}()

	chEvent, cancel := b.SubscribeEvents(1)
	defer cancel()

	if err := b.Disable("test", nil); err != nil {
		t.Fatal(err)
	}

	select {
	case <-chEvent:
		<-ctxWaitReady.Done()
		if err := ctxWaitReady.Err(); err == context.DeadlineExceeded {
			t.Fatal(err)
		}
		select {
		case <-chErr:
			t.Fatal("wait returned unexpectedly")
		default:
			// all good
		}
	case <-chErr:
		t.Fatal("wait returned unexpectedly")
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}

	if err := b.Remove("test", nil); err != nil {
		t.Fatal(err)
	}
	select {
	case err := <-chErr:
		if err == nil {
			t.Fatal("expected error")
		}
		if !strings.Contains(err.Error(), "removed") {
			t.Fatal(err)
		}
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}
}

func TestWaitEnabled(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, false)
	ctx := context.Background()
	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	chErr := make(chan error, 1)
	go func() {
		chErr <- c.Wait(ctx)
	}()

	if err := b.Disable("test", nil); err != nil {
		t.Fatal(err)
	}
	select {
	case err := <-chErr:
		if err == nil {
			t.Fatal("expected error")
		}
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}

	if err := c.Start(ctx); err != nil {
		t.Fatal(err)
	}

	ctxWaitReady, ctxWaitCancel := context.WithCancel(ctx)
	c.signalWaitReady = ctxWaitCancel
	defer ctxWaitCancel()

	go func() {
		chErr <- c.Wait(ctx)
	}()

	chEvent, cancel := b.SubscribeEvents(1)
	defer cancel()

	if err := b.Enable("test", nil); err != nil {
		t.Fatal(err)
	}

	select {
	case <-chEvent:
		<-ctxWaitReady.Done()
		if err := ctxWaitReady.Err(); err == context.DeadlineExceeded {
			t.Fatal(err)
		}
		select {
		case <-chErr:
			t.Fatal("wait returned unexpectedly")
		default:
			// all good
		}
	case <-chErr:
		t.Fatal("wait returned unexpectedly")
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}

	if err := b.Remove("test", nil); err != nil {
		t.Fatal(err)
	}
	select {
	case err := <-chErr:
		if err == nil {
			t.Fatal("expected error")
		}
		if !strings.Contains(err.Error(), "removed") {
			t.Fatal(err)
		}
	case <-time.After(10 * time.Second):
		t.Fatal("timeout waiting for event")
	}
}

func TestRemove(t *testing.T) {
	b := newMockBackend()
	c := newTestController(b, false)
	ctx := context.Background()

	if err := c.Prepare(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c.Shutdown(ctx); err != nil {
		t.Fatal(err)
	}

	c2 := newTestController(b, false)
	if err := c2.Prepare(ctx); err != nil {
		t.Fatal(err)
	}

	if err := c.Remove(ctx); err != nil {
		t.Fatal(err)
	}
	if b.p == nil {
		t.Fatal("plugin removed unexpectedly")
	}
	if err := c2.Shutdown(ctx); err != nil {
		t.Fatal(err)
	}
	if err := c2.Remove(ctx); err != nil {
		t.Fatal(err)
	}
	if b.p != nil {
		t.Fatal("expected plugin to be removed")
	}
}

func newTestController(b Backend, disabled bool) *Controller {
	return &Controller{
		logger:  &logrus.Entry{Logger: &logrus.Logger{Out: io.Discard}},
		backend: b,
		spec: runtime.PluginSpec{
			Name:     pluginTestName,
			Remote:   pluginTestRemote,
			Disabled: disabled,
		},
	}
}

func newMockBackend() *mockBackend {
	return &mockBackend{
		pub: pubsub.NewPublisher(0, 0),
	}
}

type mockBackend struct {
	p   *v2.Plugin
	pub *pubsub.Publisher
}

func (m *mockBackend) Disable(name string, config *enginetypes.PluginDisableConfig) error {
	m.p.PluginObj.Enabled = false
	m.pub.Publish(plugin.EventDisable{})
	return nil
}

func (m *mockBackend) Enable(name string, config *enginetypes.PluginEnableConfig) error {
	m.p.PluginObj.Enabled = true
	m.pub.Publish(plugin.EventEnable{})
	return nil
}

func (m *mockBackend) Remove(name string, config *enginetypes.PluginRmConfig) error {
	m.p = nil
	m.pub.Publish(plugin.EventRemove{})
	return nil
}

func (m *mockBackend) Pull(ctx context.Context, ref reference.Named, name string, metaHeaders http.Header, authConfig *enginetypes.AuthConfig, privileges enginetypes.PluginPrivileges, outStream io.Writer, opts ...plugin.CreateOpt) error {
	m.p = &v2.Plugin{
		PluginObj: enginetypes.Plugin{
			ID:              "1234",
			Name:            name,
			PluginReference: ref.String(),
		},
	}
	return nil
}

func (m *mockBackend) Upgrade(ctx context.Context, ref reference.Named, name string, metaHeaders http.Header, authConfig *enginetypes.AuthConfig, privileges enginetypes.PluginPrivileges, outStream io.Writer) error {
	m.p.PluginObj.PluginReference = pluginTestRemoteUpgrade
	return nil
}

func (m *mockBackend) Get(name string) (*v2.Plugin, error) {
	if m.p == nil {
		return nil, errors.New("not found")
	}
	return m.p, nil
}

func (m *mockBackend) SubscribeEvents(buffer int, events ...plugin.Event) (eventCh <-chan interface{}, cancel func()) {
	ch := m.pub.SubscribeTopicWithBuffer(nil, buffer)
	cancel = func() { m.pub.Evict(ch) }
	return ch, cancel
}


text:
package net

import (
	"context"
	"internal/nettrace"
	"syscall"
	"time"
)

// defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
// See golang.org/issue/31510
const (
	defaultTCPKeepAlive = 15 * time.Second
)

// A Dialer contains options for connecting to an address.
//
// The zero value for each field is equivalent to dialing
// without that option. Dialing with the zero value of Dialer
// is therefore equivalent to just calling the Dial function.
//
// It is safe to call Dialer's methods concurrently.
type Dialer struct {
	// Timeout is the maximum amount of time a dial will wait for
	// a connect to complete. If Deadline is also set, it may fail
	// earlier.
	//
	// The default is no timeout.
	//
	// When using TCP and dialing a host name with multiple IP
	// addresses, the timeout may be divided between them.
	//
	// With or without a timeout, the operating system may impose
	// its own earlier timeout. For instance, TCP timeouts are
	// often around 3 minutes.
	Timeout time.Duration

	// Deadline is the absolute point in time after which dials
	// will fail. If Timeout is set, it may fail earlier.
	// Zero means no deadline, or dependent on the operating system
	// as with the Timeout option.
	Deadline time.Time

	// LocalAddr is the local address to use when dialing an
	// address. The address must be of a compatible type for the
	// network being dialed.
	// If nil, a local address is automatically chosen.
	LocalAddr Addr

	// DualStack previously enabled RFC 6555 Fast Fallback
	// support, also known as "Happy Eyeballs", in which IPv4 is
	// tried soon if IPv6 appears to be misconfigured and
	// hanging.
	//
	// Deprecated: Fast Fallback is enabled by default. To
	// disable, set FallbackDelay to a negative value.
	DualStack bool

	// FallbackDelay specifies the length of time to wait before
	// spawning a RFC 6555 Fast Fallback connection. That is, this
	// is the amount of time to wait for IPv6 to succeed before
	// assuming that IPv6 is misconfigured and falling back to
	// IPv4.
	//
	// If zero, a default delay of 300ms is used.
	// A negative value disables Fast Fallback support.
	FallbackDelay time.Duration

	// KeepAlive specifies the interval between keep-alive
	// probes for an active network connection.
	// If zero, keep-alive probes are sent with a default value
	// (currently 15 seconds), if supported by the protocol and operating
	// system. Network protocols or operating systems that do
	// not support keep-alives ignore this field.
	// If negative, keep-alive probes are disabled.
	KeepAlive time.Duration

	// Resolver optionally specifies an alternate resolver to use.
	Resolver *Resolver

	// Cancel is an optional channel whose closure indicates that
	// the dial should be canceled. Not all types of dials support
	// cancellation.
	//
	// Deprecated: Use DialContext instead.
	Cancel <-chan struct{}

	// If Control is not nil, it is called after creating the network
	// connection but before actually dialing.
	//
	// Network and address parameters passed to Control method are not
	// necessarily the ones passed to Dial. For example, passing "tcp" to Dial
	// will cause the Control function to be called with "tcp4" or "tcp6".
	Control func(network, address string, c syscall.RawConn) error
}

func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 }

func minNonzeroTime(a, b time.Time) time.Time {
	if a.IsZero() {
		return b
	}
	if b.IsZero() || a.Before(b) {
		return a
	}
	return b
}

// deadline returns the earliest of:
//   - now+Timeout
//   - d.Deadline
//   - the context's deadline
//
// Or zero, if none of Timeout, Deadline, or context's deadline is set.
func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
	if d.Timeout != 0 { // including negative, for historical reasons
		earliest = now.Add(d.Timeout)
	}
	if d, ok := ctx.Deadline(); ok {
		earliest = minNonzeroTime(earliest, d)
	}
	return minNonzeroTime(earliest, d.Deadline)
}

func (d *Dialer) resolver() *Resolver {
	if d.Resolver != nil {
		return d.Resolver
	}
	return DefaultResolver
}

// partialDeadline returns the deadline to use for a single address,
// when multiple addresses are pending.
func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
	if deadline.IsZero() {
		return deadline, nil
	}
	timeRemaining := deadline.Sub(now)
	if timeRemaining <= 0 {
		return time.Time{}, errTimeout
	}
	// Tentatively allocate equal time to each remaining address.
	timeout := timeRemaining / time.Duration(addrsRemaining)
	// If the time per address is too short, steal from the end of the list.
	const saneMinimum = 2 * time.Second
	if timeout < saneMinimum {
		if timeRemaining < saneMinimum {
			timeout = timeRemaining
		} else {
			timeout = saneMinimum
		}
	}
	return now.Add(timeout), nil
}

func (d *Dialer) fallbackDelay() time.Duration {
	if d.FallbackDelay > 0 {
		return d.FallbackDelay
	} else {
		return 300 * time.Millisecond
	}
}

func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) {
	i := last(network, ':')
	if i < 0 { // no colon
		switch network {
		case "tcp", "tcp4", "tcp6":
		case "udp", "udp4", "udp6":
		case "ip", "ip4", "ip6":
			if needsProto {
				return "", 0, UnknownNetworkError(network)
			}
		case "unix", "unixgram", "unixpacket":
		default:
			return "", 0, UnknownNetworkError(network)
		}
		return network, 0, nil
	}
	afnet = network[:i]
	switch afnet {
	case "ip", "ip4", "ip6":
		protostr := network[i+1:]
		proto, i, ok := dtoi(protostr)
		if !ok || i != len(protostr) {
			proto, err = lookupProtocol(ctx, protostr)
			if err != nil {
				return "", 0, err
			}
		}
		return afnet, proto, nil
	}
	return "", 0, UnknownNetworkError(network)
}

// resolveAddrList resolves addr using hint and returns a list of
// addresses. The result contains at least one address when error is
// nil.
func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) {
	afnet, _, err := parseNetwork(ctx, network, true)
	if err != nil {
		return nil, err
	}
	if op == "dial" && addr == "" {
		return nil, errMissingAddress
	}
	switch afnet {
	case "unix", "unixgram", "unixpacket":
		addr, err := ResolveUnixAddr(afnet, addr)
		if err != nil {
			return nil, err
		}
		if op == "dial" && hint != nil && addr.Network() != hint.Network() {
			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
		}
		return addrList{addr}, nil
	}
	addrs, err := r.internetAddrList(ctx, afnet, addr)
	if err != nil || op != "dial" || hint == nil {
		return addrs, err
	}
	var (
		tcp      *TCPAddr
		udp      *UDPAddr
		ip       *IPAddr
		wildcard bool
	)
	switch hint := hint.(type) {
	case *TCPAddr:
		tcp = hint
		wildcard = tcp.isWildcard()
	case *UDPAddr:
		udp = hint
		wildcard = udp.isWildcard()
	case *IPAddr:
		ip = hint
		wildcard = ip.isWildcard()
	}
	naddrs := addrs[:0]
	for _, addr := range addrs {
		if addr.Network() != hint.Network() {
			return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
		}
		switch addr := addr.(type) {
		case *TCPAddr:
			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) {
				continue
			}
			naddrs = append(naddrs, addr)
		case *UDPAddr:
			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) {
				continue
			}
			naddrs = append(naddrs, addr)
		case *IPAddr:
			if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) {
				continue
			}
			naddrs = append(naddrs, addr)
		}
	}
	if len(naddrs) == 0 {
		return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()}
	}
	return naddrs, nil
}

// Dial connects to the address on the named network.
//
// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
// "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
// (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
// "unixpacket".
//
// For TCP and UDP networks, the address has the form "host:port".
// The host must be a literal IP address, or a host name that can be
// resolved to IP addresses.
// The port must be a literal port number or a service name.
// If the host is a literal IPv6 address it must be enclosed in square
// brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
// The zone specifies the scope of the literal IPv6 address as defined
// in RFC 4007.
// The functions JoinHostPort and SplitHostPort manipulate a pair of
// host and port in this form.
// When using TCP, and the host resolves to multiple IP addresses,
// Dial will try each IP address in order until one succeeds.
//
// Examples:
//
//	Dial("tcp", "golang.org:http")
//	Dial("tcp", "192.0.2.1:http")
//	Dial("tcp", "198.51.100.1:80")
//	Dial("udp", "[2001:db8::1]:domain")
//	Dial("udp", "[fe80::1%lo0]:53")
//	Dial("tcp", ":80")
//
// For IP networks, the network must be "ip", "ip4" or "ip6" followed
// by a colon and a literal protocol number or a protocol name, and
// the address has the form "host". The host must be a literal IP
// address or a literal IPv6 address with zone.
// It depends on each operating system how the operating system
// behaves with a non-well known protocol number such as "0" or "255".
//
// Examples:
//
//	Dial("ip4:1", "192.0.2.1")
//	Dial("ip6:ipv6-icmp", "2001:db8::1")
//	Dial("ip6:58", "fe80::1%lo0")
//
// For TCP, UDP and IP networks, if the host is empty or a literal
// unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
// TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
// assumed.
//
// For Unix networks, the address must be a file system path.
func Dial(network, address string) (Conn, error) {
	var d Dialer
	return d.Dial(network, address)
}

// DialTimeout acts like Dial but takes a timeout.
//
// The timeout includes name resolution, if required.
// When using TCP, and the host in the address parameter resolves to
// multiple IP addresses, the timeout is spread over each consecutive
// dial, such that each is given an appropriate fraction of the time
// to connect.
//
// See func Dial for a description of the network and address
// parameters.
func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
	d := Dialer{Timeout: timeout}
	return d.Dial(network, address)
}

// sysDialer contains a Dial's parameters and configuration.
type sysDialer struct {
	Dialer
	network, address string
	testHookDialTCP  func(ctx context.Context, net string, laddr, raddr *TCPAddr) (*TCPConn, error)
}

// Dial connects to the address on the named network.
//
// See func Dial for a description of the network and address
// parameters.
//
// Dial uses context.Background internally; to specify the context, use
// DialContext.
func (d *Dialer) Dial(network, address string) (Conn, error) {
	return d.DialContext(context.Background(), network, address)
}

// DialContext connects to the address on the named network using
// the provided context.
//
// The provided Context must be non-nil. If the context expires before
// the connection is complete, an error is returned. Once successfully
// connected, any expiration of the context will not affect the
// connection.
//
// When using TCP, and the host in the address parameter resolves to multiple
// network addresses, any dial timeout (from d.Timeout or ctx) is spread
// over each consecutive dial, such that each is given an appropriate
// fraction of the time to connect.
// For example, if a host has 4 IP addresses and the timeout is 1 minute,
// the connect to each single address will be given 15 seconds to complete
// before trying the next one.
//
// See func Dial for a description of the network and address
// parameters.
func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) {
	if ctx == nil {
		panic("nil context")
	}
	deadline := d.deadline(ctx, time.Now())
	if !deadline.IsZero() {
		if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
			subCtx, cancel := context.WithDeadline(ctx, deadline)
			defer cancel()
			ctx = subCtx
		}
	}
	if oldCancel := d.Cancel; oldCancel != nil {
		subCtx, cancel := context.WithCancel(ctx)
		defer cancel()
		go func() {
			select {
			case <-oldCancel:
				cancel()
			case <-subCtx.Done():
			}
		}()
		ctx = subCtx
	}

	// Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups.
	resolveCtx := ctx
	if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil {
		shadow := *trace
		shadow.ConnectStart = nil
		shadow.ConnectDone = nil
		resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow)
	}

	addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr)
	if err != nil {
		return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
	}

	sd := &sysDialer{
		Dialer:  *d,
		network: network,
		address: address,
	}

	var primaries, fallbacks addrList
	if d.dualStack() && network == "tcp" {
		primaries, fallbacks = addrs.partition(isIPv4)
	} else {
		primaries = addrs
	}

	c, err := sd.dialParallel(ctx, primaries, fallbacks)
	if err != nil {
		return nil, err
	}

	if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 {
		setKeepAlive(tc.fd, true)
		ka := d.KeepAlive
		if d.KeepAlive == 0 {
			ka = defaultTCPKeepAlive
		}
		setKeepAlivePeriod(tc.fd, ka)
		testHookSetKeepAlive(ka)
	}
	return c, nil
}

// dialParallel races two copies of dialSerial, giving the first a
// head start. It returns the first established connection and
// closes the others. Otherwise it returns an error from the first
// primary address.
func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) {
	if len(fallbacks) == 0 {
		return sd.dialSerial(ctx, primaries)
	}

	returned := make(chan struct{})
	defer close(returned)

	type dialResult struct {
		Conn
		error
		primary bool
		done    bool
	}
	results := make(chan dialResult) // unbuffered

	startRacer := func(ctx context.Context, primary bool) {
		ras := primaries
		if !primary {
			ras = fallbacks
		}
		c, err := sd.dialSerial(ctx, ras)
		select {
		case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
		case <-returned:
			if c != nil {
				c.Close()
			}
		}
	}

	var primary, fallback dialResult

	// Start the main racer.
	primaryCtx, primaryCancel := context.WithCancel(ctx)
	defer primaryCancel()
	go startRacer(primaryCtx, true)

	// Start the timer for the fallback racer.
	fallbackTimer := time.NewTimer(sd.fallbackDelay())
	defer fallbackTimer.Stop()

	for {
		select {
		case <-fallbackTimer.C:
			fallbackCtx, fallbackCancel := context.WithCancel(ctx)
			defer fallbackCancel()
			go startRacer(fallbackCtx, false)

		case res := <-results:
			if res.error == nil {
				return res.Conn, nil
			}
			if res.primary {
				primary = res
			} else {
				fallback = res
			}
			if primary.done && fallback.done {
				return nil, primary.error
			}
			if res.primary && fallbackTimer.Stop() {
				// If we were able to stop the timer, that means it
				// was running (hadn't yet started the fallback), but
				// we just got an error on the primary path, so start
				// the fallback immediately (in 0 nanoseconds).
				fallbackTimer.Reset(0)
			}
		}
	}
}

// dialSerial connects to a list of addresses in sequence, returning
// either the first successful connection, or the first error.
func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) {
	var firstErr error // The error from the first address is most relevant.

	for i, ra := range ras {
		select {
		case <-ctx.Done():
			return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())}
		default:
		}

		dialCtx := ctx
		if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
			partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
			if err != nil {
				// Ran out of time.
				if firstErr == nil {
					firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err}
				}
				break
			}
			if partialDeadline.Before(deadline) {
				var cancel context.CancelFunc
				dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
				defer cancel()
			}
		}

		c, err := sd.dialSingle(dialCtx, ra)
		if err == nil {
			return c, nil
		}
		if firstErr == nil {
			firstErr = err
		}
	}

	if firstErr == nil {
		firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress}
	}
	return nil, firstErr
}

// dialSingle attempts to establish and returns a single connection to
// the destination address.
func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) {
	trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
	if trace != nil {
		raStr := ra.String()
		if trace.ConnectStart != nil {
			trace.ConnectStart(sd.network, raStr)
		}
		if trace.ConnectDone != nil {
			defer func() { trace.ConnectDone(sd.network, raStr, err) }()
		}
	}
	la := sd.LocalAddr
	switch ra := ra.(type) {
	case *TCPAddr:
		la, _ := la.(*TCPAddr)
		c, err = sd.dialTCP(ctx, la, ra)
	case *UDPAddr:
		la, _ := la.(*UDPAddr)
		c, err = sd.dialUDP(ctx, la, ra)
	case *IPAddr:
		la, _ := la.(*IPAddr)
		c, err = sd.dialIP(ctx, la, ra)
	case *UnixAddr:
		la, _ := la.(*UnixAddr)
		c, err = sd.dialUnix(ctx, la, ra)
	default:
		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}}
	}
	if err != nil {
		return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer
	}
	return c, nil
}

// ListenConfig contains options for listening to an address.
type ListenConfig struct {
	// If Control is not nil, it is called after creating the network
	// connection but before binding it to the operating system.
	//
	// Network and address parameters passed to Control method are not
	// necessarily the ones passed to Listen. For example, passing "tcp" to
	// Listen will cause the Control function to be called with "tcp4" or "tcp6".
	Control func(network, address string, c syscall.RawConn) error

	// KeepAlive specifies the keep-alive period for network
	// connections accepted by this listener.
	// If zero, keep-alives are enabled if supported by the protocol
	// and operating system. Network protocols or operating systems
	// that do not support keep-alives ignore this field.
	// If negative, keep-alives are disabled.
	KeepAlive time.Duration
}

// Listen announces on the local network address.
//
// See func Listen for a description of the network and address
// parameters.
func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) {
	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
	if err != nil {
		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
	}
	sl := &sysListener{
		ListenConfig: *lc,
		network:      network,
		address:      address,
	}
	var l Listener
	la := addrs.first(isIPv4)
	switch la := la.(type) {
	case *TCPAddr:
		l, err = sl.listenTCP(ctx, la)
	case *UnixAddr:
		l, err = sl.listenUnix(ctx, la)
	default:
		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
	}
	if err != nil {
		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer
	}
	return l, nil
}

// ListenPacket announces on the local network address.
//
// See func ListenPacket for a description of the network and address
// parameters.
func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
	addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
	if err != nil {
		return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
	}
	sl := &sysListener{
		ListenConfig: *lc,
		network:      network,
		address:      address,
	}
	var c PacketConn
	la := addrs.first(isIPv4)
	switch la := la.(type) {
	case *UDPAddr:
		c, err = sl.listenUDP(ctx, la)
	case *IPAddr:
		c, err = sl.listenIP(ctx, la)
	case *UnixAddr:
		c, err = sl.listenUnixgram(ctx, la)
	default:
		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
	}
	if err != nil {
		return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer
	}
	return c, nil
}

// sysListener contains a Listen's parameters and configuration.
type sysListener struct {
	ListenConfig
	network, address string
}

// Listen announces on the local network address.
//
// The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
//
// For TCP networks, if the host in the address parameter is empty or
// a literal unspecified IP address, Listen listens on all available
// unicast and anycast IP addresses of the local system.
// To only use IPv4, use network "tcp4".
// The address can use a host name, but this is not recommended,
// because it will create a listener for at most one of the host's IP
// addresses.
// If the port in the address parameter is empty or "0", as in
// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
// The Addr method of Listener can be used to discover the chosen
// port.
//
// See func Dial for a description of the network and address
// parameters.
//
// Listen uses context.Background internally; to specify the context, use
// ListenConfig.Listen.
func Listen(network, address string) (Listener, error) {
	var lc ListenConfig
	return lc.Listen(context.Background(), network, address)
}

// ListenPacket announces on the local network address.
//
// The network must be "udp", "udp4", "udp6", "unixgram", or an IP
// transport. The IP transports are "ip", "ip4", or "ip6" followed by
// a colon and a literal protocol number or a protocol name, as in
// "ip:1" or "ip:icmp".
//
// For UDP and IP networks, if the host in the address parameter is
// empty or a literal unspecified IP address, ListenPacket listens on
// all available IP addresses of the local system except multicast IP
// addresses.
// To only use IPv4, use network "udp4" or "ip4:proto".
// The address can use a host name, but this is not recommended,
// because it will create a listener for at most one of the host's IP
// addresses.
// If the port in the address parameter is empty or "0", as in
// "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
// The LocalAddr method of PacketConn can be used to discover the
// chosen port.
//
// See func Dial for a description of the network and address
// parameters.
//
// ListenPacket uses context.Background internally; to specify the context, use
// ListenConfig.ListenPacket.
func ListenPacket(network, address string) (PacketConn, error) {
	var lc ListenConfig
	return lc.ListenPacket(context.Background(), network, address)
}


text:
@interface TransactionsViewController ()
@property (strong) AuthService *authService;
@property (strong) PendingTransactionsService *transactionService;
@property (strong) TransactionDetailService * transactionDetailService;
@property (strong) TransactionApprove * transactionApproveService;
@property (strong, nonatomic) NSMutableArray * accounts;

@property (strong, nonatomic) IBOutlet BCTableView *tableView;
@property (strong, nonatomic) UIRefreshControl *refreshControl;

@property (strong, nonatomic) IBOutlet BCTextField *txtApproveCode;
@property (nonatomic) int page;
@end

@implementation TransactionsViewController
- (BOOL)slideNavigationControllerShouldDisplayLeftMenu {
    return YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    [self initializeSearchController];

    // Init service
    _transactionService = [[PendingTransactionsService alloc] initWithDelegate:self authtoken:self.user.authtoken];

    _transactionDetailService = [[TransactionDetailService alloc] initWithDelegate:self authtoken:self.user.authtoken];

    _transactionApproveService = [[TransactionApprove alloc] initWithDelegate:self authtoken:self.user.authtoken];

    _refreshControl = [[UIRefreshControl alloc] init];
    [_refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:_refreshControl];

    [self.tableView becomeFirstResponder];

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTouchView)];

    [self.view addGestureRecognizer:recognizer];
    self.edgesForExtendedLayout = UIRectEdgeNone;

//    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setTitle:NSLocalizedString(@"Approve", @"")];
    _page = 1;
    [_transactionService getTransactionsPage:_page];
}

// Dissmiss the keyboard on tableView touches by making
// the view the first responder
- (void)didTouchView {
    [self.tableView becomeFirstResponder];
}

- (IBAction)btnAprroveClicked:(id)sender {
    [self didTouchView];
    UIActionSheet *approveAction = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"") destructiveButtonTitle:NSLocalizedString(@"Accept", @"") otherButtonTitles:nil];
    [approveAction showInView:self.view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma search controller
- (void)initializeSearchController {

    //instantiate a search results controller for presenting the search/filter results (will be presented on top of the parent table view)
    UITableViewController *searchResultsController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];

    searchResultsController.tableView.dataSource = self;

    searchResultsController.tableView.delegate = self;

    //instantiate a UISearchController - passing in the search results controller table
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];

    //this view controller can be covered by theUISearchController's view (i.e. search/filter table)
    self.definesPresentationContext = YES;

    //define the frame for the UISearchController's search bar and tint
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);

    self.searchController.searchBar.tintColor = [UIColor blueColor];

    //add the UISearchController's search bar to the header of this table
    self.tableView.tableHeaderView = self.searchController.searchBar;

    //this ViewController will be responsible for implementing UISearchResultsDialog protocol method(s) - so handling what happens when user types into the search bar
    self.searchController.searchResultsUpdater = self;

    //this ViewController will be responsisble for implementing UISearchBarDelegate protocol methods(s)
    self.searchController.searchBar.delegate = self;

}

#pragma mark - UISearchResultsUpdating

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchText = [self.searchController.searchBar text];

    //exit if there is no search text (i.e. user tapped on the search bar and did not enter text yet)
    if([searchText length] == 0) {
        _transactionService.accounts = [self deepMutableCopyOfArray:_accounts];

    }
    //handle when there is search text entered by the user
    else {
        searchText = [searchText lowercaseString];

        [_transactionService.accounts removeAllObjects];
        NSMutableArray *accs = [self deepMutableCopyOfArray:_accounts];

        for (Account *a in accs) {
            if (a.transfers) {
                NSMutableArray *temp = [[NSMutableArray alloc] init];
                for (Transaction *t in a.transfers) {
                    if ([t.searchContent containsString:searchText]) {
                        [temp addObject:t];
                    }
                }
                a.transfers = temp;
            }
            if (a.batchs) {
                NSMutableArray *temp = [[NSMutableArray alloc] init];
                for (Transaction *t in a.batchs) {
                    if ([t.searchContent containsString:searchText]) {
                        [temp addObject:t];
                    }
                }
                a.batchs = temp;
            }
            if (a.others) {
                NSMutableArray *temp = [[NSMutableArray alloc] init];
                for (Transaction *t in a.others) {
                    if ([t.searchContent containsString:searchText]) {
                        [temp addObject:t];
                    }
                }
                a.others = temp;
            }

            if ([a.transfers count] != 0 || [a.batchs count] != 0 || [a.others count] != 0) {
                [_transactionService.accounts addObject:a];
            }
        }

        //now that the tableSections and tableSectionsAndItems properties are updated, reload the UISearchController's tableview
        [((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];

    }
}

#pragma mark - UISearchBarDelegate methods

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    _transactionService.accounts = [self deepMutableCopyOfArray:_accounts];
    [self.tableView reloadData];

    [self.tableView becomeFirstResponder];
}

#pragma mark UIsearch filter data
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    return YES;
}

#pragma mark refresh control
- (void)refresh:(UIRefreshControl *)refreshControl {
    [_transactionService getTransactionsPage:_page];
}

#pragma mark - Service response

- (void)startRequest:(BaseService *)service {
    if (service == _transactionDetailService) {
        // Show indicator
    }
    [super startRequest:service];
}

- (void)successRequest:(BaseService *)service response:(NSDictionary *)data
{
    if (service == _authService && [_authService parser:data context:self.managedObjectContext]) {

    }
    if (service == _transactionService && [_transactionService parser:data context:nil]) {
        _accounts = [self deepMutableCopyOfArray:_transactionService.accounts];
        [_tableView reloadData];
        _page++;
    }

    if (service == _transactionDetailService && [_transactionDetailService parser:data context:nil]) {
        [_tableView reloadData];
    }

    if (service == _transactionApproveService) {
        if([_transactionApproveService parser:data context:nil]) {
            TransactionResultViewController *resultViewController = [[TransactionResultViewController alloc] init];
            resultViewController.listFaild = _transactionApproveService.listFaild;
            resultViewController.listSucc = _transactionApproveService.listSucc;
            resultViewController.user = self.user;
            [self pushViewController:resultViewController animated:YES title:NSLocalizedString(@"Result", @"")];
        } else {
            [[[UIAlertView alloc] initWithTitle:@"Cảnh báo" message:@"Mã xác nhận không đúng" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        }

    }
    [super successRequest:service response:data];
}

- (void)finishRequest:(BaseService *)service {
    if (service == _transactionService) {
        [_refreshControl endRefreshing];
    }

    if (service == _transactionDetailService) {
        // Hide indicator
    }

    [super finishRequest:service];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_transactionService.accounts == nil) {
        return 0;
    }
    return [_transactionService.accounts count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 80.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TransactionHeaderView *headerView = [tableView dequeueReusableCellWithIdentifier:@"header"];
    if (headerView == nil) {
        [tableView registerNib:[UINib nibWithNibName:@"HeaderSectionView" bundle:nil] forCellReuseIdentifier:@"header"];
        headerView = [tableView dequeueReusableCellWithIdentifier:@"header"];

    }
    headerView.delegate = self;
    Account *account = [_transactionService.accounts objectAtIndex:section];
    [headerView cellWithData:account];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Account *account = [_transactionService.accounts objectAtIndex:indexPath.section];
    float titleHeight = 0.0f;
    if (indexPath.row == 0 || indexPath.row == account.transfers.count || indexPath.row == (account.transfers.count + account.batchs.count)) {
        titleHeight = 15.0f;
    }
    Transaction *transaction = nil;

    if (indexPath.row < account.transfers.count) {
        transaction = [account.transfers objectAtIndex:indexPath.row];
    } else if (indexPath.row >= account.transfers.count && indexPath.row < (account.transfers.count + account.batchs.count)) {
        transaction = [account.batchs objectAtIndex:(indexPath.row - account.transfers.count)];
    } else {
        transaction = [account.others objectAtIndex:(indexPath.row - account.transfers.count - account.batchs.count)];

    }
    return [TransactionTableViewCell heightForCellWithData:transaction] + titleHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(!_transactionService.accounts) return 0;
    Account *account = [_transactionService.accounts objectAtIndex:section];
    return account.transfers.count + account.batchs.count + account.others.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"transaction"];
    if (cell == nil) {
        [tableView registerNib:[UINib nibWithNibName:@"TransactionTableViewCell" bundle:nil] forCellReuseIdentifier:@"transaction"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"transaction"];

    }
    cell.delegate = self;
    Account *account = [_transactionService.accounts objectAtIndex:indexPath.section];
    Transaction *transaction = nil;

    if (indexPath.row < account.transfers.count) {
        transaction = [account.transfers objectAtIndex:indexPath.row];
    } else if (indexPath.row >= account.transfers.count && indexPath.row < (account.transfers.count + account.batchs.count)) {
        transaction = [account.batchs objectAtIndex:(indexPath.row - account.transfers.count)];
    } else {
        transaction = [account.others objectAtIndex:(indexPath.row - account.transfers.count - account.batchs.count)];

    }

    [cell cellWithData:transaction];
    return cell;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self didTouchView];
}

#pragma mark cell and header delegate

- (void)requestDetail:(TransactionTableViewCell *)cell transaction:(Transaction *)transaction
{
    [_transactionDetailService getDetailTransaction:transaction approved:@"0"];
}

- (void)didChangeExpand {
    [_tableView reloadData];
}

- (void)didChangeCheckingValue {
    [_tableView reloadData];
}

- (void)didChangeButtonCheckAll:(TransactionHeaderView *)header {
    [_tableView reloadData];
}

- (void)didOutOfMoney{
    [[[UIAlertView alloc] initWithTitle:@"KHÔNG ĐỦ SỐ DƯ" message:@"Bạn phải hủy bỏ một số giao dịch" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != 0) {
        return;
    }
    if ([_txtApproveCode.text length] == 0) {
        [[[UIAlertView alloc] initWithTitle:@"Cảnh báo" message:@"Bạn chưa nhập mã xác nhận" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        return;
    }
    NSMutableString *strBuilder = [[NSMutableString alloc] init];
    for (Account *a in _transactionService.accounts) {
        if (a.available < 0) {
            [[[UIAlertView alloc] initWithTitle:@"KHÔNG ĐỦ SỐ DƯ" message:@"Bạn phải hủy bỏ một số giao dịch" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
            return;
        }
        NSMutableArray *array = [[NSMutableArray alloc] initWithArray:a.transfers];
        [array addObjectsFromArray:a.batchs];
        [array addObjectsFromArray:a.others];
        for (Transaction *t in array) {
            if(t.checked) [strBuilder appendFormat:@"%@|",t.tranSn];
        }

    }
    if ([strBuilder length] == 0) {
        [[[UIAlertView alloc] initWithTitle:@"Cảnh báo" message:@"Bạn phải chọn ít nhất 1 giao dịch" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
        return;
    }
    [strBuilder deleteCharactersInRange:NSMakeRange([strBuilder length] - 1, 1)];
    [_transactionApproveService approveCode:_txtApproveCode.text transactions:strBuilder];
    _txtApproveCode.text = @"";
}

#pragma mark deep copy
- (NSMutableArray*)deepMutableCopyOfArray:(NSMutableArray*) array
{
    NSMutableArray *outputArray = [[NSMutableArray alloc] initWithArray:array copyItems:YES];
//
//    for (int i = 0; i < [outputArray count]; i++) {
//        Account *oa = [outputArray objectAtIndex:i];
//        Account *ia = [array objectAtIndex:i];
//        oa.transfers = [[[NSMutableArray alloc] initWithArray:ia.transfers] mutableCopy];
//        oa.batchs = [[[NSMutableArray alloc] initWithArray:ia.batchs] mutableCopy];
//
//        oa.others = [[[NSMutableArray alloc] initWithArray:ia.others] mutableCopy];
//
//        for (int j = 0; j < [oa.batchs count]; j++) {
//            Transaction *ot = [oa.batchs objectAtIndex:j];
//            Transaction *it = [ia.batchs objectAtIndex:j];
//            ot.benefits = [[[NSArray alloc] initWithArray:it.benefits] copy];
//        }
//    }
    return outputArray;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Parseq.Combinators
{
    public static class Prims
    {
        public static Parser<TToken, Unit> EndOfInput<TToken>()
        {
            return stream => stream.Current.HasValue
                ? Reply.Failure<TToken, Unit>(stream, "Failure: Prims.EndOfInput")
                : Reply.Success<TToken, Unit>(stream, Parseq.Unit.Instance);
        }

        public static Parser<TToken, Unit> Unit<TToken>()
        {
            return Parser.Return<TToken, Unit>(Parseq.Unit.Instance);
        }

        public static Parser<TToken, TToken> Any<TToken>()
        {
            return stream => stream.Current.HasValue
                ? Reply.Success<TToken, TToken>(stream.MoveNext(), stream.Current.Value.Item0)
                : Reply.Failure<TToken, TToken>(stream, "Failure: Prims.Any");
        }

        public static Parser<TToken, TToken> Satisfy<TToken>(TToken token)
            where TToken : IEquatable<TToken>
        {
            return stream => stream.Current.HasValue && stream.Current.Value.Item0.Equals(token)
                ? Reply.Success<TToken, TToken>(stream.MoveNext(), stream.Current.Value.Item0)
                : Reply.Failure<TToken, TToken>(stream, "Failure: Prims.Satisfy");
        }

        public static Parser<TToken, TToken> Satisfy<TToken>(Func<TToken, Boolean> predicate)
        {
            return stream => stream.Current.HasValue && predicate(stream.Current.Value.Item0)
                ? Reply.Success<TToken, TToken>(stream.MoveNext(), stream.Current.Value.Item0)
                : Reply.Failure<TToken, TToken>(stream, "Failure: Prims.Satisfy");
        }

        public static Parser<TToken, TToken> OneOf<TToken>(IEnumerable<TToken> candidates)
            where TToken : IEquatable<TToken>
        {
            return Combinator.Choice(candidates.Select(Prims.Satisfy<TToken>));
        }

        public static Parser<TToken, TToken> OneOf<TToken>(params TToken[] candidates)
            where TToken : IEquatable<TToken>
        {
            return Prims.OneOf(candidates.AsEnumerable());
        }

        public static Parser<TToken, TToken> NoneOf<TToken>(IEnumerable<TToken> candidates)
            where TToken : IEquatable<TToken>
        {
            return Combinator.Sequence(candidates.Select(token => Prims.Satisfy(token).Not())).Bindr(Prims.Any<TToken>());
        }

        public static Parser<TToken, TToken> NoneOf<TToken>(params TToken[] candidates)
            where TToken : IEquatable<TToken>
        {
            return Prims.NoneOf(candidates.AsEnumerable());
        }

        public static Parser<TToken, IEnumerable<T>> Empty<TToken, T>()
        {
            return Parser.Return<TToken, IEnumerable<T>>(Enumerable.Empty<T>());
        }

        public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(
            this Parser<TToken, IEnumerable<T>> parser0,
                 Parser<TToken, IEnumerable<T>> parser1)
        {
            return InternalCombinator.Append(parser0.Map(Seq.Of), parser1.Map(Seq.Of))
                .Map(Seq.AsEnumerable);
        }

        public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(
            this Parser<TToken, IEnumerable<T>> parser0,
                 Parser<TToken, T> parser1)
        {
            return InternalCombinator.Append(parser0.Map(Seq.Of), parser1)
                .Map(Seq.AsEnumerable);
        }

        public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(
            this Parser<TToken, IEnumerable<T>> parser0,
                 Parser<TToken, IOption<IEnumerable<T>>> parser1)
        {
            return InternalCombinator.Append(
                parser0.Map(Seq.Of),
                parser1.Map(optionValue => optionValue.Map(Seq.Of)))
                .Map(Seq.AsEnumerable);
        }

        public static Parser<TToken, IEnumerable<T>> Append<TToken, T>(
            this Parser<TToken, IEnumerable<T>> parser0,
                 Parser<TToken, IOption<T>> parser1)
        {
            return InternalCombinator.Append(parser0.Map(Seq.Of), parser1)
                .Map(Seq.AsEnumerable);
        }
    }
}


text:
module Math
where

type Flt = Double

tolerance :: (Ord a, Num a) => a -> a -> Bool
tolerance a d = abs a < d

diffTolerance :: (Ord a, Num a) => a -> a -> a -> Bool
diffTolerance a b d = abs (a - b) < d

invalidFloat :: (RealFloat a) => a -> Bool
invalidFloat f = isNaN f || isInfinite f || isNegativeZero f


text:
package org.telegram.api.messages.stickers.featured;

/**
 * @author Ruben Bermudez
 * @version 1.0
 * @brief TODO
 * @date 07 of August of 2016
 */
public class TLMessagesFeaturedStickersNotModified extends TLAbsMessagesFeaturedStickers {
    public static final int CLASS_ID = 0x4ede3cf;

    public TLMessagesFeaturedStickersNotModified() {
        super();
    }

    @Override
    public int getClassId() {
        return CLASS_ID;
    }

    @Override
    public String toString() {
        return "messages.featuredStickersNotModified#4ede3cf";
    }
}


text:
<?php
namespace Skrz\Bundle\BunnyBundle;

class BunnyException extends \Exception
{
}


text:
require "spec_helper"

describe Gitlab::Git::Commit do
  let(:commit) { create(:project_with_code).repository.commit }

  describe "Commit info" do
    before do
      @committer = double(
        email: 'mike@smith.com',
        name: 'Mike Smith'
      )

      @author = double(
        email: 'john@smith.com',
        name: 'John Smith'
      )

      @raw_commit = double(
        id: "bcf03b5de6abcf03b5de6c",
        author: @author,
        committer: @committer,
        committed_date: Date.yesterday,
        authored_date: Date.yesterday,
        parents: [],
        message: 'Refactoring specs'
      )

      @commit = Gitlab::Git::Commit.new(@raw_commit)
    end

    it { @commit.short_id.should == "bcf03b5de6a" }
    it { @commit.safe_message.should == @raw_commit.message }
    it { @commit.created_at.should == @raw_commit.committed_date }
    it { @commit.author_email.should == @author.email }
    it { @commit.author_name.should == @author.name }
    it { @commit.committer_name.should == @committer.name }
    it { @commit.committer_email.should == @committer.email }
    it { @commit.different_committer?.should be_true }
  end
end


text:
module.exports = {
    ____types: "jsObject",
    "holisticView_SoftwareFactory": {
        ____label: "Software Factory Descriptor Render Request",
        ____description: "Request to render to a software factory datasheet descriptor as HTML.",
        ____types: "jsObject",
        introMarkdownSource: {
            ____label: "Introduction Markdown Content",
            ____description: "Markdown-format introduction for this software factory.",
            ____types: "jsArray",
            ____defaultValue: [
                "### Under Construction",
                "Still working on this section..."
            ],
            markdown: {
                ____label: "Markdown Content Line",
                ____description: "A single line of markdown content.",
                ____accept: "jsString",

            }
        }
    }
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Hydra.SharedCache.Registration
{
    //
    // **********************************************************************
    /// <summary>
    /// Program Instance
    /// </summary>
    // **********************************************************************
    //
    static class Program
    {
        //
        // **********************************************************************
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        // **********************************************************************
        //
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Register());
        }
    }
}


text:
@extends('layouts.app')

@section('htmlheader_title')
    {!! $headerText = 'Tags'!!}
@endsection

@section('main-content')

    @include('partials._messages')

    @include('partials.datatables.html')

@endsection

@section('custom-js')

    <script>
        endpointUrl = '{{$getRowsUrl}}';
    </script>
    @include('partials.datatables.js')

@endsection


text:
PressureConverter
=================

An iOS application to convert kgf/cm2 into psi.


text:
/*global define*/
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
  "units": {
    "miles": "Mylios",
    "kilometers": "Kilometrai",
    "feet": "Pėdos",
    "meters": "Metrai"
  },
  "layerSetting": {
    "layerSettingTabTitle": "Paieškos nuostatos",
    "buttonSet": "Nustatyti",
    "selectLayersLabel": "Pasirinkite sluoksnį",
    "selectLayersHintText": "Pastaba: naudojama plotų sluoksniui ir jo susijusių taškų sluoksniui pasirinkti.",
    "selectPrecinctSymbolLabel": "Pasirinkti poligono paryškinimo simbolį",
    "selectGraphicLocationSymbol": "Adreso arba vietos simbolis",
    "graphicLocationSymbolHintText": "Patarimas: ieškoto adreso arba spustelėtos vietos simbolis",
    "precinctSymbolHintText": "Patarimas: naudojama pasirinkto poligono simboliui rodyti",
    "selectColorForPoint": "Pasirinkti spalvą taškui paryškinti",
    "selectColorForPointHintText": "Užuomina: naudojama norint paryškinti pasirinkto taško spalvą"
  },
  "searchSourceSetting": {
    "searchSourceSettingTabTitle": "Ieškoti šaltinio parametrų",
    "searchSourceSettingTitle": "Ieškoti šaltinio parametrų",
    "searchSourceSettingTitleHintText": "Pridėti ir sukonfigūruoti geokodavimo paslaugas arba elementų sluoksnius kaip paieškos šaltinius. Šie nurodyti šaltiniai nustato, ko galima ieškoti paieškos lauke",
    "addSearchSourceLabel": "Pridėti paieškos šaltinį",
    "featureLayerLabel": "Elementų sluoksnis",
    "geocoderLabel": "Geokoderis",
    "nameTitle": "Pavadinimas",
    "generalSettingLabel": "Bendrieji parametrai",
    "allPlaceholderLabel": "Vietos rezervavimo tekstas visų elementų paieškai:",
    "allPlaceholderHintText": "Užuomina: įveskite tekstą, kuris bus rodomas kaip vietos rezervavimo ženklas ieškant visų sluoksnių ir geokoderio",
    "generalSettingCheckboxLabel": "Rodyti kontekstinį langą, skirtą rastam elementui arba vietai",
    "countryCode": "Šalies arba regiono kodas (-ai)",
    "countryCodeEg": "pvz., ",
    "countryCodeHint": "Jei ši reikšmė nebus nurodyta, bus ieškomos visos šalys ir regionai",
    "questionMark": "?",
    "searchInCurrentMapExtent": "Ieškoti tik esamo žemėlapio aprėptyje",
    "zoomScale": "Mastelis",
    "locatorUrl": "Geokoderio URL",
    "locatorName": "Geokoderio pavadinimas",
    "locatorExample": "Pavyzdys",
    "locatorWarning": "Ši geokodavimo paslaugos versija nepalaikoma. Valdiklis palaiko 10.0 arba vėlesnę geokodavimo paslaugą.",
    "locatorTips": "Pasiūlymų nėra, nes geokodavimo paslauga nepalaiko siūlomų galimybių.",
    "layerSource": "Sluoksnio šaltinis",
    "setLayerSource": "Nustatyti sluoksnio šaltinį",
    "setGeocoderURL": "Nustatyti geokoderio URL",
    "searchLayerTips": "Pasiūlymų nėra, nes elementų paslauga nepalaiko puslapių numeravimo galimybės.",
    "placeholder": "Naudotojui rodomas tekstas",
    "searchFields": "Paieškos laukai",
    "displayField": "Rodyti lauką",
    "exactMatch": "Tikslus atitikmuo",
    "maxSuggestions": "Maksimalūs pasiūlymai",
    "maxResults": "Maksimalus rezultatų skaičius",
    "enableLocalSearch": "Įgalinti vietinę paiešką",
    "minScale": "Minimalus mastelis",
    "minScaleHint": "Vietinė paieška bus taikoma, kai žemėlapio mastelis bus didesnis nei šis",
    "radius": "Spindulys",
    "radiusHint": "Nurodo ploto aplink dabartinį žemėlapio centrą spindulį, naudojamą geokodavimo objektams išdėstyti taip, kad arčiausiai vietos esantys objektai būtų pateikiami pirmiausia.",
    "meters": "Metrai",
    "setSearchFields": "Nustatyti paieškos laukus",
    "set": "Nustatyti",
    "fieldName": "Pavadinimas",
    "invalidUrlTip": "URL ${URL} yra neteisingas arba nepasiekiamas.",
    "invalidSearchSources": "Netinkami paieškos šaltinio parametrai"
  },
  "layerSelector": {
    "selectPolygonLayerLabel": "Pasirinkti poligono sluoksnį",
    "selectPolygonLayerHintText": "Patarimas: naudojama poligono sluoksniui pasirinkti.",
    "selectRelatedPointLayerLabel": "Pasirinkti su poligono sluoksniu susijusį taškų sluoksnį",
    "selectRelatedPointLayerHintText": "Pastaba: naudojama su poligono sluoksniu susijusiam taškų sluoksniui pasirinkti",
    "polygonLayerNotHavingRelatedLayer": "Pasirinkite poligono sluoksnį, kuriame yra susijusių taškų sluoksnis.",
    "errorInSelectingPolygonLayer": "Pasirinkite poligono sluoksnį, kuriame yra susijusių taškų sluoksnis.",
    "errorInSelectingRelatedLayer": "Pasirinkite su poligono sluoksniu susijusį taškų sluoksnį"
  },
  "routeSetting": {
    "routeSettingTabTitle": "Krypčių nustatymai",
    "routeServiceUrl": "Maršruto paslauga",
    "buttonSet": "Nustatyti",
    "routeServiceUrlHintText": "Patarimas: spustelėkite "Nustatyti", jei norite naršyti ir pasirinkti tinklo analizės maršruto paslaugą",
    "directionLengthUnit": "Krypties ilgio vienetai",
    "unitsForRouteHintText": "Patarimas: naudojama maršruto nurodytiems vienetams rodyti",
    "selectRouteSymbol": "Pasirinkti maršruto rodymo simbolį",
    "routeSymbolHintText": "Patarimas: naudojamas maršruto linijos simboliui rodyti",
    "routingDisabledMsg": "Jei norite įjungti nuorodas, įsitikinkite, kad maršrutas įjungtas ArcGIS Online elemente.",
    "enableDirectionLabel": "Įgalinti kryptis",
    "enableDirectionText": "Pastaba: pažymėkite, jei norite valdyklyje įgalinti kryptis"
  },
  "networkServiceChooser": {
    "arcgislabel": "Pridėti iš ArcGIS Online",
    "serviceURLabel": "Pridėti paslaugos URL",
    "routeURL": "Maršruto URL",
    "validateRouteURL": "Tikrinti",
    "exampleText": "Pavyzdys",
    "hintRouteURL1": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/",
    "hintRouteURL2": "https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
    "invalidRouteServiceURL": "Nurodykite galiojančią maršruto paslaugą.",
    "rateLimitExceeded": "Viršytas apribojimo limitas. Pabandykite dar kartą vėliau.",
    "errorInvokingService": "Naudotojo vardas arba slaptažodis neteisingas."
  },
  "symbolPickerPreviewText": "Peržiūra:",
  "showToolToSelectLabel": "Vietos nustatymo mygtukas",
  "showToolToSelectHintText": "Užuomina: pateikiamas mygtukas, skirtas vietai žemėlapyje nustatyti, bet ne visada spustelėjus žemėlapį nustatoma vieta"
});