################################################################
#
# This file contains following Group Replication helper macros:
#
# * Setsession - SESSION_NAME
# * Connect_to_instance - SESSION_NAME_PREFIX SERVER_INDEX TCP_PORT
# * Connect_to_all_mysqld_instances - SESSION_NAME_PREFIX NUMBER_OF_SERVERS_TO_INITIALIZE
# * GR_clear_bootstrap_group - NUMBER_OF_SERVERS_TO_INITIALIZE
# * GR_start_and_bootstrap - NUMBER_OF_SERVERS_TO_INITIALIZE GROUP_NAME EXPECTED_STATE
# * GR_start - GROUP_NAME EXPECTED_STATE
# * GR_stop
# * GR_start_applier_sql_thread
# * GR_stop_applier_sql_thread
# * GR_wait_for_number_of_members - EXPECTED_NUMBER_OF_MEMBERS
# * GR_wait_for_member_state - EXPECTED_STATE
# * GR_wait_for_uuid_and_member_state - UUID EXPECTED_STATE
#

#
## General macros
#
-->macro Setsession	%NAME%
quiet;
echo [connection %NAME%];
setsession %NAME%;
noquiet;
-->endmacro

-->macro Connect_to_instance	%PREFIX%	%INSTANCE_ID%	%PORT%
varlet %OPTION_CLIENT_PORT% %PORT%;
newsession %PREFIX%_%INSTANCE_ID%	%OPTION_CLIENT_USER%;
-->endmacro

-->macro Connect_to_all_mysqld_instances	%PREFIX%	%NUMBER_OF_SERVERS%
repeat %NUMBER_OF_SERVERS%	%ITERATION%;
varlet %ITERATION_SESSION% %ITERATION%;
varinc %ITERATION_SESSION% 1;
varlet %PORT_NAME% %SERVER_XPORT_%ITERATION_SESSION%%;
callmacro Connect_to_instance	%PREFIX%	%ITERATION_SESSION%	%PORT_NAME%;
endrepeat;
-->endmacro

#
## Group-replication specific macros
#
-->macro GR_clear_bootstrap_group %NUMBER_OF_SERVERS%
noquery_result;
repeat %NUMBER_OF_SERVERS%	%ITERATION%;
varlet %__SESSION% %NUMBER_OF_SERVERS%;
varinc %__SESSION% -%ITERATION%;
callmacro Setsession	server_%__SESSION%;
SET GLOBAL group_replication_bootstrap_group= 0;
endrepeat;
query_result;
-->endmacro

-->macro GR_start_and_bootstrap	%NUMBER_OF_SERVERS%	%GR_NAME%	%EXPECTED_STATE%
callmacro Setsession	server_1;
noquery_result;
SET GLOBAL group_replication_bootstrap_group= 1;
query_result;
callmacro GR_start	%GR_NAME%	%EXPECTED_STATE%;
callmacro GR_clear_bootstrap_group	%NUMBER_OF_SERVERS%;
-->endmacro

-->macro GR_start	%GR_NAME%	%EXPECTED_STATE%
noquery_result;
varsub %GR_NAME%;
SET GLOBAL group_replication_group_name='%GR_NAME%';
START GROUP_REPLICATION;
query_result;

callmacro GR_wait_for_member_state	%EXPECTED_STATE%;
-->endmacro

-->macro GR_stop
noquery_result;
STOP GROUP_REPLICATION;
quiet;
wait_for 1	SELECT COUNT(*)=1
               FROM performance_schema.replication_connection_status connection_status
               WHERE connection_status.channel_name="group_replication_applier"
                  AND connection_status.service_state="OFF";
wait_for 1	SELECT @@GLOBAL.super_read_only=1;
wait_for 1	SELECT @@GLOBAL.read_only=1;
noquiet;
SET GLOBAL read_only= FALSE;
query_result;
-->endmacro

-->macro GR_start_applier_sql_thread
noquery_result;
START SLAVE SQL_THREAD FOR CHANNEL "group_replication_applier";
quiet;
wait_for 1	SELECT service_state="ON"
                FROM performance_schema.replication_applier_status
                WHERE channel_name="group_replication_applier";
noquiet;
query_result;
-->endmacro

-->macro GR_stop_applier_sql_thread
noquery_result;
STOP SLAVE SQL_THREAD FOR CHANNEL "group_replication_applier";
quiet;
wait_for 1	SELECT service_state="OFF"
                FROM performance_schema.replication_applier_status
                WHERE channel_name="group_replication_applier";
noquiet;
query_result;
-->endmacro

-->macro GR_wait_for_number_of_members	%EXPECTED_NUMBER_OF_MEMBERS%
echo [waiting for '%EXPECTED_NUMBER_OF_MEMBERS%' members];
quiet;
noquery_result;
wait_for %EXPECTED_NUMBER_OF_MEMBERS%	SELECT COUNT(*)
                FROM performance_schema.replication_group_members;
noquiet;
query_result;
-->endmacro

-->macro GR_wait_for_member_state	%STATE%
echo [waiting for member_state to be equal '%STATE%'];
quiet;
noquery_result;
wait_for 1	SELECT COUNT(*)=1 FROM performance_schema.replication_group_members
  WHERE member_id=@@SERVER_UUID AND
  member_state="%STATE%";
stmtsql SELECT COUNT(*)=1
                FROM performance_schema.replication_group_members group_members
                WHERE group_members.member_id= @@SERVER_UUID
                  AND group_members.member_state="ONLINE"
                  AND group_members.member_role = "PRIMARY"
                  AND group_members.member_version =
                      (SELECT member_version FROM performance_schema.replication_group_members
                          ORDER BY member_version ASC LIMIT 1);
recvtovar %IS_PRIMARY%;

## Workaround for missing 'if' statement in mysqlxtest syntax.
wait_for 1	SELECT @@GLOBAL.read_only = '0' OR !%IS_PRIMARY%;
noquiet;
query_result;
-->endmacro

-->macro GR_wait_for_uuid_and_member_state	%UUID%	%STATE%
echo [waiting for concrete member with member_state to be equal '%STATE%'];
quiet;
noquery_result;
wait_for 1	SELECT COUNT(*)=1 FROM performance_schema.replication_group_members
  WHERE member_id='%UUID%' AND
  member_state="%STATE%";
stmtsql SELECT COUNT(*)=1
                FROM performance_schema.replication_group_members group_members
                WHERE group_members.member_id like '%UUID%'
                  AND group_members.member_state like "%STATE%"
                  AND group_members.member_role = "PRIMARY"
                  AND group_members.member_version =
                      (SELECT member_version FROM performance_schema.replication_group_members
                          ORDER BY member_version ASC LIMIT 1);
recvtovar %IS_PRIMARY%;

## Workaround for missing 'if' statement in mysqlxtest syntax.
wait_for 1	SELECT @@GLOBAL.read_only = '0' OR !%IS_PRIMARY%;
noquiet;
query_result;
-->endmacro


<Project Sdk="Microsoft.NET.Sdk">
  <Import Project="..\..\..\buildtools\common.props" />
  <PropertyGroup>
    <Description>Amazon Lambda .NET Core support - CloudWatchLogsEvents package.</Description>
    <TargetFrameworks>netstandard2.0;netcoreapp3.1</TargetFrameworks>
    <AssemblyTitle>Amazon.Lambda.CloudWatchLogsEvents</AssemblyTitle>
    <VersionPrefix>2.0.0</VersionPrefix>
    <AssemblyName>Amazon.Lambda.CloudWatchLogsEvents</AssemblyName>
    <PackageId>Amazon.Lambda.CloudWatchLogsEvents</PackageId>
    <PackageTags>AWS;Amazon;Lambda</PackageTags>
  </PropertyGroup>

  <PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
    <DefineConstants>NETCOREAPP_3_1</DefineConstants>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
    <PackageReference Include="System.Runtime.Serialization.Primitives" Version="4.1.1" />
  </ItemGroup>
