text:
package desugar

import "github.com/cloe-lang/cloe/src/lib/ast"

type names map[string]bool

func newNames(ss ...string) names {
	ns := make(names, len(ss))

	for _, s := range ss {
		ns.add(s)
	}

	return ns
}

func (ns names) slice() []string {
	ms := make([]string, 0, len(ns))

	for n := range ns {
		ms = append(ms, n)
	}

	return ms
}

func (ns names) add(n string) {
	ns[n] = true
}

func (ns names) copy() names {
	ms := newNames()

	for n := range ns {
		ms.add(n)
	}

	return ms
}

func (ns names) merge(ms names) {
	for m := range ms {
		ns.add(m)
	}
}

func (ns names) delete(n string) {
	delete(ns, n)
}

func (ns names) subtract(ms names) {
	for m := range ms {
		ns.delete(m)
	}
}

func (ns names) include(n string) bool {
	_, ok := ns[n]
	return ok
}

// findInDefFunction finds names in a let-function node. This assumes that a
// given let-function statement does not define its function recursively.
func (ns names) findInDefFunction(f ast.DefFunction) names {
	ns = ns.copy()
	ns.subtract(signatureToNames(f.Signature()))

	ms := newNames()

	for _, l := range f.Lets() {
		switch l := l.(type) {
		case ast.LetVar:
			ms.merge(ns.findInLetVar(l))
			ns.delete(l.Name())
		case ast.DefFunction:
			ns.delete(l.Name())
			ms.merge(ns.findInDefFunction(l))
		default:
			panic("unreachable")
		}
	}

	ms.merge(ns.findInExpression(f.Body()))
	return ms
}

// findInLetVar finds names in a let-variable node. This assumes that a given
// let-variable statement does not define its variable recursively.
func (ns names) findInLetVar(l ast.LetVar) names {
	return ns.findInExpression(l.Expr())
}

func (ns names) findInExpression(x interface{}) names {
	switch x := x.(type) {
	case string:
		if ns.include(x) {
			return newNames(x)
		}

		return newNames()
	case ast.AnonymousFunction:
		ns := ns.copy()
		ns.subtract(signatureToNames(x.Signature()))
		return ns.findInExpression(x.Body())
	case ast.App:
		ms := ns.findInExpression(x.Function())
		ms.merge(ns.findInExpression(x.Arguments()))
		return ms
	case ast.Arguments:
		ms := newNames()

		for _, p := range x.Positionals() {
			ms.merge(ns.findInExpression(p.Value()))
		}

		for _, k := range x.Keywords() {
			ms.merge(ns.findInExpression(k.Value()))
		}

		return ms
	case ast.Switch:
		ms := ns.findInExpression(x.Value())

		for _, c := range x.Cases() {
			ms.merge(ns.findInExpression(c.Value()))
		}

		ms.merge(ns.findInExpression(x.DefaultCase()))

		return ms
	}

	panic("unreachable")
}


text:
class MainWindow : public QWidget
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);

signals:
    void disconnectPatch();
    void openBlacklistPatch();

private:
    QGridLayout *mainLayout;
    QPushButton *disconnectButton;
    QPushButton *openBlacklistButton;
    QPushButton *openModsButton;
    QPushButton *openChatButton;

private slots:
    void disconnectRelay();
    void openBlacklistRelay();

};

#endif

redpajama_set_name: RedPajamaGithub


text:
require 'net/http'
require 'net/https'
require 'cgi'
require 'openssl'
require 'base64'
require 'forwardable'
require 'time'
require 'json'

require 'twilio-ruby/version' unless defined?(Twilio::VERSION)
require 'rack/twilio_webhook_authentication'

require 'twilio-ruby/util'
require 'twilio-ruby/security/request_validator'
require 'twilio-ruby/util/configuration'

Dir[File.join(__dir__, 'twilio-ruby/framework/*.rb')].sort.each do |file|
  require file
end

module Twilio
  extend SingleForwardable

  autoload :JWT, File.join(__dir__, 'twilio-ruby', 'jwt', 'jwt.rb')
  autoload :TwiML, File.join(__dir__, 'twilio-ruby', 'twiml', 'twiml.rb')
  autoload :HTTP, File.join(__dir__, 'twilio-ruby', 'http.rb')
  autoload :REST, File.join(__dir__, 'twilio-ruby', 'rest.rb')

  def_delegators :configuration, :account_sid, :auth_token, :http_client, :region, :edge, :logger

  ##
  # Pre-configure with account SID and auth token so that you don't need to
  # pass them to various initializers each time.
  def self.configure(&block)
    yield configuration
  end

  ##
  # Returns an existing or instantiates a new configuration object.
  def self.configuration
    @configuration ||= Util::Configuration.new
  end

  private_class_method :configuration
end


text:
class LogManagerImplementation
{
public:
	LogManagerImplementation();

	// Must be implemented because std::mutex is non-copyable, see
	// http://stackoverflow.com/questions/14263836/why-does-stdmutex-create-a-c2248-when-used-in-a-struct-with-windows-socket
	// for more details
	LogManagerImplementation(const LogManagerImplementation& other);
	void operator=(const LogManagerImplementation& other);

	~LogManagerImplementation();

	void addLogger(std::shared_ptr<Logger> logger);
	void removeLogger(std::shared_ptr<Logger> logger);
	void removeLoggersByType(const std::string& type);
	int getLoggerCount() const;

	void logInfo(
		const std::string& message,
		const std::string& file,
		const std::string& function,
		const unsigned int line
	);
	void logWarning(
		const std::string& message,
		const std::string& file,
		const std::string& function,
		const unsigned int line
	);
	void logError(
		const std::string& message,
		const std::string& file,
		const std::string& function,
		const unsigned int line
	);

private:
	tm getTime();

	std::vector<std::shared_ptr<Logger> > m_loggers;

	mutable std::mutex m_loggerMutex;
};

#endif // LOG_MANAGER_IMPLEMENTATION_H


text:
When(/^the client requests immunization for the patient "(.*?)" in FHIR format$/) do |pid|
  temp = QueryRDKAll.new("Immunization")
  temp.add_parameter("subject.identifier", pid)
  #temp.add_parameter("domain", "imun")
  temp.add_acknowledge("true")
  p temp.path
  @response = HTTPartyWithBasicAuth.get_with_authorization(temp.path)
end

When(/^the client requests immunization for that sensitive patient "(.*?)"$/) do |pid|
  temp = QueryRDKAll.new("Immunization")
  temp.add_parameter("subject.identifier", pid)
  #temp.add_parameter("domain", "imun")
  temp.add_acknowledge("false")
  p temp.path
  @response = HTTPartyWithBasicAuth.get_with_authorization(temp.path)
end

When(/^the client breaks glass and repeats a request for immunization for that patient "(.*?)"$/) do |pid|
  temp = QueryRDKAll.new("Immunization")
  temp.add_parameter("subject.identifier", pid)
  #temp.add_parameter("domain", "imun")
  temp.add_acknowledge("true")
  p temp.path
  @response = HTTPartyWithBasicAuth.get_with_authorization(temp.path)
end

When(/^the client requests "(.*?)" immunization for the patient "(.*?)" in FHIR format$/) do |limit, pid|
  temp = QueryRDKAll.new("Immunization")
  temp.add_parameter("subject.identifier", pid)
  temp.add_parameter("limit", limit)
  temp.add_acknowledge("true")
  p temp.path
  @response = HTTPartyWithBasicAuth.get_with_authorization(temp.path)
end


text:
package c01

object Runner {
  def number1FromInt(n: Int): Number1 = n match {
    case n1 if n1 > 0 => Number1Positive(number1FromInt(n1 - 1))
    case 0            => Number1Zero
  }
  def number5FromInt(n: Int): Number5 = n match {
    case n1 if n1 > 0 => Number5Positive(number5FromInt(n1 - 1))
    case 0            => Number5Zero
  }
  def main(args: Array[String]): Unit = {
    assert(number1FromInt(0).method1(BottomNumber0) == number5FromInt(1))
    assert(number1FromInt(1).method1(BottomNumber0) == number5FromInt(3))
    assert(number1FromInt(2).method1(BottomNumber0) == number5FromInt(9))
    assert(number1FromInt(3).method1(BottomNumber0) == number5FromInt(27))
    assert(number1FromInt(4).method1(BottomNumber0) == number5FromInt(81))
    assert(number1FromInt(5).method1(BottomNumber0) == number5FromInt(243))
    assert(number1FromInt(6).method1(BottomNumber0) == number5FromInt(729))
    assert(number1FromInt(7).method1(BottomNumber0) == number5FromInt(2187))
    assert(number1FromInt(8).method1(BottomNumber0) == number5FromInt(6561))
    assert(number1FromInt(9).method1(BottomNumber0) == number5FromInt(19683))  // 3 ^ 9 = 19683
    assert(number1FromInt(10).method1(BottomNumber0) == number5FromInt(59049)) // 3 ^ 10 = 59049
  }
}


text:
namespace ombt {

// allocate
Inference *
Inference::allocate(const Program &program)
{
    return new Inference(program);
}

// ctors and dtor
Inference::Inference():
    error_(),
    program_(),
    BaseObject()
{
}

Inference::Inference(const Program &program):
    error_(),
    program_(program),
    BaseObject()
{
}

Inference::Inference(const Inference &src):
    error_(src.error_),
    program_(src.program_),
    BaseObject(src)
{
}

Inference::~Inference()
{
}

// assignment
Inference &
Inference::operator=(const Program &program)
{
    program_ = program;
    return(*this);
}

Inference &
Inference::operator=(const Inference &rhs)
{
    if (this != &rhs)
    {
        BaseObject::operator=(rhs);
        error_ = rhs.error_;
        program_ = rhs.program_;
    }
    return(*this);
}

// output operators
std::ostream &
operator<<(std::ostream &os, const Inference &p)
{
    return os;
}

}


text:
package org.mcavallo.opencloud.filters;

import org.mcavallo.opencloud.Tag;

/**
 * Filters tags that don't match a given regular expression
 */
public class RegExFilter extends TagFilter {

	private static final long serialVersionUID = 1L;
	private String regEx = null;

	public RegExFilter(String regEx) {
		setRegEx(regEx);
	}

	@Override
	public boolean accept(Tag tag) {
		if (tag == null || tag.getName() == null)
			return false;

		if (tag.getName().matches(regEx))
			return true;
		else
			return false;
	}

	/**
	 * @return The regular expression
	 */
	public String getRegEx() {
		return regEx;
	}