</Project>


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2020 Playtika
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.playtika.test.clickhouse;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.testcontainers.containers.GenericContainer;

import static org.assertj.core.api.Assertions.assertThat;

@Slf4j
@SpringBootTest(classes = EmbeddedClickHouseDisableTest.TestConfiguration.class,
        properties = "embedded.clickhouse.enabled=false")
public class EmbeddedClickHouseDisableTest {

    @Autowired
    ConfigurableListableBeanFactory beanFactory;

    @Test
    public void contextLoads() {
        String[] containers = beanFactory.getBeanNamesForType(GenericContainer.class);
        String[] postProcessors = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class);

        assertThat(containers).isEmpty();
        assertThat(postProcessors).doesNotContain(
                "clickHouseContainerDependencyPostProcessor");
    }

    @Configuration
    static class TestConfiguration {
    }
}


#!/bin/sh

cdir=$(cd "$(dirname "$0")"; pwd)
#echo ${cdir}
cd ${cdir}/..

#echo `pwd`

usage()
{
        echo "usage: `basename $0` start|stop nodename"
	echo "       must exist configfile named node_nodename in dir config"

}

OPT=$1
PROCESS=$2

if [ $# -ne 2 ]; then
        usage
        exit 1
fi
case $OPT in
        start|Start) echo "Starting..$PROCESS"
        # some process to go here

		if [ ! -d "./db/$PROCESS"  ] ;then
			mkdir -p ./db/$PROCESS
		fi
		if [ ! -f "./pid/node_$PROCESS" ];then
			touch ./pid/node_$PROCESS
		fi

		if [ -f ./config/node_$PROCESS.conf  ]; then

			m_pid=$(cat ./pid/node_$PROCESS)

			echo "$m_pid"
			if [  "$m_pid"x != ""x   ];then
				echo "Already running,PID:$m_pid"
			else
				icegridnode --Ice.Config=./config/node_$PROCESS.conf --nochdir --daemon --pidfile ./pid/node_$PROCESS
			fi
		else

		 usage

		fi

        ;;
        stop|Stop) echo "Stopping..$PROCESS"
        # some process to go here

                if [ -f ./pid/node_$PROCESS ]; then

			m_pid=$(cat ./pid/node_$PROCESS)

                        echo "$m_pid"
                        if [  "$m_pid"x != ""x   ];then
				kill $m_pid
				:>./pid/node_$PROCESS
			else
				echo "not running..."
			fi

		else
		  echo "not find pidfile"
		fi

        ;;
        *)usage
        ;;
esac


/*
 * OSS compatible sequencer driver
 *
 * Timer control routines
 *
 * Copyright (C) 1998,99 Takashi Iwai <tiwai@suse.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 */

#include "seq_oss_timer.h"
#include "seq_oss_event.h"
#include <sound/seq_oss_legacy.h>
#include <linux/slab.h>

/*
 */
#define MIN_OSS_TEMPO		8
#define MAX_OSS_TEMPO		360
#define MIN_OSS_TIMEBASE	1
#define MAX_OSS_TIMEBASE	1000

/*
 */
static void calc_alsa_tempo(struct seq_oss_timer *timer);
static int send_timer_event(struct seq_oss_devinfo *dp, int type, int value);

/*
 * create and register a new timer.
 * if queue is not started yet, start it.
 */
struct seq_oss_timer *
snd_seq_oss_timer_new(struct seq_oss_devinfo *dp)
{
	struct seq_oss_timer *rec;

	rec = kzalloc(sizeof(*rec), GFP_KERNEL);
	if (rec == NULL)
		return NULL;

	rec->dp = dp;
	rec->cur_tick = 0;
	rec->realtime = 0;
	rec->running = 0;
	rec->oss_tempo = 60;
	rec->oss_timebase = 100;
	calc_alsa_tempo(rec);

	return rec;
}

/*
 * delete timer.
 * if no more timer exists, stop the queue.
 */
void
snd_seq_oss_timer_delete(struct seq_oss_timer *rec)
{
	if (rec) {
		snd_seq_oss_timer_stop(rec);
		kfree(rec);
	}
}

/*
 * process one timing event
 * return 1 : event proceseed -- skip this event
 *        0 : not a timer event -- enqueue this event
 */
int
snd_seq_oss_process_timer_event(struct seq_oss_timer *rec, union evrec *ev)
{
	abstime_t parm = ev->t.time;

	if (ev->t.code == EV_TIMING) {
		switch (ev->t.cmd) {
		case TMR_WAIT_REL:
			parm += rec->cur_tick;
			rec->realtime = 0;
			/* continue to next */
		case TMR_WAIT_ABS:
			if (parm == 0) {
				rec->realtime = 1;
			} else if (parm >= rec->cur_tick) {
				rec->realtime = 0;
				rec->cur_tick = parm;
			}
			return 1;	/* skip this event */

		case TMR_START:
			snd_seq_oss_timer_start(rec);
			return 1;

		}
	} else if (ev->s.code == SEQ_WAIT) {
		/* time = from 1 to 3 bytes */
		parm = (ev->echo >> 8) & 0xffffff;
		if (parm > rec->cur_tick) {
			/* set next event time */
			rec->cur_tick = parm;
			rec->realtime = 0;
		}
		return 1;
	}

	return 0;
}

/*
 * convert tempo units
 */
static void
calc_alsa_tempo(struct seq_oss_timer *timer)
{
	timer->tempo = (60 * 1000000) / timer->oss_tempo;
	timer->ppq = timer->oss_timebase;
}

/*
 * dispatch a timer event
 */
static int
send_timer_event(struct seq_oss_devinfo *dp, int type, int value)
{
	struct snd_seq_event ev;

	memset(&ev, 0, sizeof(ev));
	ev.type = type;
	ev.source.client = dp->cseq;
	ev.source.port = 0;
	ev.dest.client = SNDRV_SEQ_CLIENT_SYSTEM;
	ev.dest.port = SNDRV_SEQ_PORT_SYSTEM_TIMER;
	ev.queue = dp->queue;
	ev.data.queue.queue = dp->queue;
	ev.data.queue.param.value = value;
	return snd_seq_kernel_client_dispatch(dp->cseq, &ev, 1, 0);
}

/*
 * set queue tempo and start queue
 */
int
snd_seq_oss_timer_start(struct seq_oss_timer *timer)
{
	struct seq_oss_devinfo *dp = timer->dp;
	struct snd_seq_queue_tempo tmprec;

	if (timer->running)
		snd_seq_oss_timer_stop(timer);

	memset(&tmprec, 0, sizeof(tmprec));
	tmprec.queue = dp->queue;
	tmprec.ppq = timer->ppq;
	tmprec.tempo = timer->tempo;
	snd_seq_set_queue_tempo(dp->cseq, &tmprec);

	send_timer_event(dp, SNDRV_SEQ_EVENT_START, 0);
	timer->running = 1;
	timer->cur_tick = 0;
	return 0;
}

/*
 * stop queue
 */
int
snd_seq_oss_timer_stop(struct seq_oss_timer *timer)
{
	if (! timer->running)
		return 0;
	send_timer_event(timer->dp, SNDRV_SEQ_EVENT_STOP, 0);
	timer->running = 0;
	return 0;
}

/*
 * continue queue
 */
int
snd_seq_oss_timer_continue(struct seq_oss_timer *timer)
{
	if (timer->running)
		return 0;
	send_timer_event(timer->dp, SNDRV_SEQ_EVENT_CONTINUE, 0);
	timer->running = 1;
	return 0;
}

/*
 * change queue tempo
 */
int
snd_seq_oss_timer_tempo(struct seq_oss_timer *timer, int value)
{
	if (value < MIN_OSS_TEMPO)
		value = MIN_OSS_TEMPO;
	else if (value > MAX_OSS_TEMPO)
		value = MAX_OSS_TEMPO;
	timer->oss_tempo = value;
	calc_alsa_tempo(timer);
	if (timer->running)
		send_timer_event(timer->dp, SNDRV_SEQ_EVENT_TEMPO, timer->tempo);
	return 0;
}

/*
 * ioctls
 */
int
snd_seq_oss_timer_ioctl(struct seq_oss_timer *timer, unsigned int cmd, int __user *arg)
{
	int value;

	if (cmd == SNDCTL_SEQ_CTRLRATE) {
		/* if *arg == 0, just return the current rate */
		if (get_user(value, arg))
			return -EFAULT;
		if (value)
			return -EINVAL;
		value = ((timer->oss_tempo * timer->oss_timebase) + 30) / 60;
		return put_user(value, arg) ? -EFAULT : 0;
	}

	if (timer->dp->seq_mode == SNDRV_SEQ_OSS_MODE_SYNTH)
		return 0;

	switch (cmd) {
	case SNDCTL_TMR_START:
		return snd_seq_oss_timer_start(timer);
	case SNDCTL_TMR_STOP:
		return snd_seq_oss_timer_stop(timer);
	case SNDCTL_TMR_CONTINUE:
		return snd_seq_oss_timer_continue(timer);
	case SNDCTL_TMR_TEMPO:
		if (get_user(value, arg))
			return -EFAULT;
		return snd_seq_oss_timer_tempo(timer, value);
	case SNDCTL_TMR_TIMEBASE:
		if (get_user(value, arg))
			return -EFAULT;
		if (value < MIN_OSS_TIMEBASE)
			value = MIN_OSS_TIMEBASE;
		else if (value > MAX_OSS_TIMEBASE)
			value = MAX_OSS_TIMEBASE;
		timer->oss_timebase = value;
		calc_alsa_tempo(timer);
		return 0;

	case SNDCTL_TMR_METRONOME:
	case SNDCTL_TMR_SELECT:
	case SNDCTL_TMR_SOURCE:
		/* not supported */
		return 0;
	}
	return 0;
}


#!/usr/bin/env python3

from distutils.core import setup

print(__file__)
setup(name='rfnoc',
      version='1.0',
      description='desc',
      author='ettus',
      package_data={'rfnoc': ['templates/*.v.mako', 'templates/modules/*.v.mako']},
      scripts=['bin/rfnoc_image_builder'],
      packages=['rfnoc'],
      install_requires=['ruamel.yaml', 'Mako'],
     )


- key: kafka
  title: "Kafka"
  description: >
    Kafka module
  short_config: false
  release: ga
  fields:
    - name: kafka
      type: group
      description: >
      fields:
        - name: broker
          type: group
          description: >
            Broker Consumer Group Information have been read from (Broker handling
            the consumer group).
          fields:
            - name: id
              type: long
              description: >
                Broker id

            - name: address
              type: keyword
              description: >
                Broker advertised address

        - name: topic.name
          type: keyword
          description: >
            Topic name

        - name: topic.error.code
          type: long
          description: >
            Topic error code.

        - name: partition.id
          type: long
          description: >
            Partition id.

        - name: partition.topic_id
          type: keyword
          description:
            Unique id of the partition in the topic.

        - name: partition.topic_broker_id
          type: keyword
          description:
            Unique id of the partition in the topic and the broker.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="50dp">

    <ProgressBar
        android:id="@+id/rotation_footer_progress"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminateDrawable="@drawable/progress_gear" />
</RelativeLayout>


// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build amd64,freebsd

package unix

import (
	"syscall"
	"unsafe"
)

func Getpagesize() int { return 4096 }

func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) }

func NsecToTimespec(nsec int64) (ts Timespec) {
	ts.Sec = nsec / 1e9
	ts.Nsec = nsec % 1e9
	return
}

func NsecToTimeval(nsec int64) (tv Timeval) {
	nsec += 999 // round up to microsecond
	tv.Usec = nsec % 1e9 / 1e3
	tv.Sec = int64(nsec / 1e9)
	return
}

func SetKevent(k *Kevent_t, fd, mode, flags int) {
	k.Ident = uint64(fd)
	k.Filter = int16(mode)
	k.Flags = uint16(flags)
}

func (iov *Iovec) SetLen(length int) {
	iov.Len = uint64(length)
}

func (msghdr *Msghdr) SetControllen(length int) {
	msghdr.Controllen = uint32(length)
}

func (cmsg *Cmsghdr) SetLen(length int) {
	cmsg.Len = uint32(length)
}

func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
	var writtenOut uint64 = 0
	_, _, e1 := Syscall9(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(count), 0, uintptr(unsafe.Pointer(&writtenOut)), 0, 0, 0)

	written = int(writtenOut)

	if e1 != 0 {
		err = e1
	}
	return
}

func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)


(**************************************************************************)
(*                                                                        *)
(*                                 OCaml                                  *)
(*                                                                        *)
(*             Xavier Leroy, projet Cristal, INRIA Rocquencourt           *)
(*                                                                        *)
(*   Copyright 1996 Institut National de Recherche en Informatique et     *)
(*     en Automatique.                                                    *)
(*                                                                        *)
(*   All rights reserved.  This file is distributed under the terms of    *)
(*   the GNU Lesser General Public License version 2.1, with the          *)
(*   special exception on linking described in the file LICENSE.          *)
(*                                                                        *)
(**************************************************************************)

(* Basic operations on core types *)

open Asttypes
open Types

(**** Sets, maps and hashtables of types ****)

module TypeSet  : Set.S with type elt = type_expr
module TypeMap  : Map.S with type key = type_expr
module TypeHash : Hashtbl.S with type key = type_expr

(**** Levels ****)

val generic_level: int

val newty2: int -> type_desc -> type_expr
        (* Create a type *)
val newgenty: type_desc -> type_expr
        (* Create a generic type *)
val newgenvar: ?name:string -> unit -> type_expr
        (* Return a fresh generic variable *)

(* Use Tsubst instead
val newmarkedvar: int -> type_expr
        (* Return a fresh marked variable *)
val newmarkedgenvar: unit -> type_expr
        (* Return a fresh marked generic variable *)
*)

(**** Types ****)

val is_Tvar: type_expr -> bool
val is_Tunivar: type_expr -> bool
val is_Tconstr: type_expr -> bool
val dummy_method: label
val default_mty: module_type option -> module_type

val repr: type_expr -> type_expr
        (* Return the canonical representative of a type. *)

val field_kind_repr: field_kind -> field_kind
        (* Return the canonical representative of an object field
           kind. *)

val commu_repr: commutable -> commutable
        (* Return the canonical representative of a commutation lock *)

(**** polymorphic variants ****)

val row_repr: row_desc -> row_desc
        (* Return the canonical representative of a row description *)
val row_field_repr: row_field -> row_field
val row_field: label -> row_desc -> row_field
        (* Return the canonical representative of a row field *)
val row_more: row_desc -> type_expr
        (* Return the extension variable of the row *)
val row_fixed: row_desc -> bool
        (* Return whether the row should be treated as fixed or not *)
val static_row: row_desc -> bool
        (* Return whether the row is static or not *)
val hash_variant: label -> int
        (* Hash function for variant tags *)

val proxy: type_expr -> type_expr
        (* Return the proxy representative of the type: either itself
           or a row variable *)

(**** Utilities for private abbreviations with fixed rows ****)
val row_of_type: type_expr -> type_expr
val has_constr_row: type_expr -> bool
val is_row_name: string -> bool
val is_constr_row: allow_ident:bool -> type_expr -> bool

(**** Utilities for type traversal ****)

val iter_type_expr: (type_expr -> unit) -> type_expr -> unit
        (* Iteration on types *)
val iter_row: (type_expr -> unit) -> row_desc -> unit
        (* Iteration on types in a row *)
val iter_abbrev: (type_expr -> unit) -> abbrev_memo -> unit
        (* Iteration on types in an abbreviation list *)