	/**
	 * Sets the regular expression
	 * @param regEx The regular expression to set
	 */
	public void setRegEx(String regEx) {
		this.regEx = regEx;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((regEx == null) ? 0 : regEx.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final RegExFilter other = (RegExFilter) obj;
		if (regEx == null) {
			if (other.regEx != null)
				return false;
		} else if (!regEx.equals(other.regEx))
			return false;
		return true;
	}

}


text:
using PlanterApp.Applications.ViewModels;
using PlanterApp.Applications.Views;
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Waf.Applications;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace PlanterApp.Presentation.Views
{
    [Export(typeof(IArchitectureView))]
    public partial class ArchitectureView : UserControl, IArchitectureView
    {
        private IArchitectureItemModel _lastItem;
        //private readonly Lazy<ArchitectureViewModel> _viewModel;

        public ArchitectureView()
        {
            InitializeComponent();
            //_viewModel = new Lazy<ArchitectureViewModel>(() => ViewHelper.GetViewModel<ArchitectureViewModel>(this));
        }

        private void OnNodeSelected(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

            //var model = _viewModel.Value;

            if (/*model == null ||*/ e.NewValue == null)
            {
                return;
            }

            var item = e.NewValue as IArchitectureItemModel;

            if (item != null)
            {
                if (_lastItem != null)
                {
                    PropertyChangedEventManager.RemoveHandler(_lastItem, OnRefreshInputBindings, "PlanterMenuItems");
                }

                PropertyChangedEventManager.AddHandler(item, OnRefreshInputBindings, "PlanterMenuItems");

                OnRefreshInputBindings(item, null);

                _lastItem = item;
            }
        }

        private void OnRefreshInputBindings(object sender, PropertyChangedEventArgs e)
        {
            var item = sender as IArchitectureItemModel;
            if (item != null)
            {
                InputBindings.Clear();

                var itemBindings = item.PlanterMenuItems;

                if (itemBindings != null)
                {
                    InputBindings.AddRange(itemBindings);
                }
            }
        }
    }
}


text:
package com.site.blog.my.core.service;

import com.site.blog.my.core.entity.BlogComment;
import com.site.blog.my.core.util.PageQueryUtil;
import com.site.blog.my.core.util.PageResult;

public interface CommentService {
    /**
     * 添加评论
     *
     * @param blogComment
     * @return
     */
    Boolean addComment(BlogComment blogComment);

    /**
     * 后台管理系统中评论分页功能
     *
     * @param pageUtil
     * @return
     */
    PageResult getCommentsPage(PageQueryUtil pageUtil);

    int getTotalComments();

    /**
     * 批量审核
     *
     * @param ids
     * @return
     */
    Boolean checkDone(Integer[] ids);

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    Boolean deleteBatch(Integer[] ids);

    /**
     * 添加回复
     *
     * @param commentId
     * @param replyBody
     * @return
     */
    Boolean reply(Long commentId, String replyBody);

    /**
     * 根据文章id和分页参数获取文章的评论列表
     *
     * @param blogId
     * @param page
     * @return
     */
    PageResult getCommentPageByBlogIdAndPageNum(Long blogId, int page);
}


text:
"""
Parse FDR data from trace files.

Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-10-19 15:19:51 -0500 (Wed, 19 Oct 2011) $
* $LastChangedRevision: 5216 $

:author: Ketan Mandke <kmandke@mail.utexas.edu>

:copyright:
    Copyright 2009-2011 The University of Texas at Austin

    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.
"""
__docformat__ = "restructuredtext en"

from wins import *
from wins.ieee80211 import *

from optparse import OptionParser
import sys

import numpy as np

def read_trace(options, tracefile):
    # load trace from file
    tr = Trace()
    tr.read(tracefile)
    # return trace
    return tr

def hasfield(event, *args):
    """Check if event has all the specified arguments."""
    ok = all([(a in event) for a in args])
    return ok

def parse_info(options, trace, usemodel=False):
    # (data, param) variables
    data = []
    param = {'mcs': None, 'plen': None}
    rmsdelay = []
    # event parameters
    phyargs     = ('dot11n-sinr', 'dot11n-channel-fading')
    hydradetect = ('dot11n-detect', )
    modeldetect = ('dot11n-model-fdr', 'dot11n-model-detect')
    # paramaters for logging data
    currpkt = None  # current packet being considered by parsing loop
    for e in trace.events:
        # check timestamp - [tmin, tmax]
        ts = float(e['ts'])
        if (ts<options.tmin): continue
        elif (ts>options.tmax): break
        # get event/object/packet parameters
        obj, evt = e['obj'], e['event']
        pkt = "%s.%s"%(e['packet'], e['pid'])
        # check for 80211N SND
        if (obj=="80211N") and (evt=="SND"):
            currpkt = pkt
        # check for 80211N DETECT or IGNORE
        detect, ignore = (evt=="DETECT"), (evt=="IGNORE")
        if (obj=="80211N") and (detect or ignore):
            assert (pkt==currpkt)
            assert hasfield(e, *phyargs)
            # get SINR
            sinr = float(e['dot11n-sinr'].lower().replace("db","") )
            if options.use_average:
                sinr -= float(e['dot11n-channel-fading'].lower().replace("db","") )
            # get FDR
            fdr = 0.0
            if usemodel:
                assert hasfield(e, *modeldetect)
                pdetect = eval(e['dot11n-model-detect'])
                if pdetect: fdr = 1.0
            else:
                assert hasfield(e, *hydradetect)
                pdetect = eval(e['dot11n-detect'])
                if pdetect: fdr = 1.0
            # create new data point
            dp = {'x':sinr, 'y':fdr, 'ndata': 1}
            data.append(dp)
        # check for other parameters
        rcv, drp = (evt=="RCV"), (evt=="DRP")
        if (obj=="80211N") and (rcv or drp):
            assert hasfield(e, 'phy-rate', 'dot11n-rmsdelay')
            mcs = int(e['phy-rate'])
            if param['mcs'] is None: param['mcs'] = mcs
            else:                    assert (mcs==param['mcs'])
            tau = float(e['dot11n-rmsdelay'])
            rmsdelay.append(tau)
        if (obj=="AGT") and rcv:
            assert hasfield(e, 'plen')
            plen = int(e['plen'])
            if param['plen'] is None: param['plen'] = plen
            else:                    assert (plen==param['plen'])
    # set remaining parameters
    if rmsdelay:
        d = np.array(rmsdelay).mean()
        param['rmsdelay'] = d
    if not usemodel:
        param['use-yerror'] = True
    return data, param

def parse_fdr():
    usage = "%prog [OPTIONS] TRACEFILE1 [TRACEFILE2 ...]\n" + \
            "      Writes parsed data to standard output."
    parser = OptionParser(usage=usage)
    parser.add_option("", "--tmin", dest="tmin", \
            type="float", default=-np.inf, \
            help="Specify simulation time to start from [default=%default]")
    parser.add_option("", "--tmax", dest="tmax", \
            type="float", default=np.inf, \
            help="Specify simulation time to stop at [default=%default]")
    parser.add_option("", "--use-average", dest="use_average", \
            action="store_true", default=False, \
            help="Bin data to average (not instantaneous) SNR [default=%default]")
    (options, args) = parser.parse_args()

    if len(args)<1:
        print "Insufficient number of arguments."
        parser.print_help()
        raise SystemExit

    # get trace files
    tracefile = args[0:]
    numtraces = len(tracefile)

    # set default parameters
    defaultparam = {'xlabel': "SNR (dB)", \
                    'ylabel': "FDR", \
                    'title': "Frame-Detection Rate vs. SNR", \
                    'label': None, \
                    'source': None, \
                    'format': None}

    # define formats
    formats = [('ro','r:'), ('bo', 'b:'), ('go', 'g:')]

    # parse data from each data set
    for k in range(numtraces):
        # get tracefile
        tfile = tracefile[k]
        trace = read_trace(options, tfile) # treat as normal wins trace file
        if not trace: continue
        # get other parameters
        fmt = formats[k%len(formats)]
        # parse trace to get (data, param) for HYDRA
        sys.stderr.write("Parsing trace from %s: \n"%(tfile))
        sys.stderr.write("      hydra ...\n")
        data, dparam = parse_info(options, trace, usemodel=False)
        if data:
            param = defaultparam.copy()
            param.update(dparam)
            param['format'] = fmt[0]
            param['source'] = tfile
            param['label']  = "Hydra PHY"
            pdata = {'data': data, 'parameters':param}
            sys.stdout.write("%s\n"%(pdata))
        # parse trace to get (data, param) for MODEL
        sys.stderr.write("      model ...\n")
        data, dparam = parse_info(options, trace, usemodel=True)
        if data:
            param = defaultparam.copy()
            param.update(dparam)
            param['format'] = fmt[1]
            param['source'] = tfile
            param['label']  = "WiNS Model"
            pdata = {'data': data, 'parameters':param}
            sys.stdout.write("%s\n"%(pdata))

if __name__ == '__main__':
    parse_fdr()


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../polymer/polymer.html">

<!-- Taken from https://www.google.com/design/spec/style/color.html#color-ui-color-application -->

<style is="custom-style">

  :root {
    /*
     * Light background theme
     */
    --light-theme-background-color: #ffffff;
    --light-theme-base-color: #000000;
    --light-theme-text-color: #212121;
    --light-theme-secondary-color: #737373;  /* for secondary text and icons */
    --light-theme-disabled-color: #9b9b9b;  /* disabled/hint text */
    --light-theme-divider-color: #dbdbdb;

    /*
     * Dark background theme
     */
    --dark-theme-background-color: #212121;
    --dark-theme-base-color: #ffffff;
    --dark-theme-text-color: #ffffff;
    --dark-theme-secondary-color: #bcbcbc;  /* for secondary text and icons */
    --dark-theme-disabled-color: #646464;  /* disabled/hint text */
    --dark-theme-divider-color: #3c3c3c;

    /*
     * Primary and accent colors. Also see color.html for more colors.
     */
    --primary-color: #3f51b5;  /* --paper-indigo-500 */
    --light-primary-color: #c5cae9;  /* --paper-indigo-100 */
    --dark-primary-color: #303f9f;  /* --paper-indigo-700 */

    --accent-color: #ff4081;  /* --paper-pink-a200 */
    --light-accent-color: #ff80ab;  /* --paper-pink-a100 */
    --dark-accent-color: #f50057;  /* --paper-pink-a400 */

    /*
     * Deprecated values because of their confusing names.
     */
    --primary-text-color: var(--light-theme-text-color);
    --text-primary-color: var(--dark-theme-text-color);
    --primary-background-color: var(--light-theme-background-color);
    --secondary-text-color: var(--light-theme-secondary-color);
    --disabled-text-color:var(--light-theme-disabled-color);
    --divider-color: var(--light-theme-divider-color);
    --default-primary-color: var(--primary-color);
  }

</style>


text:
<?php

namespace app\controllers;

use Yii;
use app\models\JobCard;
use app\models\JobCardSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper as help;

/**
 * JobCardController implements the CRUD actions for JobCard model.
 */
class JobCardController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all JobCard models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new JobCardSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->orderBy('job_card_id desc');
$dataProvider->query->where('job_card_status !="completed"');

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single JobCard model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new JobCard model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new JobCard();
		$dateConvert=yii::$app->request->post();
        $dateConvert=help::datevolume($dateConvert,"date","create");
        if ($model->load($dateConvert) && $model->save()) {

			   $session = Yii::$app->session;
            $session['alert']=help::warnalert("Record has been created succesfully",1);

            return $this->redirect(['index', 'id' => $model->job_card_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing JobCard model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

		if($dateConvert=yii::$app->request->post())
		{
			 $dateConvert=help::datevolume($dateConvert,"date","create");
		}

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
			  $session = Yii::$app->session;
            $session['alert']=help::warnalert("Record has been updated succesfully",1);
            return $this->redirect(['index', 'id' => $model->job_card_id]);
        } else {
			$model=help::datevolume($model,"date","update");
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing JobCard model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
             $session = Yii::$app->session;
            $session['alert']=help::warnalert("Record has been deleted succesfully",1);
        return $this->redirect(['index']);
    }

    /**
     * Finds the JobCard model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return JobCard the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = JobCard::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Sr. Design 2015: Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

Sr. Design 2015

Solar Powered light

Main Page

Related Pages

Data Structures

Files

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

File List

Globals

All

Functions

Variables

Typedefs

Enumerations

Enumerator

Macros

_

a

b

c

d

e

f

g

h

i

l

m

n

o

p

r

s

t

u

v

w

x

y

- m -

mDataRdyUSART
: app_device_cdc_basic.c

MINUTE
: rtc.h

MONTHLY
: rtc.h

MOVE
: sensors.h

MSD_CBW_ADDR_TAG
: usb_hal_pic18.h

MSD_CSW_ADDR_TAG
: usb_hal_pic18.h

mTxRdyUSART
: app_device_cdc_basic.c

mUSBUSARTIsTxTrfReady
: usb_device_cdc.h

mUSBUSARTTxRam
: usb_device_cdc.h

mUSBUSARTTxRom
: usb_device_cdc.h

Generated on Wed Apr 15 2015 22:43:23 for Sr. Design 2015 by

     1.8.9.1


text:
import {
  OnInit,
  OnDestroy,
  Directive,
  Optional,
  Inject,
  Host,
  SkipSelf,
  forwardRef,
  Provider,
  Self
} from 'angular2/core';
import {CONST_EXPR} from 'angular2/src/facade/lang';

import {ControlContainer} from './control_container';
import {controlPath, composeValidators, composeAsyncValidators} from './shared';
import {ControlGroup} from '../model';
import {Form} from './form_interface';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {AsyncValidatorFn, ValidatorFn} from './validators';

const controlGroupProvider =
    CONST_EXPR(new Provider(ControlContainer, {useExisting: forwardRef(() => NgControlGroup)}));

/**
 * Creates and binds a control group to a DOM element.
 *
 * This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
 *
 * ### Example ([live demo](http://plnkr.co/edit/7EJ11uGeaggViYM6T5nq?p=preview))
 *
 * ```typescript
 * @Component({
 *   selector: 'my-app',
 *   directives: [FORM_DIRECTIVES],
 * })
 * @View({
 *   template: `
 *     <div>
 *       <h2>Angular2 Control & ControlGroup Example</h2>
 *       <form #f="ngForm">
 *         <div ngControlGroup="name" #cg-name="form">
 *           <h3>Enter your name:</h3>
 *           <p>First: <input ngControl="first" required></p>
 *           <p>Middle: <input ngControl="middle"></p>
 *           <p>Last: <input ngControl="last" required></p>
 *         </div>
 *         <h3>Name value:</h3>
 *         <pre>{{valueOf(cgName)}}</pre>
 *         <p>Name is {{cgName?.control?.valid ? "valid" : "invalid"}}</p>
 *         <h3>What's your favorite food?</h3>
 *         <p><input ngControl="food"></p>
 *         <h3>Form value</h3>
 *         <pre>{{valueOf(f)}}</pre>
 *       </form>
 *     </div>
 *   `,
 *   directives: [FORM_DIRECTIVES]
 * })
 * export class App {
 *   valueOf(cg: NgControlGroup): string {
 *     if (cg.control == null) {
 *       return null;
 *     }
 *     return JSON.stringify(cg.control.value, null, 2);
 *   }
 * }
 * ```
 *
 * This example declares a control group for a user's name. The value and validation state of
 * this group can be accessed separately from the overall form.
 */
@Directive({
  selector: '[ngControlGroup]',
  providers: [controlGroupProvider],
  inputs: ['name: ngControlGroup'],
  exportAs: 'ngForm'
})
export class NgControlGroup extends ControlContainer implements OnInit,
    OnDestroy {
  /** @internal */
  _parent: ControlContainer;

  constructor(@Host() @SkipSelf() parent: ControlContainer,
              @Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
              @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
    super();
    this._parent = parent;
  }

  ngOnInit(): void { this.formDirective.addControlGroup(this); }

  ngOnDestroy(): void { this.formDirective.removeControlGroup(this); }

  /**
   * Get the {@link ControlGroup} backing this binding.
   */
  get control(): ControlGroup { return this.formDirective.getControlGroup(this); }

  /**
   * Get the path to this control group.
   */
  get path(): string[] { return controlPath(this.name, this._parent); }

  /**
   * Get the {@link Form} to which this group belongs.
   */
  get formDirective(): Form { return this._parent.formDirective; }

  get validator(): ValidatorFn { return composeValidators(this._validators); }

  get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
}


text:
package org.jgentleframework.context;

import java.util.ArrayList;

/**
 * Chỉ định một component service context (CSC), các CSC
 * cần implement interface này để được cung cấp chức năng như là
 * một CSC. Các CSC sẽ được khởi tạo cùng lúc ngay sau khi khởi
 * tạo services context.
 *
 * @author LE QUOC CHUNG - mailto: skydunkpro@yahoo.com
 * @date Nov 23, 2007
 * @param <T>
 *            kiểu type của configurable interface tương ứng của
 *            CSC.
 */
public interface ComponentServiceContextType<T> {
	/**
	 * init method sẽ được thực thi ngay sau khi
	 * Component Service Context (CSC) chỉ định được khởi tạo.
	 * Sau khi init method được invoked, JGenlle
	 * context sẽ tự động add CSC vào trong
	 * serviceProvider hiện hành.
	 *
	 * @param serviceProvider
	 *            đối tượng serviceProvider của CSC hiện hành
	 * @param configInstances
	 *            danh sách các config instances tương ứng của
	 *            Component Service Context (CSC) hiện hành.
	 */
	public void init(ServiceProvider serviceProvider,
			ArrayList<T> configInstances);

	/**
	 * Trả về object class chỉ định kiểu của
	 * config class tương ứng với
	 * Component Service Context hiện hành.
	 *
	 * @return {@link Class}
	 */
	public Class<T> returnClassType();
}


text:
<?php
namespace vakata\database\test;

use vakata\database\DB as DBI;
use vakata\database\DBException as DBE;

abstract class Schema extends \PHPUnit\Framework\TestCase
{
    protected static $db = null;

    abstract protected function getConnectionString();

    public static function tearDownAfterClass(): void
    {
        static::$db = null;
    }

    protected function getDB()
    {
        if (!static::$db) {
            $connection = $this->getConnectionString();
            static::$db = new DBI($connection);
            $this->importFile(
                static::$db,
                __DIR__ . '/data/' . basename(explode('://', $connection)[0]) . '_schema.sql'
            );
        }
        return static::$db;
    }
    protected function importFile(DBI $dbc, string $path)
    {
        $sql = file_get_contents($path);
        $sql = str_replace("\r", '', $sql);
        $sql = preg_replace('(--.*\n)', '', $sql);
        $sql = preg_replace('(\n+)', "\n", $sql);
        $sql = explode(';', $sql);
        foreach (array_filter(array_map("trim", $sql)) as $q) {
            $dbc->query($q);
        }
    }

    public function testIDs()
    {
        $books = $this->getDB()->book()
            ->with('author')->filter('author.name', 'Terry Pratchett')->ids();
        $this->assertEquals($books, ['1']);
    }

    public function testCollection()
    {
        $books = $this->getDB()->book();
        $this->assertEquals(count($books), 1);
        $this->assertEquals($books[0]['name'], 'Equal rites');
    }
    public function testRelations()
    {
        $books = $this->getDB()->book()->with('author')->with('tag');
        $this->assertEquals($books[0]['author']['name'], 'Terry Pratchett');
        $this->assertEquals(count($books[0]['tag']), 2);
    }
    public function testRemoteRelations()
    {
        $author = $this->getDB()->author()->with('book')->with('book.tag');
        $this->assertEquals(count($author[0]['book'][0]['tag']), 2);
        $this->assertEquals(count($author[2]['book']), 0);
    }

    public function testSerialize()
    {
        $this->getDB()->setSchema($this->getDB()->getSchema());
        $books = $this->getDB()->book()->with('author')->with('tag');
        $this->assertEquals($books[0]['author']['name'], 'Terry Pratchett');
        $this->assertEquals(count($books[0]['tag']), 2);
    }

    public function testFilter()
    {
        $this->assertEquals(count($this->getDB()->book()->filter('name', 'Equal rites')), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('name', 'Not found')), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author.name', 'Terry Pratchett')), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author.name', 'Douglas Adams')), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('tag.name', 'Escarina')), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('tag.name', 'Discworld')), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('tag.name', 'None')), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gt' => 0])), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gt' => 1])), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gte' => 1])), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lt' => 1])), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lt' => 2])), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lte' => 1])), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gt' => 0], true)), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gt' => 1], true)), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['gte' => 1], true)), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lt' => 1], true)), 1);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lt' => 2], true)), 0);
        $this->assertEquals(count($this->getDB()->book()->filter('author_id', ['lte' => 1], true)), 0);
    }

    public function testReadLoop()
    {
        $author = $this->getDB()->author();
        foreach ($author as $k => $a) {
            $this->assertEquals($k + 1, $a['id']);
        }
        foreach ($author as $k => $a) {
            $this->assertEquals($k + 1, $a['id']);
        }
    }
    public function testReadIndex()
    {
        $author = $this->getDB()->author();
        $this->assertEquals($author[0]['name'], 'Terry Pratchett');
        $this->assertEquals($author[2]['name'], 'Douglas Adams');
    }
    public function testReadRelations()
    {
        $author = $this->getDB()->author()->with('book');
        $this->assertEquals($author[0]['book'][0]['name'], 'Equal rites');
    }
    public function testReadChanges()
    {
        $this->getDB()->query('INSERT INTO author (name) VALUES (?)', ['Stephen King']);
        $author = $this->getDB()->author();
        $this->assertEquals($author[3]['name'], 'Stephen King');
    }

    public function testMappedCollection()
    {
        $books = $this->getDB()->book(true);
        foreach ($books as $book) {
            $this->assertEquals($book->name, 'Equal rites');
        }
        $this->assertEquals(count($books), 1);
        $this->assertEquals($books[0]->name, 'Equal rites');
        iterator_to_array($books);
        foreach ($books as $book) {
            $this->assertEquals($book->name, 'Equal rites');
        }
    }
    public function testMappedRelations()
    {
        $books = $this->getDB()->book(true);
        $this->assertEquals('Terry Pratchett', $books[0]->author->name);
        $this->assertEquals(2, count($books[0]->tag));
        $this->assertEquals('Terry Pratchett', $books[0]->author->book[0]->tag[0]->book[0]->author->name);
    }

    public function testMappedRelationsWith()
    {
        $books = $this->getDB()->tableMapped('book')->with('author');
        $this->assertEquals($books[0]->author->name, 'Terry Pratchett');
        $this->assertEquals(count($books[0]->tag), 2);
    }

    public function testMappedFilter()
    {
        $this->assertEquals(count($this->getDB()->book(true)->filter('name', 'Equal rites')), 1);
        $this->assertEquals(count($this->getDB()->book(true)->filter('name', 'Not found')), 0);
        $this->assertEquals(count($this->getDB()->book(true)->filter('author.name', 'Terry Pratchett')), 1);
        $this->assertEquals(count($this->getDB()->book(true)->filter('author.name', 'Douglas Adams')), 0);
        $this->assertEquals(count($this->getDB()->book(true)->filter('tag.name', 'Escarina')), 1);
        $this->assertEquals(count($this->getDB()->book(true)->filter('tag.name', 'Discworld')), 1);
        $this->assertEquals(count($this->getDB()->book(true)->filter('tag.name', 'None')), 0);
        $this->assertEquals(
            count(
                $this->getDB()->book(true)->any([['author.name', 'Terry Pratchett'],['author.name', 'Douglas Adams']])
            ),
            1
        );
        $this->assertEquals(
            count(
                $this->getDB()->book(true)->all([['author.name', 'Terry Pratchett'],['author.name', 'Douglas Adams']])
            ),
            0
        );
        $this->assertEquals(
            count(
                $this->getDB()->book(true)->all([['tag.name', 'Discworld'],['author.name', 'Douglas Adams']])
            ),
            0
        );
        $this->assertEquals(
            count(
                $this->getDB()->book(true)->any([['tag.name', 'Discworld'],['author.name', 'Douglas Adams']])
            ),
            1
        );
    }

    public function testMappedReadLoop()
    {
        $author = $this->getDB()->author(true);
        foreach ($author as $k => $a) {
            $this->assertEquals($k + 1, $a->id);
        }
        foreach ($author as $k => $a) {
            $this->assertEquals($k + 1, $a->id);
        }
    }
    public function testMappedReadIndex()
    {
        $author = $this->getDB()->author(true);
        $this->assertEquals($author[0]->name, 'Terry Pratchett');
        $this->assertEquals($author[2]->name, 'Douglas Adams');
    }
    public function testMappedReadRelations()
    {
        $author = $this->getDB()->author(true);
        $this->assertEquals($author[0]->book[0]->name, 'Equal rites');
        $this->assertEquals($author[0]->book[0]->tag[1]->name, 'Escarina');
    }

    public function testJoins()
    {
        $this->assertEquals(
            $this->getDB()->author()
                ->join('book', [ 'author_id' => 'id' ], 'books')
                ->groupById()
                ->having('COUNT(books.id) = ?', [1]) // ->having('cnt = ?', [1]) - not standard SQL!
                ->order('cnt DESC')
                ->limit(2)
                ->select(['id', 'cnt' => 'COUNT(books.id)']),
            [ [ 'id' => 1, 'cnt' => 1 ] ]
        );
        $this->getDB()->query('INSERT INTO book(name, author_id) VALUES(?, ?)', ['Going postal', 1]);
        $this->getDB()->query('INSERT INTO book(name, author_id) VALUES(?, ?)', ['HGTG', 2]);
        $this->assertEquals(
            $this->getDB()->author()
                ->join('book', [ 'author_id' => 'id' ], 'books')
                ->groupById()
                ->having('COUNT(books.id) > ?', [0]) // ->having('cnt > ?', [0]) - not standard SQL!
                ->order('cnt ASC')
                ->limit(2)
                ->select(['id', 'cnt' => 'COUNT(books.id)']),
            [ [ 'id' => 2, 'cnt' => 1 ], [ 'id' => 1, 'cnt' => 2 ] ]
        );
    }

    public function testCreate()
    {
        $author = $this->getDB()->author();
        $res = $author->insert(['name' => 'John Resig' ]);
        $this->assertEquals($res, ['id' => 5]);
        $this->assertEquals($author[4]['name'], 'John Resig');
    }
    public function testUpdate()
    {
        $author = $this->getDB()->author();
        $author->where('id = 1')->update(['name' => 'Terry Pratchett, Sir']);
        $this->assertEquals($this->getDB()->author()[0]['name'], 'Terry Pratchett, Sir');
        $this->assertEquals($this->getDB()->one('SELECT name FROM author WHERE id = 1'), 'Terry Pratchett, Sir');
    }
    public function testDelete()
    {
        $author = $this->getDB()->author();
        $author->filter('id', 5)->delete();
        $this->assertEquals(count($this->getDB()->author()), 4);
        $this->assertEquals($this->getDB()->one('SELECT COUNT(id) FROM author'), 4);
    }
    public function testAny()
    {
        $author = $this->getDB()->author();
        $this->assertEquals(count($author->reset()->any([['id', 1], ['id', 2], ['id', [3,4]]])), 4);
        $this->assertEquals(count($author->reset()->any([['id', 1], ['id', 2]])), 2);
    }
    public function testAll()
    {
        $author = $this->getDB()->author();
        $this->assertEquals(count($author->reset()->all([['id', 1], ['id', 2], ['id', [3,4]]])), 0);
        $this->assertEquals(count($author->reset()->all([['id', 1], ['id', 2]])), 0);
        $this->assertEquals(count($author->reset()->all([['id', 1], ['id', ['lt'=>2]]])), 1);
        $this->assertEquals(count($author->reset()->all([['id', 1], ['id', ['not'=>2]]])), 1);
        $this->assertEquals(count($author->reset()->all([['id', 2], ['id', ['not'=>2]]])), 0);
    }
    public function testLike()
    {
        $author = $this->getDB()->author();
        $this->assertEquals(count($author->reset()->filter('name', ['like'=>'Brad'])), 0);
        $this->assertEquals(count($author->reset()->filter('name', ['like'=>'%Brad%'])), 1);
        $this->assertEquals(count($author->reset()->filter('name', ['like'=>'%Ivan%'])), 0);
        $this->assertEquals(
            count($author->reset()->any([['name', ['like'=>'%Ivan%']], ['name', ['like'=>'%Brad%']]])),
            1
        );
    }
    public function testStrictDisabled()
    {
        $db = $this->getDB();
        $id = $db->tag()->insert([
            'name' => str_repeat('a', 256)
        ]);
        $this->assertEquals(str_repeat('a', 255), $db->tag()->filter('id', $id['id'])[0]['name']);
    }
    public function testStrictEnabled()
    {
        $this->expectException(DBE::class);
        $db = new DBI($this->getConnectionString() . '&strict=1');
        $db->tag()->insert([
            'name' => str_repeat('a', 256)
        ]);
    }
}