type type_iterators =
  { it_signature: type_iterators -> signature -> unit;
    it_signature_item: type_iterators -> signature_item -> unit;
    it_value_description: type_iterators -> value_description -> unit;
    it_type_declaration: type_iterators -> type_declaration -> unit;
    it_extension_constructor: type_iterators -> extension_constructor -> unit;
    it_module_declaration: type_iterators -> module_declaration -> unit;
    it_modtype_declaration: type_iterators -> modtype_declaration -> unit;
    it_class_declaration: type_iterators -> class_declaration -> unit;
    it_class_type_declaration: type_iterators -> class_type_declaration -> unit;
    it_module_type: type_iterators -> module_type -> unit;
    it_class_type: type_iterators -> class_type -> unit;
    it_type_kind: type_iterators -> type_kind -> unit;
    it_do_type_expr: type_iterators -> type_expr -> unit;
    it_type_expr: type_iterators -> type_expr -> unit;
    it_path: Path.t -> unit; }
val type_iterators: type_iterators
        (* Iteration on arbitrary type information.
           [it_type_expr] calls [mark_type_node] to avoid loops. *)
val unmark_iterators: type_iterators
        (* Unmark any structure containing types. See [unmark_type] below. *)

val copy_type_desc:
    ?keep_names:bool -> (type_expr -> type_expr) -> type_desc -> type_desc
        (* Copy on types *)
val copy_row:
    (type_expr -> type_expr) ->
    bool -> row_desc -> bool -> type_expr -> row_desc
val copy_kind: field_kind -> field_kind

val save_desc: type_expr -> type_desc -> unit
        (* Save a type description *)
val dup_kind: field_kind option ref -> unit
        (* Save a None field_kind, and make it point to a fresh Fvar *)
val cleanup_types: unit -> unit
        (* Restore type descriptions *)

val lowest_level: int
        (* Marked type: ty.level < lowest_level *)
val pivot_level: int
        (* Type marking: ty.level <- pivot_level - ty.level *)
val mark_type: type_expr -> unit
        (* Mark a type *)
val mark_type_node: type_expr -> unit
        (* Mark a type node (but not its sons) *)
val mark_type_params: type_expr -> unit
        (* Mark the sons of a type node *)
val unmark_type: type_expr -> unit
val unmark_type_decl: type_declaration -> unit
val unmark_extension_constructor: extension_constructor -> unit
val unmark_class_type: class_type -> unit
val unmark_class_signature: class_signature -> unit
        (* Remove marks from a type *)

(**** Memorization of abbreviation expansion ****)

val find_expans: private_flag -> Path.t -> abbrev_memo -> type_expr option
        (* Look up a memorized abbreviation *)
val cleanup_abbrev: unit -> unit
        (* Flush the cache of abbreviation expansions.
           When some types are saved (using [output_value]), this
           function MUST be called just before. *)
val memorize_abbrev:
        abbrev_memo ref ->
        private_flag -> Path.t -> type_expr -> type_expr -> unit
        (* Add an expansion in the cache *)
val forget_abbrev:
        abbrev_memo ref -> Path.t -> unit
        (* Remove an abbreviation from the cache *)

(**** Utilities for labels ****)

val is_optional : arg_label -> bool
val label_name : arg_label -> label

(* Returns the label name with first character '?' or '~' as appropriate. *)
val prefixed_label_name : arg_label -> label

val extract_label :
    label -> (arg_label * 'a) list ->
    arg_label * 'a * (arg_label * 'a) list * (arg_label * 'a) list
    (* actual label, value, before list, after list *)

(**** Utilities for backtracking ****)

type snapshot
        (* A snapshot for backtracking *)
val snapshot: unit -> snapshot
        (* Make a snapshot for later backtracking. Costs nothing *)
val backtrack: snapshot -> unit
        (* Backtrack to a given snapshot. Only possible if you have
           not already backtracked to a previous snapshot.
           Calls [cleanup_abbrev] internally *)
val undo_compress: snapshot -> unit
        (* Backtrack only path compression. Only meaningful if you have
           not already backtracked to a previous snapshot.
           Does not call [cleanup_abbrev] *)

(* Functions to use when modifying a type (only Ctype?) *)
val link_type: type_expr -> type_expr -> unit
        (* Set the desc field of [t1] to [Tlink t2], logging the old
           value if there is an active snapshot *)
val set_level: type_expr -> int -> unit
val set_name:
    (Path.t * type_expr list) option ref ->
    (Path.t * type_expr list) option -> unit
val set_row_field: row_field option ref -> row_field -> unit
val set_univar: type_expr option ref -> type_expr -> unit
val set_kind: field_kind option ref -> field_kind -> unit
val set_commu: commutable ref -> commutable -> unit
val set_typeset: TypeSet.t ref -> TypeSet.t -> unit
        (* Set references, logging the old value *)
val log_type: type_expr -> unit
        (* Log the old value of a type, before modifying it by hand *)

(**** Forward declarations ****)
val print_raw: (Format.formatter -> type_expr -> unit) ref

val iter_type_expr_kind: (type_expr -> unit) -> (type_kind -> unit)

val iter_type_expr_cstr_args: (type_expr -> unit) ->
  (constructor_arguments -> unit)
val map_type_expr_cstr_args: (type_expr -> type_expr) ->
  (constructor_arguments -> constructor_arguments)

(** merlin: check if a snapshot has been invalidated *)
val is_valid: snapshot -> bool

(** merlin: also register changes to arbitrary references *)
val on_backtrack: (unit -> unit) -> unit

(** merlin: Number of unification variables that have been linked so far.
   Used to estimate the "cost" of unification. *)
val linked_variables: unit -> int


"""Utility functions for copying and archiving files and directory trees.

XXX The functions here don't copy the resource fork or other metadata on Mac.

"""

import os
import sys
import stat
from os.path import abspath
import fnmatch
import collections
import errno

try:
    from pwd import getpwnam
except ImportError:
    getpwnam = None

try:
    from grp import getgrnam
except ImportError:
    getgrnam = None

__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
           "copytree", "move", "rmtree", "Error", "SpecialFileError",
           "ExecError", "make_archive", "get_archive_formats",
           "register_archive_format", "unregister_archive_format"]

class Error(EnvironmentError):
    pass

class SpecialFileError(EnvironmentError):
    """Raised when trying to do a kind of operation (e.g. copying) which is
    not supported on a special file (e.g. a named pipe)"""

class ExecError(EnvironmentError):
    """Raised when a command could not be executed"""

try:
    WindowsError
except NameError:
    WindowsError = None

def copyfileobj(fsrc, fdst, length=16*1024):
    """copy data from file-like object fsrc to file-like object fdst"""
    while 1:
        buf = fsrc.read(length)
        if not buf:
            break
        fdst.write(buf)

def _samefile(src, dst):
    # Macintosh, Unix.
    if hasattr(os.path, 'samefile'):
        try:
            return os.path.samefile(src, dst)
        except OSError:
            return False

    # All other platforms: check for same pathname.
    return (os.path.normcase(os.path.abspath(src)) ==
            os.path.normcase(os.path.abspath(dst)))

def copyfile(src, dst):
    """Copy data from src to dst"""
    if _samefile(src, dst):
        raise Error("`%s` and `%s` are the same file" % (src, dst))

    for fn in [src, dst]:
        try:
            st = os.stat(fn)
        except OSError:
            # File most likely does not exist
            pass
        else:
            # XXX What about other special files? (sockets, devices...)
            if stat.S_ISFIFO(st.st_mode):
                raise SpecialFileError("`%s` is a named pipe" % fn)

    with open(src, 'rb') as fsrc:
        with open(dst, 'wb') as fdst:
            copyfileobj(fsrc, fdst)

def copymode(src, dst):
    """Copy mode bits from src to dst"""
    if hasattr(os, 'chmod'):
        st = os.stat(src)
        mode = stat.S_IMODE(st.st_mode)
        os.chmod(dst, mode)