text:
<?php

namespace Xsist10\WTW;

use Xsist10\WTW\Search\SearchAdapter;
use \Exception;

class ErrorManager extends DumpManager
{
    /**
     * @var array
     */
    private $logLevels = array();

    public function addLevel($logLevel)
    {
        $this->logLevels[$logLevel] = $logLevel;
        return $this;
    }

    public function handleExceptions()
    {
        set_exception_handler(array($this, "exception"));
    }

    public function register()
    {
        set_error_handler(array($this, "error"));
        register_shutdown_function(array($this, "shutdown"));
    }

    public function error($errorNumber, $errString, $errFile, $errLine)
    {
        if (in_array($errorNumber, $this->logLevels))
        {
            $this->process($errString);
            exit(1);
        }
    }

    public function exception(Exception $exception)
    {
        $this->process($exception->getMessage());
        exit(1);
    }

    public function shutdown()
    {
        $error = error_get_last();
        $this->error(
            $error['type'],
            $error['message'],
            $error['file'],
            $error['line']
        );
    }
}


text:
use utils::version_constants;
use libc::c_char;
use utils::cstring::CStringUtils;
use utils::libindy::{wallet, pool, ledger};
use utils::error;
use settings;
use std::ffi::CString;
use utils::threadpool::spawn;
use error::prelude::*;

/// Initializes VCX with config settings
///
/// example configuration is in libvcx/sample_config/config.json
///
/// #Params
/// command_handle: command handle to map callback to user context.
///
/// config_path: path to a config file to populate config attributes
///
/// cb: Callback that provides error status of initialization
///
/// #Returns
/// Error code as a u32
#[no_mangle]
pub extern fn vcx_init_with_config(command_handle: u32,
                                   config: *const c_char,
                                   cb: Option<extern fn(xcommand_handle: u32, err: u32)>) -> u32 {
    info!("vcx_init_with_config >>>");

    check_useful_c_str!(config,VcxErrorKind::InvalidOption);
    check_useful_c_callback!(cb, VcxErrorKind::InvalidOption);

    trace!("vcx_init(command_handle: {}, config: {:?})",
           command_handle, config);

    if config == "ENABLE_TEST_MODE" {
        settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "true");
        settings::set_defaults();
    } else {
        match settings::process_config_string(&config, true) {
            Err(e) => {
                error!("Invalid configuration specified: {}", e);
                return e.into();
            }
            Ok(_) => (),
        }
    };

    _finish_init(command_handle, cb)
}

/// Initializes VCX with config file
///
/// An example file is at libvcx/sample_config/config.json
///
/// #Params
/// command_handle: command handle to map callback to user context.
///
/// config_path: path to a config file to populate config attributes
///
/// cb: Callback that provides error status of initialization
///
/// #Returns
/// Error code as a u32
#[no_mangle]
pub extern fn vcx_init(command_handle: u32,
                       config_path: *const c_char,
                       cb: Option<extern fn(xcommand_handle: u32, err: u32)>) -> u32 {
    info!("vcx_init >>>");

    check_useful_c_callback!(cb, VcxErrorKind::InvalidOption);

    trace!("vcx_init(command_handle: {}, config_path: {:?})",
           command_handle, config_path);

    if !config_path.is_null() {
        check_useful_c_str!(config_path,VcxErrorKind::InvalidOption);

        if config_path == "ENABLE_TEST_MODE" {
            settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "true");
            settings::set_defaults();
        } else {
            match settings::process_config_file(&config_path) {
                Err(e) => {
                    return VcxError::from_msg(VcxErrorKind::InvalidConfiguration, "Cannot initialize with given config path.").into();
                }
                Ok(_) => {
                    match settings::validate_payment_method() {
                        Ok(_) => (),
                        Err(e) => return e.into()
                    }
                }
            };
        }
    } else {
        error!("Cannot initialize with given config path: config path is null.");
        return VcxError::from_msg(VcxErrorKind::InvalidConfiguration, "Cannot initialize with given config path: config path is null.").into();
    }

    _finish_init(command_handle, cb)
}

fn _finish_init(command_handle: u32, cb: extern fn(xcommand_handle: u32, err: u32)) -> u32 {
    ::utils::threadpool::init();

    settings::log_settings();

    if wallet::get_wallet_handle() > 0 {
        error!("Library was already initialized");
        return VcxError::from_msg(VcxErrorKind::AlreadyInitialized, "Library was already initialized").into();
    }
    // Wallet name was already validated
    let wallet_name = match settings::get_config_value(settings::CONFIG_WALLET_NAME) {
        Ok(x) => x,
        Err(_) => {
            trace!("Using default wallet: {}", settings::DEFAULT_WALLET_NAME.to_string());
            settings::set_config_value(settings::CONFIG_WALLET_NAME, settings::DEFAULT_WALLET_NAME);
            settings::DEFAULT_WALLET_NAME.to_string()
        }
    };

    let wallet_type = settings::get_config_value(settings::CONFIG_WALLET_TYPE).ok();
    let storage_config = settings::get_config_value(settings::CONFIG_WALLET_STORAGE_CONFIG).ok();
    let storage_creds = settings::get_config_value(settings::CONFIG_WALLET_STORAGE_CREDS).ok();

    trace!("libvcx version: {}{}", version_constants::VERSION, version_constants::REVISION);

    spawn(move || {
        if settings::get_config_value(settings::CONFIG_GENESIS_PATH).is_ok() {
            match ::utils::libindy::init_pool() {
                Ok(_) => (),
                Err(e) => {
                    error!("Init Pool Error {}.", e);
                    return Ok(cb(command_handle, e.into()));
                }
            }
        }

        match wallet::open_wallet(&wallet_name, wallet_type.as_ref().map(String::as_str),
                                  storage_config.as_ref().map(String::as_str), storage_creds.as_ref().map(String::as_str)) {
            Ok(_) => {
                debug!("Init Wallet Successful");
                cb(command_handle, error::SUCCESS.code_num);
            }
            Err(e) => {
                error!("Init Wallet Error {}.", e);
                cb(command_handle, e.into());
            }
        }
        Ok(())
    });

    error::SUCCESS.code_num
}

/// Initialize vcx with the minimal configuration (wallet, pool must already be set with
/// vcx_wallet_set_handle() and vcx_pool_set_handle()) and without any agency configuration
///
/// #Example:
///
/// vcx_init_minimal('{"institution_name":"faber","institution_did":"44x8p4HubxzUK1dwxcc5FU",\
//      "institution_verkey":"444MFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE"}')
///
/// #Params
///
/// config: minimal configuration
///
/// #Returns
/// Error code as u32
#[no_mangle]
pub extern fn vcx_init_minimal(config: *const c_char) -> u32 {
    check_useful_c_str!(config,VcxErrorKind::InvalidOption);

    trace!("vcx_init_minimal(config: {:?})", config);

    if config == "ENABLE_TEST_MODE" {
        settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "true");
        settings::set_defaults();
    } else {
        match settings::process_config_string(&config, false) {
            Err(e) => {
                error!("Invalid configuration specified: {}", e);
                return e.into();
            }
            Ok(_) => (),
        }
    };

    if wallet::get_wallet_handle() <= 0 || pool::get_pool_handle().is_err() {
        error!("Library cannot be initialized without wallet/pool");
        return error::INVALID_STATE.code_num;
    }

    ::utils::threadpool::init();

    settings::log_settings();

    trace!("libvcx version: {}{}", version_constants::VERSION, version_constants::REVISION);

    error::SUCCESS.code_num
}

lazy_static! {
    pub static ref VERSION_STRING: CString = CString::new(format!("{}{}", version_constants::VERSION, version_constants::REVISION)).unwrap();
}

#[no_mangle]
pub extern fn vcx_version() -> *const c_char {
    info!("vcx_version >>>");
    VERSION_STRING.as_ptr()
}

/// Reset libvcx to a pre-configured state, releasing/deleting any handles and freeing memory
///
/// libvcx will be inoperable and must be initialized again with vcx_init_with_config
///
/// #Params
/// delete: specify whether wallet/pool should be deleted
///
/// #Returns
/// Success
#[no_mangle]
pub extern fn vcx_shutdown(delete: bool) -> u32 {
    info!("vcx_shutdown >>>");
    trace!("vcx_shutdown(delete: {})", delete);

    match wallet::close_wallet() {
        Ok(_) => {}
        Err(_) => {}
    };

    match pool::close() {
        Ok(_) => {}
        Err(_) => {}
    };

    ::schema::release_all();
    ::connection::release_all();
    ::issuer_credential::release_all();
    ::credential_def::release_all();
    ::proof::release_all();
    ::disclosed_proof::release_all();
    ::credential::release_all();

    if delete {
        let pool_name = settings::get_config_value(settings::CONFIG_POOL_NAME)
            .unwrap_or(settings::DEFAULT_POOL_NAME.to_string());

        let wallet_name = settings::get_config_value(settings::CONFIG_WALLET_NAME)
            .unwrap_or(settings::DEFAULT_WALLET_NAME.to_string());

        let wallet_type = settings::get_config_value(settings::CONFIG_WALLET_TYPE).ok();

        match wallet::delete_wallet(&wallet_name, wallet_type.as_ref().map(String::as_str), None, None) {
            Ok(_) => (),
            Err(_) => (),
        };

        match pool::delete(&pool_name) {
            Ok(_) => (),
            Err(_) => (),
        };
    }

    settings::clear_config();
    trace!("vcx_shutdown(delete: {})", delete);
    error::SUCCESS.code_num
}

#[no_mangle]
pub extern fn vcx_error_c_message(error_code: u32) -> *const c_char {
    info!("vcx_error_c_message >>>");
    trace!("vcx_error_message(error_code: {})", error_code);
    error::error_c_message(&error_code).as_ptr()
}

#[no_mangle]
pub extern fn vcx_update_institution_info(name: *const c_char, logo_url: *const c_char) -> u32 {
    info!("vcx_update_institution_info >>>");

    check_useful_c_str!(name, VcxErrorKind::InvalidConfiguration);
    check_useful_c_str!(logo_url, VcxErrorKind::InvalidConfiguration);
    trace!("vcx_update_institution_info(name: {}, logo_url: {})", name, logo_url);

    settings::set_config_value(::settings::CONFIG_INSTITUTION_NAME, &name);
    settings::set_config_value(::settings::CONFIG_INSTITUTION_LOGO_URL, &logo_url);

    error::SUCCESS.code_num
}

/// Retrieve author agreement and acceptance mechanisms set on the Ledger
///
/// #params
///
/// command_handle: command handle to map callback to user context.
///
/// cb: Callback that provides array of matching messages retrieved
///
/// #Returns
/// Error code as a u32
#[no_mangle]
pub extern fn vcx_get_ledger_author_agreement(command_handle: u32,
                                              cb: Option<extern fn(xcommand_handle: u32, err: u32, author_agreement: *const c_char)>) -> u32 {
    info!("vcx_get_ledger_author_agreement >>>");

    check_useful_c_callback!(cb, VcxErrorKind::InvalidOption);

    trace!("vcx_get_ledger_author_agreement(command_handle: {})",
           command_handle);

    spawn(move || {
        match ledger::libindy_get_txn_author_agreement() {
            Ok(x) => {
                trace!("vcx_ledger_get_fees_cb(command_handle: {}, rc: {}, author_agreement: {})",
                       command_handle, error::SUCCESS.message, x);

                let msg = CStringUtils::string_to_cstring(x);
                cb(command_handle, error::SUCCESS.code_num, msg.as_ptr());
            }
            Err(e) => {
                error!("vcx_get_ledger_author_agreement(command_handle: {}, rc: {})",
                       command_handle, e);
                cb(command_handle, e.into(), ::std::ptr::null_mut());
            }
        };

        Ok(())
    });

    error::SUCCESS.code_num
}

/// Set some accepted agreement as active.
///
/// As result of succesfull call of this funciton appropriate metadata will be appended to each write request by `indy_append_txn_author_agreement_meta_to_request` libindy call.
///
/// #Params
/// text and version - (optional) raw data about TAA from ledger.
///     These parameters should be passed together.
///     These parameters are required if hash parameter is ommited.
/// hash - (optional) hash on text and version. This parameter is required if text and version parameters are ommited.
/// acc_mech_type - mechanism how user has accepted the TAA
/// time_of_acceptance - UTC timestamp when user has accepted the TAA
///
/// #Returns
/// Error code as a u32
#[no_mangle]
pub extern fn vcx_set_active_txn_author_agreement_meta(text: *const c_char,
                                                       version: *const c_char,
                                                       hash: *const c_char,
                                                       acc_mech_type: *const c_char,
                                                       time_of_acceptance: u64) -> u32 {
    info!("vcx_set_active_txn_author_agreement_meta >>>");

    check_useful_opt_c_str!(text, VcxErrorKind::InvalidOption);
    check_useful_opt_c_str!(version, VcxErrorKind::InvalidOption);
    check_useful_opt_c_str!(hash, VcxErrorKind::InvalidOption);
    check_useful_c_str!(acc_mech_type, VcxErrorKind::InvalidOption);

    trace!("vcx_set_active_txn_author_agreement_meta(text: {:?}, version: {:?}, hash: {:?}, acc_mech_type: {:?}, time_of_acceptance: {:?})",
           text, version, hash, acc_mech_type, time_of_acceptance);

    match ::utils::author_agreement::set_txn_author_agreement(text, version, hash, acc_mech_type, time_of_acceptance) {
        Ok(x) => error::SUCCESS.code_num,
        Err(err) => err.into()
    }
}