def copystat(src, dst):
    """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
    st = os.stat(src)
    mode = stat.S_IMODE(st.st_mode)
    if hasattr(os, 'utime'):
        os.utime(dst, (st.st_atime, st.st_mtime))
    if hasattr(os, 'chmod'):
        os.chmod(dst, mode)
    if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
        try:
            os.chflags(dst, st.st_flags)
        except OSError, why:
            if (not hasattr(errno, 'EOPNOTSUPP') or
                why.errno != errno.EOPNOTSUPP):
                raise

def copy(src, dst):
    """Copy data and mode bits ("cp src dst").

    The destination may be a directory.

    """
    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))
    copyfile(src, dst)
    copymode(src, dst)

def copy2(src, dst):
    """Copy data and all stat info ("cp -p src dst").

    The destination may be a directory.

    """
    if os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))
    copyfile(src, dst)
    copystat(src, dst)

def ignore_patterns(*patterns):
    """Function that can be used as copytree() ignore parameter.

    Patterns is a sequence of glob-style patterns
    that are used to exclude files"""
    def _ignore_patterns(path, names):
        ignored_names = []
        for pattern in patterns:
            ignored_names.extend(fnmatch.filter(names, pattern))
        return set(ignored_names)
    return _ignore_patterns

def copytree(src, dst, symlinks=False, ignore=None):
    """Recursively copy a directory tree using copy2().

    The destination directory must not already exist.
    If exception(s) occur, an Error is raised with a list of reasons.

    If the optional symlinks flag is true, symbolic links in the
    source tree result in symbolic links in the destination tree; if
    it is false, the contents of the files pointed to by symbolic
    links are copied.

    The optional ignore argument is a callable. If given, it
    is called with the `src` parameter, which is the directory
    being visited by copytree(), and `names` which is the list of
    `src` contents, as returned by os.listdir():

        callable(src, names) -> ignored_names

    Since copytree() is called recursively, the callable will be
    called once for each directory that is copied. It returns a
    list of names relative to the `src` directory that should
    not be copied.

    XXX Consider this example code rather than the ultimate tool.

    """
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

def rmtree(path, ignore_errors=False, onerror=None):
    """Recursively delete a directory tree.

    If ignore_errors is set, errors are ignored; otherwise, if onerror
    is set, it is called to handle the error with arguments (func,
    path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
    path is the argument to that function that caused it to fail; and
    exc_info is a tuple returned by sys.exc_info().  If ignore_errors
    is false and onerror is None, an exception is raised.

    """
    if ignore_errors:
        def onerror(*args):
            pass
    elif onerror is None:
        def onerror(*args):
            raise
    try:
        if os.path.islink(path):
            # symlinks to directories are forbidden, see bug #1669
            raise OSError("Cannot call rmtree on a symbolic link")
    except OSError:
        onerror(os.path.islink, path, sys.exc_info())
        # can't continue even if onerror hook returns
        return
    names = []
    try:
        names = os.listdir(path)
    except os.error, err:
        onerror(os.listdir, path, sys.exc_info())
    for name in names:
        fullname = os.path.join(path, name)
        try:
            mode = os.lstat(fullname).st_mode
        except os.error:
            mode = 0
        if stat.S_ISDIR(mode):
            rmtree(fullname, ignore_errors, onerror)
        else:
            try:
                os.remove(fullname)
            except os.error, err:
                onerror(os.remove, fullname, sys.exc_info())
    try:
        os.rmdir(path)
    except os.error:
        onerror(os.rmdir, path, sys.exc_info())

def _basename(path):
    # A basename() variant which first strips the trailing slash, if present.
    # Thus we always get the last component of the path, even for directories.
    return os.path.basename(path.rstrip(os.path.sep))

def move(src, dst):
    """Recursively move a file or directory to another location. This is
    similar to the Unix "mv" command.

    If the destination is a directory or a symlink to a directory, the source
    is moved inside the directory. The destination path must not already
    exist.

    If the destination already exists but is not a directory, it may be
    overwritten depending on os.rename() semantics.

    If the destination is on our current filesystem, then rename() is used.
    Otherwise, src is copied to the destination and then removed.
    A lot more could be done here...  A look at a mv.c shows a lot of
    the issues this implementation glosses over.

    """
    real_dst = dst
    if os.path.isdir(dst):
        if _samefile(src, dst):
            # We might be on a case insensitive filesystem,
            # perform the rename anyway.
            os.rename(src, dst)
            return

        real_dst = os.path.join(dst, _basename(src))
        if os.path.exists(real_dst):
            raise Error, "Destination path '%s' already exists" % real_dst
    try:
        os.rename(src, real_dst)
    except OSError:
        if os.path.isdir(src):
            if _destinsrc(src, dst):
                raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
            copytree(src, real_dst, symlinks=True)
            rmtree(src)
        else:
            copy2(src, real_dst)
            os.unlink(src)

def _destinsrc(src, dst):
    src = abspath(src)
    dst = abspath(dst)
    if not src.endswith(os.path.sep):
        src += os.path.sep
    if not dst.endswith(os.path.sep):
        dst += os.path.sep
    return dst.startswith(src)

def _get_gid(name):
    """Returns a gid, given a group name."""
    if getgrnam is None or name is None:
        return None
    try:
        result = getgrnam(name)
    except KeyError:
        result = None
    if result is not None:
        return result[2]
    return None

def _get_uid(name):
    """Returns an uid, given a user name."""
    if getpwnam is None or name is None:
        return None
    try:
        result = getpwnam(name)
    except KeyError:
        result = None
    if result is not None:
        return result[2]
    return None

def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
                  owner=None, group=None, logger=None):
    """Create a (possibly compressed) tar file from all the files under
    'base_dir'.

    'compress' must be "gzip" (the default), "bzip2", or None.

    'owner' and 'group' can be used to define an owner and a group for the
    archive that is being built. If not provided, the current owner and group
    will be used.

    The output tar file will be named 'base_name' +  ".tar", possibly plus
    the appropriate compression extension (".gz", or ".bz2").

    Returns the output filename.
    """
    tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: ''}
    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2'}

    # flags for compression program, each element of list will be an argument
    if compress is not None and compress not in compress_ext.keys():
        raise ValueError, \
              ("bad value for 'compress': must be None, 'gzip' or 'bzip2'")

    archive_name = base_name + '.tar' + compress_ext.get(compress, '')
    archive_dir = os.path.dirname(archive_name)

    if not os.path.exists(archive_dir):
        logger.info("creating %s" % archive_dir)
        if not dry_run:
            os.makedirs(archive_dir)

    # creating the tarball
    import tarfile  # late import so Python build itself doesn't break

    if logger is not None:
        logger.info('Creating tar archive')

    uid = _get_uid(owner)
    gid = _get_gid(group)

    def _set_uid_gid(tarinfo):
        if gid is not None:
            tarinfo.gid = gid
            tarinfo.gname = group
        if uid is not None:
            tarinfo.uid = uid
            tarinfo.uname = owner
        return tarinfo

    if not dry_run:
        tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
        try:
            tar.add(base_dir, filter=_set_uid_gid)
        finally:
            tar.close()

    return archive_name

def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
    # XXX see if we want to keep an external call here
    if verbose:
        zipoptions = "-r"
    else:
        zipoptions = "-rq"
    from distutils.errors import DistutilsExecError
    from distutils.spawn import spawn
    try:
        spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
    except DistutilsExecError:
        # XXX really should distinguish between "couldn't find
        # external 'zip' command" and "zip failed".
        raise ExecError, \
            ("unable to create zip file '%s': "
            "could neither import the 'zipfile' module nor "
            "find a standalone zip utility") % zip_filename

def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
    """Create a zip file from all the files under 'base_dir'.

    The output zip file will be named 'base_name' + ".zip".  Uses either the
    "zipfile" Python module (if available) or the InfoZIP "zip" utility
    (if installed and found on the default search path).  If neither tool is
    available, raises ExecError.  Returns the name of the output zip
    file.
    """
    zip_filename = base_name + ".zip"
    archive_dir = os.path.dirname(base_name)

    if not os.path.exists(archive_dir):
        if logger is not None:
            logger.info("creating %s", archive_dir)
        if not dry_run:
            os.makedirs(archive_dir)

    # If zipfile module is not available, try spawning an external 'zip'
    # command.
    try:
        import zipfile
    except ImportError:
        zipfile = None

    if zipfile is None:
        _call_external_zip(base_dir, zip_filename, verbose, dry_run)
    else:
        if logger is not None:
            logger.info("creating '%s' and adding '%s' to it",
                        zip_filename, base_dir)

        if not dry_run:
            zip = zipfile.ZipFile(zip_filename, "w",
                                  compression=zipfile.ZIP_DEFLATED)

            for dirpath, dirnames, filenames in os.walk(base_dir):
                for name in filenames:
                    path = os.path.normpath(os.path.join(dirpath, name))
                    if os.path.isfile(path):
                        zip.write(path, path)
                        if logger is not None:
                            logger.info("adding '%s'", path)
            zip.close()

    return zip_filename

_ARCHIVE_FORMATS = {
    'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
    'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
    'tar':   (_make_tarball, [('compress', None)], "uncompressed tar file"),
    'zip':   (_make_zipfile, [],"ZIP file")
    }

def get_archive_formats():
    """Returns a list of supported formats for archiving and unarchiving.

    Each element of the returned sequence is a tuple (name, description)
    """
    formats = [(name, registry[2]) for name, registry in
               _ARCHIVE_FORMATS.items()]
    formats.sort()
    return formats

def register_archive_format(name, function, extra_args=None, description=''):
    """Registers an archive format.

    name is the name of the format. function is the callable that will be
    used to create archives. If provided, extra_args is a sequence of
    (name, value) tuples that will be passed as arguments to the callable.
    description can be provided to describe the format, and will be returned
    by the get_archive_formats() function.
    """
    if extra_args is None:
        extra_args = []
    if not isinstance(function, collections.Callable):
        raise TypeError('The %s object is not callable' % function)
    if not isinstance(extra_args, (tuple, list)):
        raise TypeError('extra_args needs to be a sequence')
    for element in extra_args:
        if not isinstance(element, (tuple, list)) or len(element) !=2 :
            raise TypeError('extra_args elements are : (arg_name, value)')

    _ARCHIVE_FORMATS[name] = (function, extra_args, description)

def unregister_archive_format(name):
    del _ARCHIVE_FORMATS[name]

def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
                 dry_run=0, owner=None, group=None, logger=None):
    """Create an archive file (eg. zip or tar).

    'base_name' is the name of the file to create, minus any format-specific
    extension; 'format' is the archive format: one of "zip", "tar", "bztar"
    or "gztar".

    'root_dir' is a directory that will be the root directory of the
    archive; ie. we typically chdir into 'root_dir' before creating the
    archive.  'base_dir' is the directory where we start archiving from;
    ie. 'base_dir' will be the common prefix of all files and
    directories in the archive.  'root_dir' and 'base_dir' both default
    to the current directory.  Returns the name of the archive file.

    'owner' and 'group' are used when creating a tar archive. By default,
    uses the current owner and group.
    """
    save_cwd = os.getcwd()
    if root_dir is not None:
        if logger is not None:
            logger.debug("changing into '%s'", root_dir)
        base_name = os.path.abspath(base_name)
        if not dry_run:
            os.chdir(root_dir)

    if base_dir is None:
        base_dir = os.curdir

    kwargs = {'dry_run': dry_run, 'logger': logger}

    try:
        format_info = _ARCHIVE_FORMATS[format]
    except KeyError:
        raise ValueError, "unknown archive format '%s'" % format

    func = format_info[0]
    for arg, val in format_info[1]:
        kwargs[arg] = val

    if format != 'zip':
        kwargs['owner'] = owner
        kwargs['group'] = group

    try:
        filename = func(base_name, base_dir, **kwargs)
    finally:
        if root_dir is not None:
            if logger is not None:
                logger.debug("changing back to '%s'", save_cwd)
            os.chdir(save_cwd)

    return filename


/*
    CFURLEnumerator.h
    Copyright (c) 2008-2017, Apple Inc. All rights reserved.
 */

#if (TARGET_OS_MAC || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE) || CF_BUILDING_CF || NSBUILDINGFOUNDATION

#if !defined(__COREFOUNDATION_CFURLENUMERATOR__)
#define __COREFOUNDATION_CFURLENUMERATOR__ 1

#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFArray.h>
#include <CoreFoundation/CFError.h>
#include <CoreFoundation/CFURL.h>

CF_IMPLICIT_BRIDGING_ENABLED
CF_EXTERN_C_BEGIN

typedef const struct CF_BRIDGED_MUTABLE_TYPE(id) __CFURLEnumerator *CFURLEnumeratorRef;

/* CFURLEnumeratorGetTypeID - Returns the CFURLEnumerator CFTypeID. */
CF_EXPORT
CFTypeID CFURLEnumeratorGetTypeID( void ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorOptions - Options for controlling enumerator behavior. */
typedef CF_OPTIONS(CFOptionFlags, CFURLEnumeratorOptions) {
    kCFURLEnumeratorDefaultBehavior                 = 0,        /* Use the default behavior for the enumerator. */
    kCFURLEnumeratorDescendRecursively              = 1UL << 0, /* The directory enumerator will recurse ("depth-first") into each subdirectory enumerated */
    kCFURLEnumeratorSkipInvisibles                  = 1UL << 1, /* The directory or volume enumerator skips "hidden" or "invisible" objects */
    kCFURLEnumeratorGenerateFileReferenceURLs       = 1UL << 2, /* The volume enumerator generates file reference URLs */
    kCFURLEnumeratorSkipPackageContents             = 1UL << 3, /* The directory enumerator skips package directory contents */
    kCFURLEnumeratorIncludeDirectoriesPreOrder      = 1UL << 4, /* With this option set, a recursive directory enumerator will return directory URLs when CFURLEnumeratorGetNextURL() returns kCFURLEnumeratorSuccess before any of the directory's descendants are visited (pre-order). */
    kCFURLEnumeratorIncludeDirectoriesPostOrder     = 1UL << 5, /* With this option set, a recursive directory enumerator will return directory URLs when CFURLEnumeratorGetNextURL() returns kCFURLEnumeratorDirectoryPostOrderSuccess after all of directory's descendants have been visited (post-order). */
    /* Note: if both kCFURLEnumeratorIncludeDirectoriesPreOrder and kCFURLEnumeratorIncludeDirectoriesPostOrder are used, directories will be seen twice (even empty directories and directories whose descendants are skipped) -- once when kCFURLEnumeratorSuccess is returned and once when kCFURLEnumeratorDirectoryPostOrderSuccess is returned. */
};

/* CFURLEnumeratorCreateForDirectoryURL - Creates a directory enumerator, flat or recursive. Client specifies the directory URL to enumerate, a bit array of options, and an optional array of property keys to pre-fetch for the found URLs. Specifying pre-fetch properties allows the implementation to optimize device access by using bulk operations when available. Pre-fetching more properties than are actually needed may degrade performance.

A directory enumerator generates URLs with the same type as the directory URL being enumerated. If the directoryURL input parameter is a file reference URL, then generated URLs will be file reference URLs. If the directoryURL input parameter is a file path URL, then generated URLs will be file path URLs.

The kCFURLEnumeratorGenerateFileReferenceURLs option is ignored by CFURLEnumeratorCreateForDirectoryURL.
*/
CF_EXPORT
CFURLEnumeratorRef CFURLEnumeratorCreateForDirectoryURL( CFAllocatorRef alloc, CFURLRef directoryURL, CFURLEnumeratorOptions option, CFArrayRef propertyKeys ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorCreateForMountedVolumes - Creates an enumerator for mounted filesystem volumes. Client specifies an allocator, a bit array of options, and an optional array of property keys to pre-fetch for the volume URLs. Specifying pre-fetch properties allows the implementation to optimize device access by using bulk operations when available. Pre-fetching more properties than are actually needed may degrade performance.

A volume enumerator generates file path URLs. If you want a volume enumerator to generate file reference URLs, pass the kCFURLEnumeratorGenerateFileReferenceURLs option.

The kCFURLEnumeratorDescendRecursively and kCFURLEnumeratorSkipPackageContents options are ignored by CFURLEnumeratorCreateForMountedVolumes.
*/
CF_EXPORT
CFURLEnumeratorRef CFURLEnumeratorCreateForMountedVolumes( CFAllocatorRef alloc, CFURLEnumeratorOptions option, CFArrayRef propertyKeys ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorResult - Results for CFURLEnumeratorGetNextURL */
typedef CF_ENUM(CFIndex, CFURLEnumeratorResult) {
    kCFURLEnumeratorSuccess = 1,                    /* The enumeration was successful. The url output parameter is valid. */
    kCFURLEnumeratorEnd = 2,                        /* The enumeration is complete. */
    kCFURLEnumeratorError = 3,			    /* An error occured during enumeration. The retained error output parameter describes the error. */
    kCFURLEnumeratorDirectoryPostOrderSuccess = 4,  /* The enumeration was successful. The url output parameter is for a directory after all of directory's descendants have been visited (post-order). This result will only be returned for directories when both the kCFURLEnumeratorDescendRecursively and kCFURLEnumeratorIncludeDirectoriesPostOrder options are passed to CFURLEnumeratorCreateForDirectoryURL. */
};

/* CFURLEnumeratorGetNextURL - Advances the enumerator. If kCFURLEnumeratorSuccess is returned, the url output parameter returns the next URL found. If kCFURLEnumeratorError is returned, an error has occured and the error output parameter describes the error. If kCFURLEnumeratorEnd, the enumeration is finished.

The url output parameter, if returned, is not retained. The error output parameter, if returned, is retained and must be released.
*/
CF_EXPORT
CFURLEnumeratorResult CFURLEnumeratorGetNextURL( CFURLEnumeratorRef enumerator, CFURLRef *url, CFErrorRef *error ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorSkipDescendents - Tells a recursive CFURLEnumerator not to descend into the directory of the last CFURLRef returned by CFURLEnumeratorGetNextURL.

Calls to CFURLEnumeratorSkipDescendents are ignored if:
    * CFURLEnumeratorGetNextURL has never been called with the CFURLEnumerator.
    * The last CFURL returned by CFURLEnumeratorGetNextURL is not a directory.
    * The CFURLEnumerator was not created with CFURLEnumeratorCreateForDirectoryURL using the kCFURLEnumeratorDescendRecursively option.
*/
CF_EXPORT
void CFURLEnumeratorSkipDescendents( CFURLEnumeratorRef enumerator ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorGetDescendentLevel - Returns the number of levels a directory enumerator has descended down into the directory hierarchy from the starting directory. The children of the starting directory are at level 1. Each time a recursive enumerator descends into a subdirectory, it adds one to the descendent level. It then subtracts one from the level when it finishes a subdirectory and continues enumerating the parent directory.
*/
CF_EXPORT
CFIndex CFURLEnumeratorGetDescendentLevel( CFURLEnumeratorRef enumerator ) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

/* CFURLEnumeratorGetSourceDidChange is deprecated. If your program is interested in directory hierarchy changes during enumeration (and most programs are not interested), you should use the File System Events API.

 CFURLEnumeratorGetSourceDidChange does nothing and always returns false.
 */
CF_EXPORT
Boolean CFURLEnumeratorGetSourceDidChange( CFURLEnumeratorRef enumerator ) API_DEPRECATED("Use File System Events API instead", macos(10.6,10.7), ios(4.0,5.0), watchos(2.0,2.0), tvos(9.0,9.0));

CF_EXTERN_C_END
CF_IMPLICIT_BRIDGING_DISABLED

#endif /* ! __COREFOUNDATION_CFURLENUMERATOR__ */

#endif


/*
 * Copyright (C) 2015 - Holy Lobster
 *
 * Nuntius is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Nuntius is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuntius. If not, see <http://www.gnu.org/licenses/>.
 */

namespace Nuntius {

public class NotificationApp : Object {
    public string id { get; construct set; }
    public Connection connection { get; construct set; }
    private string _app_name;
    private BytesIcon _icon;
    private uint _unread_notifications;
    private List<Notification> _notifications;

    public string app_name {
        get { return _app_name; }
    }

    public BytesIcon icon {
        get { return _icon; }
    }

    public uint unread_notifications {
        get { return _unread_notifications; }
    }

    public List<Notification> notifications {
        get { return _notifications; }
    }

    public NotificationApp(string id, Connection connection) {
        Object(id: id, connection: connection);
    }

    construct {
        _notifications = new List<Notification>();
    }

    public void add_notification(Notification notification) {
        _notifications.prepend(notification);

        // Update the icon with the latest notification
        if (_icon != notification.icon) {
            _icon = notification.icon;
            notify_property("icon");
        }

        if (_app_name != notification.app_name) {
            _app_name = notification.app_name;
            notify_property("app-name");
        }

        if (!notification.read) {
            _unread_notifications++;
            notify_property("unread-notifications");
        }

        notification.notify["read"].connect(() => {
            if (notification.read) {
                _unread_notifications--;
            } else {
                _unread_notifications++;
            }

            notify_property("unread-notifications");
        });
    }

    public Notification get_notification(string id) {
        Notification? n = null;

        foreach (var notif in _notifications) {
            if (notif.id == id) {
                n = notif;
                break;
            }
        }

        return n;
    }

    public void blacklist() {
        Json.Builder builder = new Json.Builder();
        builder.begin_object();
        builder.set_member_name("event");
        builder.add_string_value("blacklist");
        builder.set_member_name("app");
        builder.begin_object();

        builder.set_member_name("packageName");
        builder.add_string_value(id);

        builder.end_object();
        builder.end_object();

        Json.Generator generator = new Json.Generator();
        Json.Node root = builder.get_root();
        generator.set_root(root);

        string blacklist_message = generator.to_data(null);
        connection.send_message(blacklist_message);
    }
}

} // namespace Nuntius

/* ex:set ts=4 et: */


import os
import sys
import unittest
import test.support as test_support
from tkinter import Tcl, TclError

test_support.requires('gui')

class TkLoadTest(unittest.TestCase):

    @unittest.skipIf('DISPLAY' not in os.environ, 'No $DISPLAY set.')
    def testLoadTk(self):
        tcl = Tcl()
        self.assertRaises(TclError,tcl.winfo_geometry)
        tcl.loadtk()
        self.assertEqual('1x1+0+0', tcl.winfo_geometry())
        tcl.destroy()

    def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with test_support.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                with os.popen('echo $DISPLAY') as pipe:
                    display = pipe.read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk)

tests_gui = (TkLoadTest, )

if __name__ == "__main__":
    test_support.run_unittest(*tests_gui)


package org.telegram.api.functions.phone;

import org.telegram.api.input.phonecall.TLInputPhoneCall;
import org.telegram.api.phone.TLPhoneCallProtocol;
import org.telegram.api.phone.TLPhonePhoneCall;
import org.telegram.tl.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Ruben Bermudez
 * @version 1.0
 */
public class TLRequestPhoneConfirmCall extends TLMethod<TLPhonePhoneCall> {
    public static final int CLASS_ID = 0x2efe1722;

    private TLInputPhoneCall peer;
    private TLBytes gA;
    private long keyFingerprint;
    private TLPhoneCallProtocol protocol;

    public TLRequestPhoneConfirmCall() {
        super();
    }

    public TLInputPhoneCall getPeer() {
        return peer;
    }

    public void setPeer(TLInputPhoneCall peer) {
        this.peer = peer;
    }

    public TLBytes getgA() {
        return gA;
    }

    public void setgA(TLBytes gA) {
        this.gA = gA;
    }

    public long getKeyFingerprint() {
        return keyFingerprint;
    }

    public void setKeyFingerprint(long keyFingerprint) {
        this.keyFingerprint = keyFingerprint;
    }

    public TLPhoneCallProtocol getProtocol() {
        return protocol;
    }

    public void setProtocol(TLPhoneCallProtocol protocol) {
        this.protocol = protocol;
    }

    @Override
    public TLPhonePhoneCall deserializeResponse(InputStream stream, TLContext context) throws IOException {
        TLObject res = StreamingUtils.readTLObject(stream, context);
        if (res == null) {
            throw new IOException("Unable to parse response");
        }
        if (res instanceof TLPhonePhoneCall) {
            return (TLPhonePhoneCall) res;
        }
        throw new IOException("Incorrect response type. Expected " + TLPhonePhoneCall.class.getCanonicalName() +
                ", got: " + res.getClass().getCanonicalName());
    }

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

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        StreamingUtils.writeTLObject(peer, stream);
        StreamingUtils.writeTLBytes(gA, stream);
        StreamingUtils.writeLong(keyFingerprint, stream);
        StreamingUtils.writeTLObject(protocol, stream);
    }

    @Override
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        peer = StreamingUtils.readTLObject(stream, context, TLInputPhoneCall.class);
        gA = StreamingUtils.readTLBytes(stream, context);
        keyFingerprint = StreamingUtils.readLong(stream);
        protocol = StreamingUtils.readTLObject(stream, context, TLPhoneCallProtocol.class);
    }

    @Override
    public String toString() {
        return "phone.confirmCall#2efe1722";
    }
}


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">

	<title>Test dojox.grid.Grid Expand Rows</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>

dojox.grid.Grid Expand Row Example


<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <link rel="stylesheet" href="assets/css/login.css">

                        <% if (generalSettings && generalSettings.appIcon) { %>

                                <img src="<%= generalSettings.appIcon %>" style="width:50px;height:50px;">

                        <%}else{%>

                        <%}%>

                        <% if (generalSettings && generalSettings.appName) { %>

<%= generalSettings.appName %>

                        <%}else{%>

App on CloudBoost

                        <%}%>

                        Unknown Error

                        <% if(!authSettings || (authSettings && authSettings.custom && authSettings.custom.enabled)){ %>

                                    <button class="default-inputfield login-btn" style="">LOG IN</button>

                                    <button class="default-inputfield sinup-btn" style="">SIGN UP</button>

                        <%}%>

                                    <% if(authSettings && authSettings.facebook && authSettings.facebook.enabled){ %>

                                    <%}%>

                                    <% if(authSettings && authSettings.twitter && authSettings.twitter.enabled){ %>

                                    <%}%>

                                    <% if(authSettings && authSettings.google && authSettings.google.enabled){ %>

                                    <%}%>

                                    <% if(authSettings && authSettings.linkedIn && authSettings.linkedIn.enabled){ %>

                                    <%}%>

                                    <% if(authSettings && authSettings.github && authSettings.github.enabled){ %>

                                    <%}%>

                                <% if((authSettings && authSettings.custom && authSettings.custom.enabled) && ((authSettings && authSettings.facebook && authSettings.facebook.enabled) || (authSettings && authSettings.twitter && authSettings.twitter.enabled) || (authSettings && authSettings.google && authSettings.google.enabled) || (authSettings && authSettings.linkedIn && authSettings.linkedIn.enabled) || (authSettings && authSettings.github && authSettings.github.enabled))){ %>

Or

                                <%}%>

                            <% if(!authSettings || (authSettings && authSettings.custom && authSettings.custom.enabled)){ %>

                                            <input id="login-username" type="text" placeholder="Username" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

                                            <input id="login-password" type="password" placeholder="Password" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

                                            <input id="signup-username" type="text" placeholder="Enter Username" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

                                            <input id="signup-password" type="password" placeholder="Create a Password" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

                                            <input id="signup-email" type="text" placeholder="Enter Email" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

                                Don't remember your password?

                            <%}%>

                    <% if(!authSettings || (authSettings && authSettings.custom && authSettings.custom.enabled)){ %>

                    <%}%>

                        <% if (generalSettings && generalSettings.appIcon) { %>

                                <img src="<%= generalSettings.appIcon %>" style="width:50px;height:50px;">

                        <%}else{%>

                        <%}%>

Password Reset

                        Unknown Error

                            Please enter your email address.

                             We will send you an email to reset your password.

                                        <input id="forgot-email" type="text" placeholder="Enter Email" class="default-inputfield" required style="width: 100%;height: 100%;padding-left: 12px;">

powered by

 CloudBoost


Extending Vim with Scripts and
  Plugins

Problem

You want to add functionality to Vim, preferably without having to write it
yourself.

Solution

Browse Vim Scripts to find a
script that meets your needs. Its 'type' should be utility or
ftplugin.  Download the latest version to your computer. If the plugin
comes with its own installation instructions, use those; otherwise, read
on.

If the file you've downloaded has a name ending with <tt>.vim</tt> you
usually just need to save it in the right directory and then its ready to use.
For scripts labelled utility, also known as global plugins, this
directory is <tt>$VIMHOME/plugin</tt>; for those labeled ftplugin, also
known as filetype plugins,  the last component of this path is
ftplugin instead. If this directory does not already exist you need to
create it. The sidebar lists the locations of the plugin directories on
various operating systems.

If the file is compressed (ending with <tt>.zip</tt> or <tt>.tar.gz</tt>),
try uncompressing it in the parent directory of the applicable plugin
directory.  For example, on Linux this is <tt>~/.vim/</tt>.

Now you should just be able to start Vim and have the plugin work.

Plugin Directory Location

Note: For filetype plugins, the last portion of
these paths is ftplugin; not plugin.

Unix

<tt>~/.vim/plugin</tt>

PC and OS/2

<tt>$HOME/vimfiles/plugin</tt> or <tt>$VIM/vimfiles/plugin</tt>

Amiga

<tt>s:vimfiles/plugin</tt>

Macintosh

<tt>$VIM:vimfiles:plugin</tt>

Mac OS X

<tt>~/.vim/plugin</tt>

RISC-OS

<tt>Choices:vimfiles.plugin</tt>

Plugin Types

Plugins can be either global or filetype-specific. Global plugins
are loaded for every file you open; filetype-specific plugins are only loaded
for certain filetypes.

Discussion

As complicated as the above instructions may sound, it's generally trivial
to install a plugin. For example, on Linux to install the potwiki
  plugin:

<samp>$ </samp>mkdir -p ~/.vim/plugin
<samp>$ </samp>wget
http://www.vim.org/scripts/download_script.php?src_id=9316 -O
~/.vim/plugin/potwiki.vim

(If your plugin directory already exists, the first command is
superfluous.)

Vim 7 added support for a new plugin installation method called
vimball.  Vimballs make plugin installation and configuration easier,
and are a slight improvement over the previous methods. They're not in wide
use yet, but if you find a plugin distributed in this way (they have a
*.vba extension), try following the steps below:

Download the *.vba file.

Open it with Vim, e.g. <tt>vim something.vba</tt>.

Use <tt>:VimballList</tt> to verify its contents.

Install it by sourcing: <tt>:source %</tt>.


/*
 * Copyright (c) Enalean, 2019 - present. All Rights Reserved.
 *
 * This file is a part of Tuleap.
 *
 * Tuleap is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Tuleap is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Tuleap. If not, see http://www.gnu.org/licenses/.
 *
 */
import moment from "moment/moment";

export function getObsolescenceDateValueInput(select_date_value) {
    const current_date = moment();
    let date;
    switch (select_date_value) {
        case "permanent":
            date = null;
            break;
        case "today":
            date = current_date.format("YYYY-MM-DD");
            break;
        default:
            date = moment(current_date, "YYYY-MM-DD")
                .add(select_date_value, "M")
                .format("YYYY-MM-DD");
    }
    return date;
}