#[no_mangle]
pub extern fn vcx_mint_tokens(seed: *const c_char, fees: *const c_char) {
    info!("vcx_mint_tokens >>>");

    // TODO: CHEC
    let seed = if !seed.is_null() {
        match CStringUtils::c_str_to_string(seed) {
            Ok(opt_val) => opt_val.map(String::from),
            Err(_) => return ()
        }
    } else {
        None
    };

    let fees = if !fees.is_null() {
        match CStringUtils::c_str_to_string(fees) {
            Ok(opt_val) => opt_val.map(String::from),
            Err(_) => return ()
        }
    } else {
        None
    };
    trace!("vcx_mint_tokens(seed: {:?}, fees: {:?})", seed, fees);

    ::utils::libindy::payments::mint_tokens_and_set_fees(None, None, fees, seed).unwrap_or_default();
}

/// Get details for last occurred error.
///
/// This function should be called in two places to handle both cases of error occurrence:
///     1) synchronous  - in the same application thread
///     2) asynchronous - inside of function callback
///
/// NOTE: Error is stored until the next one occurs in the same execution thread or until asynchronous callback finished.
///       Returning pointer has the same lifetime.
///
/// #Params
/// * `error_json_p` - Reference that will contain error details (if any error has occurred before)
///  in the format:
/// {
///     "backtrace": Optional<str> - error backtrace.
///         Collecting of backtrace can be enabled by setting environment variable `RUST_BACKTRACE=1`
///     "message": str - human-readable error description
/// }
///
#[no_mangle]
pub extern fn vcx_get_current_error(error_json_p: *mut *const c_char) {
    trace!("vcx_get_current_error >>> error_json_p: {:?}", error_json_p);

    let error = get_current_error_c_json();
    unsafe { *error_json_p = error };

    trace!("vcx_get_current_error: <<<");
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;
    use std::ptr;
    use std::thread;
    use utils::{
        libindy::{
        wallet::{import, tests::export_test_wallet, tests::delete_import_wallet_path},
        pool::get_pool_handle
        },
        get_temp_dir_path
    };
    use api::VcxStateType;
    use api::return_types_u32;
    use api::connection::vcx_connection_create;

    fn create_config_util(logging: Option<&str>) -> String {
        json!({"agency_did" : "72x8p4HubxzUK1dwxcc5FU",
               "remote_to_sdk_did" : "UJGjM6Cea2YVixjWwHN9wq",
               "sdk_to_remote_did" : "AB3JM851T4EQmhh8CdagSP",
               "sdk_to_remote_verkey" : "888MFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE",
               "institution_name" : "evernym enterprise",
               "agency_verkey" : "91qMFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE",
               "remote_to_sdk_verkey" : "91qMFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE",
               "genesis_path": get_temp_dir_path(Some("pool1.txn")).to_str().unwrap(),
               "payment_method": "null",
               "pool_config": json!({"timeout":60}).to_string()
           }).to_string()
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_with_file() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();

        let config_path_buf = get_temp_dir_path(Some("test_init.json"));
        let config_path = config_path_buf.to_str().unwrap();
        let content = create_config_util(Some("true"));
        settings::write_config_to_file(&content, config_path).unwrap();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init(cb.command_handle,
                            CString::new(config_path).unwrap().into_raw(),
                            Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();
        // Assert pool was initialized
        assert_ne!(get_pool_handle().unwrap(), 0);
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_with_file_no_payment_method() {
        init!("false");
        settings::clear_config();

        let config_path_buf = get_temp_dir_path(Some("test_init.json"));
        let config_path = config_path_buf.to_str().unwrap();
        let content = json!({
            "wallet_name": settings::DEFAULT_WALLET_NAME,
            "wallet_key": settings::DEFAULT_WALLET_KEY,
            "wallet_key_derivation": settings::DEFAULT_WALLET_KEY_DERIVATION,
        }).to_string();

        settings::write_config_to_file(&content, config_path).unwrap();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init(cb.command_handle,
                            CString::new(config_path).unwrap().into_raw(),
                            Some(cb.get_callback())),
                   error::MISSING_PAYMENT_METHOD.code_num);
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_with_config() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();

        let content = create_config_util(None);

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();
        // Assert pool was initialized
        assert_ne!(get_pool_handle().unwrap(), 0);
    }

    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_fails_when_open_pool_fails() {
        settings::set_defaults();
        vcx_shutdown(true);
        use std::fs;
        use std::io::Write;
        settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE, "false");
        settings::set_config_value(settings::CONFIG_WALLET_KEY, settings::DEFAULT_WALLET_KEY);

        // Write invalid genesis.txn
        let mut f = fs::File::create(get_temp_dir_path(Some(::utils::constants::GENESIS_PATH)).to_str().unwrap()).unwrap();
        f.write_all("{}".as_bytes()).unwrap();
        f.flush().unwrap();
        f.sync_all().unwrap();

        let wallet_name = "test_init_fails_when_open_pool_fails";
        wallet::create_wallet(wallet_name, None, None, None).unwrap();

        let content = create_config_util(None);

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        let rc = cb.receive(Some(Duration::from_secs(10)));
        thread::sleep(Duration::from_secs(1));
        assert!(rc.is_err());
        assert_eq!(get_pool_handle().unwrap_err().kind(), VcxErrorKind::NoPoolOpen);
        assert_eq!(wallet::get_wallet_handle(), 0);
        wallet::delete_wallet(wallet_name, None, None, None).unwrap();
    }

    #[test]
    fn test_init_can_be_called_with_no_pool_config() {
        init!("false");
        wallet::close_wallet().unwrap();

        let content = json!({
            "wallet_name": settings::DEFAULT_WALLET_NAME,
            "wallet_key": settings::DEFAULT_WALLET_KEY,
            "wallet_key_derivation": settings::DEFAULT_WALLET_KEY_DERIVATION,
        }).to_string();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        // assert that pool was never initialized
        assert!(get_pool_handle().is_err());
    }

    #[test]
    fn test_init_fails_with_no_wallet_key() {
        settings::set_defaults();
        vcx_shutdown(true);
        let content = json!({
            "wallet_name": settings::DEFAULT_WALLET_NAME,
        }).to_string();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::MISSING_WALLET_KEY.code_num);
    }

    #[test]
    fn test_config_with_no_wallet_uses_default() {
        init!("false");

        vcx_shutdown(false);
        thread::sleep(Duration::from_secs(1));
        assert!(settings::get_config_value(settings::CONFIG_WALLET_NAME).is_err());

        let content = json!({
            "wallet_key": "key",
        }).to_string();
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        let err = cb.receive(Some(Duration::from_secs(10)));
        // Assert default wallet name
        assert_eq!(settings::get_config_value(settings::CONFIG_WALLET_NAME).unwrap(), settings::DEFAULT_WALLET_NAME);
    }

    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_vcx_init_with_default_values() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();

        let content = "{}".to_string();
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_vcx_init_called_twice_fails() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();

        let content = "{}";

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        // Repeat call
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::ALREADY_INITIALIZED.code_num);
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_vcx_init_called_twice_passes_after_shutdown() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();

        let content = format!(r#"{{"wallet_name":"{}"}}"#, settings::DEFAULT_WALLET_NAME);

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content.clone()).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        //Assert config values were set correctly
        assert_eq!(settings::get_config_value("wallet_name").unwrap(), settings::DEFAULT_WALLET_NAME);

        //Verify shutdown was successful
        vcx_shutdown(true);
        assert_eq!(settings::get_config_value("wallet_name").unwrap_err().kind(), VcxErrorKind::InvalidConfiguration);

        // Init for the second time works
        ::utils::devsetup::tests::setup_ledger_env();
        wallet::close_wallet().unwrap();
        pool::close().unwrap();
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        vcx_shutdown(true);
    }

    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_fails_with_open_wallet() {
        init!("ledger");

        let config_path_buf = get_temp_dir_path(Some("test_init.json"));
        let config_path = config_path_buf.to_str().unwrap();
        let content = create_config_util(None);
        settings::write_config_to_file(&content, config_path).unwrap();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init(cb.command_handle,
                            CString::new(config_path).unwrap().into_raw(),
                            Some(cb.get_callback())),
                   error::ALREADY_INITIALIZED.code_num);
    }

    #[test]
    fn test_init_after_importing_wallet_success() {
        settings::set_defaults();
        teardown!("false");

        let export_path = export_test_wallet();

        vcx_shutdown(true);

        let import_config = json!({
            settings::CONFIG_WALLET_NAME: settings::DEFAULT_WALLET_NAME,
            settings::CONFIG_WALLET_KEY: settings::DEFAULT_WALLET_KEY,
            settings::CONFIG_WALLET_KEY_DERIVATION: settings::DEFAULT_WALLET_KEY_DERIVATION,
            settings::CONFIG_WALLET_BACKUP_KEY: settings::DEFAULT_WALLET_BACKUP_KEY,
            settings::CONFIG_EXPORTED_WALLET_PATH: export_path,
        }).to_string();
        import(&import_config).unwrap();

        let content = json!({
            "wallet_name": settings::DEFAULT_WALLET_NAME,
            "wallet_key": settings::DEFAULT_WALLET_KEY,
            "wallet_key_derivation": settings::DEFAULT_WALLET_KEY_DERIVATION,
        }).to_string();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        delete_import_wallet_path(export_path);
        vcx_shutdown(true);
    }

    #[test]
    fn test_init_with_imported_wallet_fails_with_different_params() {
        settings::set_defaults();
        teardown!("false");

        let export_path = export_test_wallet();

        vcx_shutdown(true);

        let import_config = json!({
            settings::CONFIG_WALLET_NAME: settings::DEFAULT_WALLET_NAME,
            settings::CONFIG_WALLET_KEY: settings::DEFAULT_WALLET_KEY,
            settings::CONFIG_WALLET_KEY_DERIVATION: settings::DEFAULT_WALLET_KEY_DERIVATION,
            settings::CONFIG_EXPORTED_WALLET_PATH: export_path,
            settings::CONFIG_WALLET_BACKUP_KEY: settings::DEFAULT_WALLET_BACKUP_KEY,
        }).to_string();
        import(&import_config).unwrap();

        let content = json!({
            "wallet_name": "different_wallet_name",
            "wallet_key": settings::DEFAULT_WALLET_KEY,
            "wallet_key_derivation": settings::DEFAULT_WALLET_KEY_DERIVATION,
        }).to_string();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        assert_eq!(cb.receive(Some(Duration::from_secs(10))).err(), Some(error::WALLET_NOT_FOUND.code_num));

        delete_import_wallet_path(export_path);
        settings::set_config_value(settings::CONFIG_WALLET_NAME, settings::DEFAULT_WALLET_NAME);
        vcx_shutdown(true);
    }

    #[test]
    fn test_import_after_init_fails() {
        settings::set_defaults();
        teardown!("false");

        let export_path = export_test_wallet();

        vcx_shutdown(false);

        let content = json!({
            "wallet_name": settings::DEFAULT_WALLET_NAME,
            "wallet_key": settings::DEFAULT_WALLET_KEY,
            "wallet_key_derivation": settings::DEFAULT_WALLET_KEY_DERIVATION,
        }).to_string();

        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();

        let import_config = json!({
            settings::CONFIG_WALLET_NAME: settings::DEFAULT_WALLET_NAME,
            settings::CONFIG_WALLET_KEY: settings::DEFAULT_WALLET_KEY,
            settings::CONFIG_EXPORTED_WALLET_PATH: export_path,
            settings::CONFIG_WALLET_BACKUP_KEY: settings::DEFAULT_WALLET_BACKUP_KEY,
        }).to_string();
        assert_eq!(import(&import_config).unwrap_err().kind(), VcxErrorKind::DuplicationWallet);

        delete_import_wallet_path(export_path);
        vcx_shutdown(true);
    }

    #[test]
    fn test_init_bad_path() {
        use utils::libindy::pool::get_pool_handle;
        init!("false");
        let config_path = "";
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init(cb.command_handle,
                            CString::new(config_path).unwrap().into_raw(),
                            Some(cb.get_callback())),
                   error::INVALID_OPTION.code_num);

        match get_pool_handle() {
            Ok(h) => { pool::close().unwrap(); }
            Err(_) => {}
        };
    }

    // this test now fails, you must provide a path to a valid config
    #[test]
    fn test_init_no_config_path() {
        init!("true");
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init(cb.command_handle,
                            ptr::null(),
                            Some(cb.get_callback())),
                   error::INVALID_CONFIGURATION.code_num);
    }

    #[test]
    fn test_shutdown_with_no_previous_config() {
        vcx_shutdown(true);
        vcx_shutdown(false);
    }

    #[test]
    fn test_shutdown() {
        init!("true");

        let data = r#"["name","male"]"#;
        let connection = ::connection::tests::build_test_connection();
        let credentialdef = ::credential_def::create_and_publish_credentialdef("SID".to_string(), "NAME".to_string(), "4fUDR9R7fjwELRvH9JT6HH".to_string(), "id".to_string(), "tag".to_string(), "{}".to_string()).unwrap();
        let issuer_credential = ::issuer_credential::issuer_credential_create(credentialdef, "1".to_string(), "8XFh8yBzrpJQmNyZzgoTqB".to_owned(), "credential_name".to_string(), "{\"attr\":\"value\"}".to_owned(), 1).unwrap();
        let proof = ::proof::create_proof("1".to_string(), "[]".to_string(), "[]".to_string(), r#"{"support_revocation":false}"#.to_string(), "Optional".to_owned()).unwrap();
        let schema = ::schema::create_and_publish_schema("5", "VsKV7grR1BUE29mG2Fm2kX".to_string(), "name".to_string(), "0.1".to_string(), data.to_string()).unwrap();
        let disclosed_proof = ::disclosed_proof::create_proof("id", ::utils::constants::PROOF_REQUEST_JSON).unwrap();
        let credential = ::credential::credential_create_with_offer("name", ::utils::constants::CREDENTIAL_OFFER_JSON).unwrap();

        vcx_shutdown(true);
        assert_eq!(::connection::release(connection).unwrap_err().kind(), VcxErrorKind::InvalidConnectionHandle);
        assert_eq!(::issuer_credential::release(issuer_credential).unwrap_err().kind(), VcxErrorKind::InvalidIssuerCredentialHandle);
        assert_eq!(::schema::release(schema).unwrap_err().kind(), VcxErrorKind::InvalidSchemaHandle);
        assert_eq!(::proof::release(proof).unwrap_err().kind(), VcxErrorKind::InvalidProofHandle);
        assert_eq!(::credential_def::release(credentialdef).unwrap_err().kind(), VcxErrorKind::InvalidCredDefHandle);
        assert_eq!(::credential::release(credential).unwrap_err().kind(), VcxErrorKind::InvalidCredentialHandle);
        assert_eq!(::disclosed_proof::release(disclosed_proof).unwrap_err().kind(), VcxErrorKind::InvalidDisclosedProofHandle);
        assert_eq!(wallet::get_wallet_handle(), 0);
    }

    #[test]
    fn test_error_c_message() {
        init!("true");
        let c_message = CStringUtils::c_str_to_string(vcx_error_c_message(0)).unwrap().unwrap();
        assert_eq!(c_message, error::SUCCESS.message);

        let c_message = CStringUtils::c_str_to_string(vcx_error_c_message(1001)).unwrap().unwrap();
        assert_eq!(c_message, error::UNKNOWN_ERROR.message);

        let c_message = CStringUtils::c_str_to_string(vcx_error_c_message(100100)).unwrap().unwrap();
        assert_eq!(c_message, error::UNKNOWN_ERROR.message);

        let c_message = CStringUtils::c_str_to_string(vcx_error_c_message(1021)).unwrap().unwrap();
        assert_eq!(c_message, error::INVALID_ATTRIBUTES_STRUCTURE.message);
    }

    #[test]
    fn test_vcx_version() {
        let return_version = CStringUtils::c_str_to_string(vcx_version()).unwrap().unwrap();
        assert!(return_version.len() > 5);
    }

    #[test]
    fn test_vcx_update_institution_info() {
        init!("true");
        let new_name = "new_name";
        let new_url = "http://www.evernym.com";
        assert_ne!(new_name, &settings::get_config_value(::settings::CONFIG_INSTITUTION_NAME).unwrap());
        assert_ne!(new_url, &settings::get_config_value(::settings::CONFIG_INSTITUTION_LOGO_URL).unwrap());

        assert_eq!(error::SUCCESS.code_num, vcx_update_institution_info(CString::new(new_name.to_string()).unwrap().into_raw(),
                                                                        CString::new(new_url.to_string()).unwrap().into_raw()));

        assert_eq!(new_name, &settings::get_config_value(::settings::CONFIG_INSTITUTION_NAME).unwrap());
        assert_eq!(new_url, &settings::get_config_value(::settings::CONFIG_INSTITUTION_LOGO_URL).unwrap());
        ::settings::set_defaults();
    }

    // This test is ignored because it sets up logging, which can only be done
    // once per process.
    #[ignore]
    #[cfg(feature = "agency")]
    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_with_logging_config() {
        init!("ledger");
        wallet::close_wallet().unwrap();
        pool::close().unwrap();
        let content = create_config_util(Some("debug"));
        let cb = return_types_u32::Return_U32::new().unwrap();
        assert_eq!(vcx_init_with_config(cb.command_handle,
                                        CString::new(content).unwrap().into_raw(),
                                        Some(cb.get_callback())),
                   error::SUCCESS.code_num);
        cb.receive(Some(Duration::from_secs(10))).unwrap();
        assert_ne!(get_pool_handle().unwrap(), 0);
        debug!("This statement should log");
    }

    #[test]
    fn get_current_error_works_for_no_error() {
        ::error::reset_current_error();

        let mut error_json_p: *const c_char = ptr::null();

        vcx_get_current_error(&mut error_json_p);
        assert_eq!(None, CStringUtils::c_str_to_string(error_json_p).unwrap());
    }

    #[test]
    fn get_current_error_works_for_sync_error() {
        ::api::utils::vcx_provision_agent(ptr::null());

        let mut error_json_p: *const c_char = ptr::null();
        vcx_get_current_error(&mut error_json_p);
        assert!(CStringUtils::c_str_to_string(error_json_p).unwrap().is_some());
    }

    #[test]
    fn get_current_error_works_for_async_error() {
        extern fn cb(storage_handle: u32,
                     err: u32,
                     config: *const c_char) {
            let mut error_json_p: *const c_char = ptr::null();
            vcx_get_current_error(&mut error_json_p);
            assert!(CStringUtils::c_str_to_string(error_json_p).unwrap().is_some());
        }

        let config = CString::new("{}").unwrap();
        ::api::utils::vcx_agent_provision_async(0, config.as_ptr(), Some(cb));
        ::std::thread::sleep(::std::time::Duration::from_secs(1));
    }

    #[test]
    fn test_vcx_set_active_txn_author_agreement_meta() {
        init!("true");
        assert!(&settings::get_config_value(::settings::CONFIG_TXN_AUTHOR_AGREEMENT).is_err());

        let text = "text";
        let version = "1.0.0";
        let acc_mech_type = "type 1";
        let time_of_acceptance = 123456789;

        assert_eq!(error::SUCCESS.code_num, vcx_set_active_txn_author_agreement_meta(CString::new(text.to_string()).unwrap().into_raw(),
                                                                                CString::new(version.to_string()).unwrap().into_raw(),
                                                                                ::std::ptr::null(),
                                                                                CString::new(acc_mech_type.to_string()).unwrap().into_raw(),
                                                                                time_of_acceptance));

        let expected = json!({
            "text": text,
            "version": version,
            "acceptanceMechanismType": acc_mech_type,
            "timeOfAcceptance": time_of_acceptance,
        });

        let auth_agreement = settings::get_config_value(::settings::CONFIG_TXN_AUTHOR_AGREEMENT).unwrap();
        let auth_agreement = ::serde_json::from_str::<::serde_json::Value>(&auth_agreement).unwrap();

        assert_eq!(expected, auth_agreement);

        ::settings::set_defaults();
    }

    #[test]
    fn test_vcx_get_ledger_author_agreement() {
        init!("true");
        let cb = return_types_u32::Return_U32_STR::new().unwrap();
        assert_eq!(vcx_get_ledger_author_agreement(cb.command_handle,
                                                   Some(cb.get_callback())), error::SUCCESS.code_num);
        let agreement = cb.receive(Some(Duration::from_secs(2))).unwrap();
        assert_eq!(::utils::constants::DEFAULT_AUTHOR_AGREEMENT, agreement.unwrap());
    }

    fn get_settings() -> String {
        json!({
            settings::CONFIG_AGENCY_DID:           settings::get_config_value(settings::CONFIG_AGENCY_DID).unwrap(),
            settings::CONFIG_AGENCY_VERKEY:        settings::get_config_value(settings::CONFIG_AGENCY_VERKEY).unwrap(),
            settings::CONFIG_AGENCY_ENDPOINT:      settings::get_config_value(settings::CONFIG_AGENCY_ENDPOINT).unwrap(),
            settings::CONFIG_REMOTE_TO_SDK_DID:    settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_DID).unwrap(),
            settings::CONFIG_REMOTE_TO_SDK_VERKEY: settings::get_config_value(settings::CONFIG_REMOTE_TO_SDK_VERKEY).unwrap(),
            settings::CONFIG_SDK_TO_REMOTE_DID:    settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_DID).unwrap(),
            settings::CONFIG_SDK_TO_REMOTE_VERKEY: settings::get_config_value(settings::CONFIG_SDK_TO_REMOTE_VERKEY).unwrap(),
            settings::CONFIG_INSTITUTION_NAME:     settings::get_config_value(settings::CONFIG_INSTITUTION_NAME).unwrap(),
            settings::CONFIG_INSTITUTION_DID:      settings::get_config_value(settings::CONFIG_INSTITUTION_DID).unwrap(),
            settings::CONFIG_INSTITUTION_LOGO_URL: settings::get_config_value(settings::CONFIG_INSTITUTION_LOGO_URL).unwrap(),
            settings::CONFIG_PAYMENT_METHOD:       settings::get_config_value(settings::CONFIG_PAYMENT_METHOD).unwrap()
        }).to_string()
    }

    #[cfg(feature = "pool_tests")]
    #[test]
    fn test_init_minimal() {
        init!("ledger");
        let content = get_settings();
        settings::clear_config();
        // Store settings and handles
        let config = CString::new(content).unwrap().into_raw();
        let wallet_handle = ::utils::libindy::wallet::get_wallet_handle();
        let pool_handle = ::utils::libindy::pool::get_pool_handle().unwrap();
        assert!(wallet_handle > 0);
        assert!(pool_handle > 0);
        // Reset handles to 0
        assert_eq!(::api::utils::vcx_pool_set_handle(0), 0);
        assert_eq!(::api::wallet::vcx_wallet_set_handle(0), 0);
        // Test for errors when handles not set
        assert_ne!(error::SUCCESS.code_num, vcx_init_minimal(config));
        ::api::wallet::vcx_wallet_set_handle(wallet_handle);
        assert_ne!(error::SUCCESS.code_num, vcx_init_minimal(config));
        ::api::utils::vcx_pool_set_handle(pool_handle);
        // NOTE: handles are set independently, test config with no wallet or pool
        assert_eq!(error::SUCCESS.code_num, vcx_init_minimal(config));
        // test that wallet and pool are operational
        ::utils::libindy::anoncreds::tests::create_and_store_credential(::utils::constants::DEFAULT_SCHEMA_ATTRS, false);
    }

    #[test]
    fn test_no_agency_config() {
        settings::clear_config();
        settings::set_config_value(settings::CONFIG_ENABLE_TEST_MODE,"true");
        let config = json!({ "institution_name": "faber",
                             "institution_did": "44x8p4HubxzUK1dwxcc5FU",
                             "institution_verkey": "444MFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE"}).to_string();
        let config = CString::new(config).unwrap().into_raw();
        ::api::wallet::vcx_wallet_set_handle(1);
        ::api::utils::vcx_pool_set_handle(1);
        assert_eq!(vcx_init_minimal(config), error::SUCCESS.code_num);

        let cred_handle = ::issuer_credential::from_string(::utils::constants::DEFAULT_SERIALIZED_ISSUER_CREDENTIAL).unwrap();
        let connection_handle = ::connection::from_string(::utils::constants::DEFAULT_CONNECTION).unwrap();

        let (offer, _) = ::issuer_credential::generate_credential_offer_msg(cred_handle, connection_handle).unwrap();
        let mycred = ::credential::credential_create_with_offer("test1", &offer).unwrap();
        let request = ::credential::generate_credential_request_msg(mycred, connection_handle).unwrap();
        ::issuer_credential::update_state(cred_handle, Some(request)).unwrap();
        let cred = ::issuer_credential::generate_credential_msg(cred_handle, connection_handle).unwrap();
        ::credential::update_state(mycred, Some(cred)).unwrap();
        assert!(::credential::get_state(mycred).unwrap() == VcxStateType::VcxStateAccepted as u32);
    }

    #[test]
    fn test_invalid_agency_config() {
        let config = json!({ "institution_name": "faber",
                             "institution_did": "44x8p4HubxzUK1dwxcc5FU",
                             "institution_verkey": "444MFrZjXDoi2Vc8Mm14Ys112tEZdDegBZZoembFEATE"}).to_string();
        let config = CString::new(config).unwrap().into_raw();
        ::api::wallet::vcx_wallet_set_handle(1);
        ::api::utils::vcx_pool_set_handle(1);
        assert_eq!(vcx_init_minimal(config), error::SUCCESS.code_num);
        let rc = vcx_connection_create(0,
                                       CString::new("test_create_fails").unwrap().into_raw(),
                                       None);
        assert_eq!(rc, error::INVALID_OPTION.code_num);
        let cb = return_types_u32::Return_U32_U32::new().unwrap();
        let rc = vcx_connection_create(cb.command_handle,
                                       ptr::null(),
                                       Some(cb.get_callback()));
        assert_eq!(rc, error::INVALID_OPTION.code_num);
    }
}


text:
import { expectFileToMatch } from '../../../utils/fs';
import { ng } from '../../../utils/process';
import { useCIChrome } from '../../../utils/project';

export default function() {
  return ng('generate', 'application', 'app2')
    .then(() => expectFileToMatch('angular.json', /\"app2\":/))
    .then(() => useCIChrome('projects/app2'))
    .then(() => ng('test', 'app2', '--watch=false'));
}


text:
package com.streamsets.pipeline.stage.destination.datalake.gen2;

import com.streamsets.pipeline.api.ConfigDefBean;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.stage.conf.DataLakeGen2BaseConfig;
import com.streamsets.pipeline.stage.destination.hdfs.HdfsTargetConfigBean;

import java.util.List;

public class DataLakeGen2TargetConfigBean extends HdfsTargetConfigBean {

  @ConfigDefBean
  public DataLakeGen2BaseConfig dataLakeConfig;

  @Override
  public void init(final Stage.Context context, List<Stage.ConfigIssue> issues) {
    dataLakeConfig.init(this, context, issues);
    super.init(context, issues);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Eurofurence.Companion.ViewModel.Local;

namespace Eurofurence.Companion.ViewModel.Behaviors
{
    public class MainMenuDataTemplateSelector : DataTemplateSelector
    {

        public DataTemplate MenuItemTemplate { get; set; }
        public DataTemplate MenuSpacerTemplate { get; set; }

        protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
        {
            if (item is MenuItemViewModel)
                return MenuItemTemplate;

            return MenuSpacerTemplate;
        }
    }
}


text:
#ifndef SCRIPTCONTAINER_H
#define SCRIPTCONTAINER_H

#include "can_structs.h"
#include "canfilter.h"
#include "bus_protocols/isotp_handler.h"
#include "bus_protocols/isotp_message.h"
#include "bus_protocols/uds_handler.h"

#include <QElapsedTimer>
#include <QJSEngine>
#include <QTimer>
#include <qlistwidget.h>

class ScriptingWindow;

class CANScriptHelper: public QObject
{
    Q_OBJECT
public:
    CANScriptHelper(QJSEngine *engine);

public slots:
    void setFilter(QJSValue id, QJSValue mask, QJSValue bus);
    void clearFilters();
    void sendFrame(QJSValue bus, QJSValue id, QJSValue length, QJSValue data);
    void setRxCallback(QJSValue cb);

private slots:
    void gotTargettedFrame(const CANFrame &frame);

private:
    QList<CANFilter> filters;
    QJSValue gotFrameFunction;
    QJSEngine *scriptEngine;
};

class ISOTPScriptHelper: public QObject
{
    Q_OBJECT
public:
    ISOTPScriptHelper(QJSEngine *engine);
public slots:
    void setFilter(QJSValue id, QJSValue mask, QJSValue bus);
    void clearFilters();
    void sendISOTP(QJSValue bus, QJSValue id, QJSValue length, QJSValue data);
    void setRxCallback(QJSValue cb);
private slots:
    void newISOMessage(ISOTP_MESSAGE msg);
private:
    QJSValue gotFrameFunction;
    QJSEngine *scriptEngine;
    ISOTP_HANDLER *handler;
};

class UDSScriptHelper: public QObject
{
    Q_OBJECT
public:
    UDSScriptHelper(QJSEngine *engine);
public slots:
    void setFilter(QJSValue id, QJSValue mask, QJSValue bus);
    void clearFilters();
    void sendUDS(QJSValue bus, QJSValue id, QJSValue service, QJSValue sublen, QJSValue subFunc, QJSValue length, QJSValue data);
    void setRxCallback(QJSValue cb);
private slots:
    void newUDSMessage(UDS_MESSAGE msg);
private:
    QJSValue gotFrameFunction;
    QJSEngine *scriptEngine;
    UDS_HANDLER *handler;
};

class ScriptContainer : public QObject
{
    Q_OBJECT

public:
    ScriptContainer();
    virtual ~ScriptContainer();
    void setScriptWindow(ScriptingWindow *win);

    QString fileName;
    QString filePath;
    QString scriptText;

/*
  Anything registered as a public slot on this class and that takes either no arguments
  or only QJSValue arguments will be callable from scripts via  host.XXX calls. So, have at it, champ.
*/
public slots:
    void compileScript();
    void setTickInterval(QJSValue interval);
    void log(QJSValue logString);
    void addParameter(QJSValue name);
    void updateValuesTable(QTableWidget *widget);
    void updateParameter(QString name, QString value);

signals:
    void sendLog(QString text);

private slots:
    void tick();

private:
    QJSEngine *scriptEngine;
    QJSValue compiledScript;
    QJSValue setupFunction;
    QJSValue tickFunction;
    QTimer timer;
    ScriptingWindow *window;
    CANScriptHelper *canHelper;
    ISOTPScriptHelper *isoHelper;
    UDSScriptHelper *udsHelper;
    QVector<QString> scriptParams;
};

#endif // SCRIPTCONTAINER_H


text:
          <button type="button" class="navbar-toggle" ng-click="goToPage('/settings')">

          </button>

Favourite Brands

All From Favourite Places

Top Ratings First

Shouts Only

Near By

Search

Favourite


text:
package org.harms.jpa.entitymanager;

import org.harms.orm.upgrade.Jpa21TestDao;
import org.harms.orm.upgrade.Jpa21TestEntity;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.ejb.EJB;
import java.util.Random;

/**
 * System test for testing against JPA 2.1 (Hibernate 5.2) With Wildfly 8.2.
 *
 */
@RunWith(Arquillian.class)
public class Jpa21Wildfly82IT {

    @Deployment
    public static WebArchive createDeployment() {
        WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "jpa2wildfly.war")
                .addClass(Jpa21TestDao.class)
                .addClass(Jpa21TestEntity.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource("META-INF/persistence.xml")
                .addAsWebInfResource("META-INF/jboss-deployment-structure.xml");
        System.out.println("Jar :"+webArchive.toString(true));
        return webArchive;
    }

    @EJB
    Jpa21TestDao dao;

    @Test
    public void testWithHibernate5() throws Exception {
        Random rand = new Random();

        Jpa21TestEntity entity = new Jpa21TestEntity();
        entity.setId((long) (rand.nextInt(50) + 1));
        Jpa21TestEntity saveEntity = dao.save(entity);
        Assert.assertEquals(entity.getId(),saveEntity.getId());
    }
}