use crate::iter::{self, Iter, IterImpl};
use crate::{Define, Error, Export, ExportArgs, FakeCallSite, Input, Macro, Visibility};
use proc_macro::Delimiter::{Brace, Bracket, Parenthesis};
use proc_macro::{Delimiter, Ident, Span, TokenStream, TokenTree};

pub(crate) fn parse_input(tokens: Iter) -> Result<Input, Error> {
    let attrs = parse_attributes(tokens)?;
    let vis = parse_visibility(tokens)?;
    let kw = parse_ident(tokens)?;
    if kw.to_string() == "use" {
        parse_export(attrs, vis, tokens).map(Input::Export)
    } else if kw.to_string() == "fn" {
        parse_define(attrs, vis, kw.span(), tokens).map(Input::Define)
    } else {
        Err(Error::new(
            kw.span(),
            "unexpected input to #[proc_macro_hack]",
        ))
    }
}

fn parse_export(attrs: TokenStream, vis: Visibility, tokens: Iter) -> Result<Export, Error> {
    let _ = parse_punct(tokens, ':');
    let _ = parse_punct(tokens, ':');
    let from = parse_ident(tokens)?;
    parse_punct(tokens, ':')?;
    parse_punct(tokens, ':')?;

    let mut macros = Vec::new();
    match tokens.peek() {
        Some(TokenTree::Group(group)) if group.delimiter() == Brace => {
            let ref mut content = iter::new(group.stream());
            loop {
                macros.push(parse_macro(content)?);
                if content.peek().is_none() {
                    break;
                }
                parse_punct(content, ',')?;
                if content.peek().is_none() {
                    break;
                }
            }
            tokens.next().unwrap();
        }
        _ => macros.push(parse_macro(tokens)?),
    }

    parse_punct(tokens, ';')?;
    Ok(Export {
        attrs,
        vis,
        from,
        macros,
    })
}

fn parse_punct(tokens: Iter, ch: char) -> Result<(), Error> {
    match tokens.peek() {
        Some(TokenTree::Punct(punct)) if punct.as_char() == ch => {
            tokens.next().unwrap();
            Ok(())
        }
        tt => Err(Error::new(
            tt.map_or_else(Span::call_site, TokenTree::span),
            format!("expected `{}`", ch),
        )),
    }
}

fn parse_define(
    attrs: TokenStream,
    vis: Visibility,
    fn_token: Span,
    tokens: Iter,
) -> Result<Define, Error> {
    if vis.is_none() {
        return Err(Error::new(
            fn_token,
            "functions tagged with `#[proc_macro_hack]` must be `pub`",
        ));
    }
    let name = parse_ident(tokens)?;
    let body = tokens.collect();
    Ok(Define { attrs, name, body })
}

fn parse_macro(tokens: Iter) -> Result<Macro, Error> {
    let name = parse_ident(tokens)?;
    let export_as = match tokens.peek() {
        Some(TokenTree::Ident(ident)) if ident.to_string() == "as" => {
            tokens.next().unwrap();
            parse_ident(tokens)?
        }
        _ => name.clone(),
    };
    Ok(Macro { name, export_as })
}

fn parse_ident(tokens: Iter) -> Result<Ident, Error> {
    match tokens.next() {
        Some(TokenTree::Ident(ident)) => Ok(ident),
        tt => Err(Error::new(
            tt.as_ref().map_or_else(Span::call_site, TokenTree::span),
            "expected identifier",
        )),
    }
}

fn parse_keyword(tokens: Iter, kw: &'static str) -> Result<(), Error> {
    match &tokens.next() {
        Some(TokenTree::Ident(ident)) if ident.to_string() == kw => Ok(()),
        tt => Err(Error::new(
            tt.as_ref().map_or_else(Span::call_site, TokenTree::span),
            format!("expected `{}`", kw),
        )),
    }
}

fn parse_int(tokens: Iter) -> Result<u16, Span> {
    match tokens.next() {
        Some(TokenTree::Literal(lit)) => lit.to_string().parse().map_err(|_| lit.span()),
        Some(tt) => Err(tt.span()),
        None => Err(Span::call_site()),
    }
}

fn parse_group(tokens: Iter, delimiter: Delimiter) -> Result<IterImpl, Error> {
    match &tokens.next() {
        Some(TokenTree::Group(group)) if group.delimiter() == delimiter => {
            Ok(iter::new(group.stream()))
        }
        tt => Err(Error::new(
            tt.as_ref().map_or_else(Span::call_site, TokenTree::span),
            "expected delimiter",
        )),
    }
}

fn parse_visibility(tokens: Iter) -> Result<Visibility, Error> {
    if let Some(TokenTree::Ident(ident)) = tokens.peek() {
        if ident.to_string() == "pub" {
            return Ok(Some(tokens.next().unwrap().span()));
        }
    }
    Ok(None)
}

fn parse_attributes(tokens: Iter) -> Result<TokenStream, Error> {
    let mut attrs = TokenStream::new();
    while let Some(TokenTree::Punct(punct)) = tokens.peek() {
        if punct.as_char() != '#' {
            break;
        }
        let span = punct.span();
        attrs.extend(tokens.next());
        match tokens.peek() {
            Some(TokenTree::Group(group)) if group.delimiter() == Bracket => {
                attrs.extend(tokens.next());
            }
            _ => return Err(Error::new(span, "unexpected input")),
        }
    }
    Ok(attrs)
}

pub(crate) fn parse_export_args(tokens: Iter) -> Result<ExportArgs, Error> {
    let mut args = ExportArgs {
        support_nested: false,
        internal_macro_calls: 0,
        fake_call_site: false,
    };

    while let Some(tt) = tokens.next() {
        match &tt {
            TokenTree::Ident(ident) if ident.to_string() == "support_nested" => {
                args.support_nested = true;
            }
            TokenTree::Ident(ident) if ident.to_string() == "internal_macro_calls" => {
                parse_punct(tokens, '=')?;
                let calls = parse_int(tokens).map_err(|span| {
                    Error::new(span, "expected integer value for internal_macro_calls")
                })?;
                args.internal_macro_calls = calls;
            }
            TokenTree::Ident(ident) if ident.to_string() == "fake_call_site" => {
                args.fake_call_site = true;
            }
            _ => {
                return Err(Error::new(
                    tt.span(),
                    "expected one of: `support_nested`, `internal_macro_calls`, `fake_call_site`",
                ))
            }
        }
        if tokens.peek().is_none() {
            break;
        }
        parse_punct(tokens, ',')?;
    }

    Ok(args)
}

pub(crate) fn parse_define_args(tokens: Iter) -> Result<(), Error> {
    if tokens.peek().is_none() {
        Ok(())
    } else {
        Err(Error::new(Span::call_site(), "unexpected input"))
    }
}

pub(crate) fn parse_enum_hack(tokens: Iter) -> Result<TokenStream, Error> {
    parse_keyword(tokens, "enum")?;
    parse_ident(tokens)?;

    let ref mut braces = parse_group(tokens, Brace)?;
    parse_ident(braces)?;
    parse_punct(braces, '=')?;

    let ref mut parens = parse_group(braces, Parenthesis)?;
    parse_ident(parens)?;
    parse_punct(parens, '!')?;

    let ref mut inner = parse_group(parens, Brace)?;
    let token_stream = inner.collect();

    parse_punct(parens, ',')?;
    let _ = parens.next();
    parse_punct(braces, '.')?;
    let _ = braces.next();
    parse_punct(braces, ',')?;

    Ok(token_stream)
}

pub(crate) fn parse_fake_call_site(tokens: Iter) -> Result<FakeCallSite, Error> {
    parse_punct(tokens, '#')?;
    let ref mut attr = parse_group(tokens, Bracket)?;
    parse_keyword(attr, "derive")?;
    let ref mut path = parse_group(attr, Parenthesis)?;
    Ok(FakeCallSite {
        derive: parse_ident(path)?,
        rest: tokens.collect(),
    })
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 *
 */

package org.apache.skywalking.oap.server.core.analysis.worker;

import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.oap.server.core.analysis.config.NoneStream;
import org.apache.skywalking.oap.server.core.storage.INoneStreamDAO;
import org.apache.skywalking.oap.server.core.storage.model.Model;
import org.apache.skywalking.oap.server.core.worker.AbstractWorker;
import org.apache.skywalking.oap.server.library.module.ModuleDefineHolder;

/**
 * None persistent use {@link INoneStreamDAO#insert(Model, NoneStream)} on saving new data
 */
@Slf4j
public class NoneStreamPersistentWorker extends AbstractWorker<NoneStream> {
    private final Model model;
    private final INoneStreamDAO configDAO;

    public NoneStreamPersistentWorker(ModuleDefineHolder moduleDefineHolder, Model model, INoneStreamDAO configDAO) {
        super(moduleDefineHolder);
        this.model = model;
        this.configDAO = configDAO;
    }

    @Override
    public void in(NoneStream noneStream) {
        try {
            configDAO.insert(model, noneStream);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <ByteChucker.hxx>
#include <PackageConstants.hxx>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XOutputStream.hpp>

using namespace ::com::sun::star::io;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

ByteChucker::ByteChucker(Reference<XOutputStream> const & xOstream)
: xStream(xOstream)
, xSeek (xOstream, UNO_QUERY )
, a2Sequence ( 2 )
, a4Sequence ( 4 )
, p2Sequence ( a2Sequence.getArray() )
, p4Sequence ( a4Sequence.getArray() )
{
}

ByteChucker::~ByteChucker()
{
}

void ByteChucker::WriteBytes( const Sequence< sal_Int8 >& aData )
{
    xStream->writeBytes(aData);
}

sal_Int64 ByteChucker::GetPosition(  )
{
    return xSeek->getPosition();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */


package org.arquillian.cube.kubernetes.impl.feedback;

import io.fabric8.kubernetes.api.model.v4_0.Container;
import io.fabric8.kubernetes.api.model.v4_0.Endpoints;
import io.fabric8.kubernetes.api.model.v4_0.Event;
import io.fabric8.kubernetes.api.model.v4_0.EventList;
import io.fabric8.kubernetes.api.model.v4_0.HasMetadata;
import io.fabric8.kubernetes.api.model.v4_0.LabelSelectorRequirement;
import io.fabric8.kubernetes.api.model.v4_0.Pod;
import io.fabric8.kubernetes.api.model.v4_0.PodList;
import io.fabric8.kubernetes.api.model.v4_0.PodListBuilder;
import io.fabric8.kubernetes.api.model.v4_0.ReplicationController;
import io.fabric8.kubernetes.api.model.v4_0.Service;
import io.fabric8.kubernetes.api.model.v4_0.apps.Deployment;
import io.fabric8.kubernetes.api.model.v4_0.apps.ReplicaSet;
import io.fabric8.kubernetes.clnt.v4_0.KubernetesClient;
import io.fabric8.kubernetes.clnt.v4_0.Watch;
import io.fabric8.kubernetes.clnt.v4_0.Watcher;
import io.fabric8.kubernetes.clnt.v4_0.dsl.FilterWatchListDeletable;
import java.util.HashMap;
import java.util.Map;
import org.arquillian.cube.kubernetes.api.FeedbackProvider;
import org.arquillian.cube.kubernetes.api.Logger;
import org.arquillian.cube.kubernetes.api.WithToImmutable;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;

public class DefaultFeedbackProvider implements FeedbackProvider {

    protected FeedbackProvider delegate;

    @Inject
    protected Instance<KubernetesClient> client;

    @Inject
    protected Instance<Logger> logger;

    @Override
    public <T extends HasMetadata> void onResourceNotReady(T resource) {

    }

    @Override
    public FeedbackProvider toImmutable() {
        if (delegate != null) {
            return delegate;
        }
        synchronized (this) {
            if (delegate == null) {
                delegate = new ImmutableFeedbackProvider(client.get(),
                    logger.get().toImmutable());
            }
        }
        return delegate;
    }

    public static class ImmutableFeedbackProvider implements FeedbackProvider, WithToImmutable<FeedbackProvider> {

        @Inject
        protected final KubernetesClient client;

        @Inject
        protected final Logger logger;

        public ImmutableFeedbackProvider(KubernetesClient client, Logger logger) {
            this.client = client;
            this.logger = logger;
        }

        @Override
        public <T extends HasMetadata> void onResourceNotReady(T resource) {
            try {
                PodList podList = podsOf(resource);
                if (podList == null) {
                    return;
                }

                for (Pod pod : podList.getItems()) {
                    //That should only happen in tests.
                    if (pod.getSpec() == null || pod.getSpec().getContainers() == null) {
                        continue;
                    }

                    displayPodEvents(pod);

                    for (Container container : pod.getSpec().getContainers()) {
                        displayContainerLogs(pod, container);
                    }
                }
            } catch (Throwable t) {
                //ignore
            }
        }

        protected void displayContainerLogs(Pod pod, Container container) {
            try {
                logger.warn("Tailing logs of matching pod: ["
                    + pod.getMetadata().getName()
                    + "], container: ["
                    + container.getName()
                    + "]");
                logger.info(client.pods()
                    .inNamespace(pod.getMetadata().getNamespace())
                    .withName(pod.getMetadata().getName())
                    .inContainer(container.getName())
                    .tailingLines(100)
                    .withPrettyOutput()
                    .getLog());
            } catch (Throwable t) {
                logger.error("Failed to read logs, due to:" + t.getMessage());
            } finally {
                logger.warn("---");
            }
        }

        protected void displayPodEvents(Pod pod) {
            try {
                Map<String, String> fields = new HashMap<>();
                fields.put("involvedObject.uid", pod.getMetadata().getUid());
                fields.put("involvedObject.name", pod.getMetadata().getName());
                fields.put("involvedObject.namespace", pod.getMetadata().getNamespace());

                EventList eventList = client.events().inNamespace(pod.getMetadata().getNamespace()).withFields(fields).list();
                if (eventList == null) {
                    return;
                }
                logger.warn("Events of matching pod: [" + pod.getMetadata().getName() + "]");
                for (Event event : eventList.getItems()) {
                    logger.info(String.format("%s\t\t%s", event.getReason(), event.getMessage()));
                }
            } catch (Throwable t) {
                logger.error("Failed to read events, due to:" + t.getMessage());
            } finally {
                logger.warn("---");
            }
        }

        /**
         * Finds the pod that correspond to the specified resource.
         *
         * @param resource
         *     The resource.
         *
         * @return The podList with the matching pods.
         */
        public <T extends HasMetadata> PodList podsOf(T resource) {
            if (resource instanceof Pod) {
                return new PodListBuilder().withItems((Pod) resource).build();
            } else if (resource instanceof Endpoints) {
                return podsOf(client.services()
                    .inNamespace(resource.getMetadata().getNamespace())
                    .withName(resource.getMetadata().getName())
                    .get());
            } else if (resource instanceof Service) {
                return client.pods()
                    .inNamespace(resource.getMetadata().getNamespace())
                    .withLabels(((Service) resource).getSpec().getSelector())
                    .list();
            } else if (resource instanceof ReplicationController) {
                return client.pods()
                    .inNamespace(resource.getMetadata().getNamespace())
                    .withLabels(((ReplicationController) resource).getSpec().getSelector())
                    .list();
            } else if (resource instanceof ReplicaSet) {
                return findMatching((ReplicaSet) resource);
            } else if (resource instanceof Deployment) {
                return findMatching((Deployment) resource);
            } else {
                return new PodListBuilder().build();
            }
        }

        /**
         * Returns the {@link PodList} that match the specified {@link Deployment}.
         *
         * @param deployment
         *     The {@link Deployment}
         */
        public PodList findMatching(Deployment deployment) {
            FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister =
                client.pods().inNamespace(deployment.getMetadata().getNamespace());
            if (deployment.getSpec().getSelector().getMatchLabels() != null) {
                podLister.withLabels(deployment.getSpec().getSelector().getMatchLabels());
            }
            if (deployment.getSpec().getSelector().getMatchExpressions() != null) {
                for (LabelSelectorRequirement req : deployment.getSpec().getSelector().getMatchExpressions()) {
                    switch (req.getOperator()) {
                        case "In":
                            podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[] {}));
                            break;
                        case "NotIn":
                            podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[] {}));
                            break;
                        case "DoesNotExist":
                            podLister.withoutLabel(req.getKey());
                            break;
                        case "Exists":
                            podLister.withLabel(req.getKey());
                            break;
                    }
                }
            }
            return podLister.list();
        }

        /**
         * Returns the {@link PodList} that match the specified {@link ReplicaSet}.
         *
         * @param replicaSet
         *     The {@link ReplicaSet}
         */
        public PodList findMatching(ReplicaSet replicaSet) {
            FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister =
                client.pods().inNamespace(replicaSet.getMetadata().getNamespace());
            if (replicaSet.getSpec().getSelector().getMatchLabels() != null) {
                podLister.withLabels(replicaSet.getSpec().getSelector().getMatchLabels());
            }
            if (replicaSet.getSpec().getSelector().getMatchExpressions() != null) {
                for (LabelSelectorRequirement req : replicaSet.getSpec().getSelector().getMatchExpressions()) {
                    switch (req.getOperator()) {
                        case "In":
                            podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[] {}));
                            break;
                        case "NotIn":
                            podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[] {}));
                            break;
                        case "DoesNotExist":
                            podLister.withoutLabel(req.getKey());
                            break;
                        case "Exists":
                            podLister.withLabel(req.getKey());
                            break;
                    }
                }
            }
            return podLister.list();
        }

        @Override
        public FeedbackProvider toImmutable() {
            return this;
        }
    }
}


using System;
using System.IO;
using Dynamo.PackageManager.Interfaces;

namespace Dynamo.PackageManager
{
    /// <summary>
    ///     An IFileCompressor that actually attempts to compress a directory
    /// </summary>
    public class MutatingFileCompressor : IFileCompressor
    {
        public IFileInfo Zip(IDirectoryInfo directory)
        {
            if (directory == null) throw new ArgumentNullException("directory");

            if (!(new MutatingFileSystem()).DirectoryExists(directory.FullName))
            {
                throw new DirectoryNotFoundException(directory.FullName);
            }

            return new RealFileInfo(Greg.Utility.FileUtilities.Zip(directory.FullName));
        }
    }
}


Id	Name	Info	BornPosition[1]	BornPosition[2]	BornPosition[3]	BornPosition[4]	BornPosition[5]	LookPosition[1]	LookPosition[2]	LookPosition[3]	LookPosition[4]	LookPosition[5]	DefaultObstacleArea[1]	DefaultObstacleArea[2]	DefaultObstacleArea[3]	DefaultObstacleArea[4]	DefaultDynamicObject[1]	DefaultDynamicObject[2]	DefaultDynamicObject[3]	DefaultDynamicObject[4]
300904010	Scene00905a	30090405	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904020	Scene00904a	30090403	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904030	Scene07000a	30090403	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904040	Scene00903a	30090425	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904050	Scene00903a	30090405	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904060	Scene00903a	30090405	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904070	Scene00903a	30090405	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904110	Scene00905a	30090405	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904120	Scene00904a	30090403	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904130	Scene00906a	30090413	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904140	Scene00903a	30090425	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904210	Scene00903a	30090421	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904220	Scene00903a	30090421	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904230	Scene00903a	30090421	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904240	Scene00903a	30090421	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904250	Scene00903a	30090425	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1
300904310	Scene00903a	20000501	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1					ZXYP
300904320	Scene00903a	20000501	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1					ZXYP
300904330	Scene00903a	20000501	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1					ZXYP
300904340	Scene00903a	20000501	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1					ZXYP
300904350	Scene00903a	20000501	PB1	PB2	PB3	PB4	PB5	S1	S1	S1	S1	S1					ZXYP


// 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 generate

package windows

//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go


// Copyright 2017, 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.md file.

package value

import (
	"fmt"
	"math"
	"reflect"
	"sort"
)

// SortKeys sorts a list of map keys, deduplicating keys if necessary.
// The type of each value must be comparable.
func SortKeys(vs []reflect.Value) []reflect.Value {
	if len(vs) == 0 {
		return vs
	}

	// Sort the map keys.
	sort.SliceStable(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) })

	// Deduplicate keys (fails for NaNs).
	vs2 := vs[:1]
	for _, v := range vs[1:] {
		if isLess(vs2[len(vs2)-1], v) {
			vs2 = append(vs2, v)
		}
	}
	return vs2
}

// isLess is a generic function for sorting arbitrary map keys.
// The inputs must be of the same type and must be comparable.
func isLess(x, y reflect.Value) bool {
	switch x.Type().Kind() {
	case reflect.Bool:
		return !x.Bool() && y.Bool()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return x.Int() < y.Int()
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return x.Uint() < y.Uint()
	case reflect.Float32, reflect.Float64:
		// NOTE: This does not sort -0 as less than +0
		// since Go maps treat -0 and +0 as equal keys.
		fx, fy := x.Float(), y.Float()
		return fx < fy || math.IsNaN(fx) && !math.IsNaN(fy)
	case reflect.Complex64, reflect.Complex128:
		cx, cy := x.Complex(), y.Complex()
		rx, ix, ry, iy := real(cx), imag(cx), real(cy), imag(cy)
		if rx == ry || (math.IsNaN(rx) && math.IsNaN(ry)) {
			return ix < iy || math.IsNaN(ix) && !math.IsNaN(iy)
		}
		return rx < ry || math.IsNaN(rx) && !math.IsNaN(ry)
	case reflect.Ptr, reflect.UnsafePointer, reflect.Chan:
		return x.Pointer() < y.Pointer()
	case reflect.String:
		return x.String() < y.String()
	case reflect.Array:
		for i := 0; i < x.Len(); i++ {
			if isLess(x.Index(i), y.Index(i)) {
				return true
			}
			if isLess(y.Index(i), x.Index(i)) {
				return false
			}
		}
		return false
	case reflect.Struct:
		for i := 0; i < x.NumField(); i++ {
			if isLess(x.Field(i), y.Field(i)) {
				return true
			}
			if isLess(y.Field(i), x.Field(i)) {
				return false
			}
		}
		return false
	case reflect.Interface:
		vx, vy := x.Elem(), y.Elem()
		if !vx.IsValid() || !vy.IsValid() {
			return !vx.IsValid() && vy.IsValid()
		}
		tx, ty := vx.Type(), vy.Type()
		if tx == ty {
			return isLess(x.Elem(), y.Elem())
		}
		if tx.Kind() != ty.Kind() {
			return vx.Kind() < vy.Kind()
		}
		if tx.String() != ty.String() {
			return tx.String() < ty.String()
		}
		if tx.PkgPath() != ty.PkgPath() {
			return tx.PkgPath() < ty.PkgPath()
		}
		// This can happen in rare situations, so we fallback to just comparing
		// the unique pointer for a reflect.Type. This guarantees deterministic
		// ordering within a program, but it is obviously not stable.
		return reflect.ValueOf(vx.Type()).Pointer() < reflect.ValueOf(vy.Type()).Pointer()
	default:
		// Must be Func, Map, or Slice; which are not comparable.
		panic(fmt.Sprintf("%T is not comparable", x.Type()))
	}
}


// THIS FILE IS AUTO-GENERATED. DO NOT EDIT
package ai.verta.swagger._public.registry.model

import scala.util.Try

import net.liftweb.json._

import ai.verta.swagger._public.registry.model.ArtifactTypeEnumArtifactType._
import ai.verta.swagger._public.registry.model.OperatorEnumOperator._
import ai.verta.swagger._public.registry.model.ProtobufNullValue._
import ai.verta.swagger._public.registry.model.TernaryEnumTernary._
import ai.verta.swagger._public.registry.model.ValueTypeEnumValueType._
import ai.verta.swagger._public.registry.model.VisibilityEnumVisibility._
import ai.verta.swagger.client.objects._

case class RegistryFindRegisteredModelRequest (
  ascending: Option[Boolean] = None,
  pagination: Option[CommonPagination] = None,
  predicates: Option[List[CommonKeyValueQuery]] = None,
  sort_key: Option[String] = None,
  workspace_name: Option[String] = None
) extends BaseSwagger {
  def toJson(): JValue = RegistryFindRegisteredModelRequest.toJson(this)
}

object RegistryFindRegisteredModelRequest {
  def toJson(obj: RegistryFindRegisteredModelRequest): JObject = {
    new JObject(
      List[Option[JField]](
        obj.ascending.map(x => JField("ascending", JBool(x))),
        obj.pagination.map(x => JField("pagination", ((x: CommonPagination) => CommonPagination.toJson(x))(x))),
        obj.predicates.map(x => JField("predicates", ((x: List[CommonKeyValueQuery]) => JArray(x.map(((x: CommonKeyValueQuery) => CommonKeyValueQuery.toJson(x)))))(x))),
        obj.sort_key.map(x => JField("sort_key", JString(x))),
        obj.workspace_name.map(x => JField("workspace_name", JString(x)))
      ).flatMap(x => x match {
        case Some(y) => List(y)
        case None => Nil
      })
    )
  }

  def fromJson(value: JValue): RegistryFindRegisteredModelRequest =
    value match {
      case JObject(fields) => {
        val fieldsMap = fields.map(f => (f.name, f.value)).toMap
        RegistryFindRegisteredModelRequest(
          // TODO: handle required
          ascending = fieldsMap.get("ascending").map(JsonConverter.fromJsonBoolean),
          pagination = fieldsMap.get("pagination").map(CommonPagination.fromJson),
          predicates = fieldsMap.get("predicates").map((x: JValue) => x match {case JArray(elements) => elements.map(CommonKeyValueQuery.fromJson); case _ => throw new IllegalArgumentException(s"unknown type ${x.getClass.toString}")}),
          sort_key = fieldsMap.get("sort_key").map(JsonConverter.fromJsonString),
          workspace_name = fieldsMap.get("workspace_name").map(JsonConverter.fromJsonString)
        )
      }
      case _ => throw new IllegalArgumentException(s"unknown type ${value.getClass.toString}")
    }
}


// +build example,go1.7

package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

// Uploads a file to S3 given a bucket and object key. Also takes a duration
// value to terminate the update if it doesn't complete within that time.
//
// The AWS Region needs to be provided in the AWS shared config or on the
// environment variable as `AWS_REGION`. Credentials also must be provided
// Will default to shared config file, but can load from environment if provided.
//
// Usage:
//   # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail
//   go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt
func main() {
	var bucket, key string
	var timeout time.Duration

	flag.StringVar(&bucket, "b", "", "Bucket name.")
	flag.StringVar(&key, "k", "", "Object key name.")
	flag.DurationVar(&timeout, "d", 0, "Upload timeout.")
	flag.Parse()

	sess := session.Must(session.NewSession())
	svc := s3.New(sess)

	// Create a context with a timeout that will abort the upload if it takes
	// more than the passed in timeout.
	ctx := context.Background()
	var cancelFn func()
	if timeout > 0 {
		ctx, cancelFn = context.WithTimeout(ctx, timeout)
	}
	// Ensure the context is canceled to prevent leaking.
	// See context package for more information, https://golang.org/pkg/context/
	defer cancelFn()

	// Uploads the object to S3. The Context will interrupt the request if the
	// timeout expires.
	_, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		Body:   os.Stdin,
	})
	if err != nil {
		if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode {
			// If the SDK can determine the request or retry delay was canceled
			// by a context the CanceledErrorCode error code will be returned.
			fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err)
		} else {
			fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err)
		}
		os.Exit(1)
	}

	fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key)
}


#!/bin/sh

if test "$(id -u)" != '0'; then
    echo "This test only works when run as root. Skipping." >&2
    exit 77
fi

if test "$(id -u nobody)" = ""; then
    echo "This test requires that your system have a 'nobody' user. Sorry." >&2
    exit 1
fi

if test "$OVERRIDE_GCDA_PERMISSIONS_HACK" = "yes"; then
  find src -type f -name '*gcda' -print0 | xargs -0 chmod 0666
fi

"${builddir:-.}/src/test/test-switch-id" nobody setuid          || exit 1
"${builddir:-.}/src/test/test-switch-id" nobody root-bind-low   || exit 1
"${builddir:-.}/src/test/test-switch-id" nobody setuid-strict   || exit 1
"${builddir:-.}/src/test/test-switch-id" nobody built-with-caps || exit 0
# ... Go beyond this point only if we were built with capability support.

"${builddir:-.}/src/test/test-switch-id" nobody have-caps       || exit 1
"${builddir:-.}/src/test/test-switch-id" nobody setuid-keepcaps || exit 1

if test "$OVERRIDE_GCDA_PERMISSIONS_HACK" = "yes"; then
    find src -type f -name '*gcda' -print0 | xargs -0 chmod 0644
fi

echo "All okay"

exit 0


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

#ifndef REMOTING_HOST_TOKEN_VALIDATOR_BASE_H_
#define REMOTING_HOST_TOKEN_VALIDATOR_BASE_H_

#include <memory>

#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "net/ssl/client_cert_identity.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context_getter.h"
#include "remoting/host/third_party_auth_config.h"
#include "remoting/protocol/token_validator.h"
#include "url/gurl.h"

namespace net {
class ClientCertStore;
}

namespace remoting {

class TokenValidatorBase
    : public net::URLRequest::Delegate,
      public protocol::TokenValidator {
 public:
  TokenValidatorBase(
      const ThirdPartyAuthConfig& third_party_auth_config,
      const std::string& token_scope,
      scoped_refptr<net::URLRequestContextGetter> request_context_getter);
  ~TokenValidatorBase() override;

  // TokenValidator interface.
  void ValidateThirdPartyToken(
      const std::string& token,
      const base::Callback<void(const std::string& shared_secret)>&
          on_token_validated) override;

  const GURL& token_url() const override;
  const std::string& token_scope() const override;

  // URLRequest::Delegate interface.
  void OnResponseStarted(net::URLRequest* source, int net_result) override;
  void OnReadCompleted(net::URLRequest* source, int net_result) override;
  void OnReceivedRedirect(net::URLRequest* request,
                          const net::RedirectInfo& redirect_info,
                          bool* defer_redirect) override;
  void OnCertificateRequested(
      net::URLRequest* source,
      net::SSLCertRequestInfo* cert_request_info) override;

 protected:
  void OnCertificatesSelected(net::ClientCertStore* unused,
                              net::ClientCertIdentityList selected_certs);

  virtual void StartValidateRequest(const std::string& token) = 0;
  virtual void ContinueWithCertificate(
      scoped_refptr<net::X509Certificate> client_cert,
      scoped_refptr<net::SSLPrivateKey> client_private_key);
  virtual bool IsValidScope(const std::string& token_scope);
  std::string ProcessResponse(int net_result);

  // Constructor parameters.
  ThirdPartyAuthConfig third_party_auth_config_;
  std::string token_scope_;
  scoped_refptr<net::URLRequestContextGetter> request_context_getter_;

  // URLRequest related fields.
  std::unique_ptr<net::URLRequest> request_;
  scoped_refptr<net::IOBuffer> buffer_;
  std::string data_;

  // This is set by OnReceivedRedirect() if the token validation request is
  // being re-submitted as a POST request. This can happen if the authentication
  // cookie has not yet been set, and a login handler redirection causes the
  // POST request to be turned into a GET operation, losing the POST data. In
  // this case, an immediate retry (with the same cookie jar) is expected to
  // succeeed.
  bool retrying_request_ = false;

  // Stores the most recently requested token, in case the validation request
  // needs to be retried.
  std::string token_;

  base::Callback<void(const std::string& shared_secret)> on_token_validated_;

  base::WeakPtrFactory<TokenValidatorBase> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(TokenValidatorBase);
};

}  // namespace remoting

#endif  // REMOTING_HOST_TOKEN_VALIDATOR_BASE_H


import py
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest

class AppTestNDIter(BaseNumpyAppTest):
    def test_type(self):
        import numpy as np
        assert type(np.nditer) is type
        assert np.nditer.__name__ == 'nditer'
        assert np.nditer.__module__ == 'numpy'
        try:
            class Sub(np.nditer):
                pass
        except TypeError as e:
            assert "not an acceptable base" in str(e)
        else:
            assert False

    def test_basic(self):
        from numpy import arange, nditer, ndarray
        a = arange(6).reshape(2,3)
        i = nditer(a)
        r = []
        for x in i:
            assert type(x) is ndarray
            assert x.base is i
            assert x.shape == ()
            assert x.strides == ()
            exc = raises(ValueError, "x[()] = 42")
            assert str(exc.value) == 'assignment destination is read-only'
            r.append(x)
        assert r == [0, 1, 2, 3, 4, 5]
        r = []
        for x in nditer(a.T):
            r.append(x)
        assert r == [0, 1, 2, 3, 4, 5]

    def test_order(self):
        from numpy import arange, nditer
        a = arange(6).reshape(2,3)
        r = []
        for x in nditer(a, order='C'):
            r.append(x)
        assert r == [0, 1, 2, 3, 4, 5]
        r = []
        for x in nditer(a, order='F'):
            r.append(x)
        assert r == [0, 3, 1, 4, 2, 5]

    def test_readwrite(self):
        from numpy import arange, nditer, ndarray
        a = arange(6).reshape(2,3)
        i = nditer(a, op_flags=['readwrite'])
        for x in i:
            assert type(x) is ndarray
            assert x.base is i
            assert x.shape == ()
            assert x.strides == ()
            x[...] = 2 * x
        assert (a == [[0, 2, 4], [6, 8, 10]]).all()

    def test_external_loop(self):
        from numpy import arange, nditer, array
        a = arange(24).reshape(2, 3, 4)
        import sys
        r = []
        for x in nditer(a, flags=['external_loop']):
            r.append(x)
        assert len(r) == 1
        assert r[0].shape == (24,)
        assert (array(r) == range(24)).all()
        r = []
        for x in nditer(a, flags=['external_loop'], order='F'):
            r.append(x)
        assert len(r) == 12
        assert (array(r) == [[ 0, 12], [ 4, 16], [ 8, 20], [ 1, 13], [ 5, 17], [ 9, 21],
                             [ 2, 14], [ 6, 18], [10, 22], [ 3, 15], [ 7, 19], [11, 23],
                            ]).all()
        e = raises(ValueError, 'r[0][0] = 0')
        assert str(e.value) == 'assignment destination is read-only'
        r = []
        for x in nditer(a.T, flags=['external_loop'], order='F'):
            r.append(x)
        array_r = array(r)
        assert len(array_r.shape) == 2
        assert array_r.shape == (1,24)
        assert (array(r) == arange(24)).all()

    def test_index(self):
        from numpy import arange, nditer
        a = arange(6).reshape(2,3)

        r = []
        it = nditer(a, flags=['c_index'])
        assert it.has_index
        for value in it:
            r.append((value, it.index))
        assert r == [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
        exc = None
        try:
            it.index
        except ValueError as e:
            exc = e
        assert exc

        r = []
        it = nditer(a, flags=['f_index'])
        assert it.has_index
        for value in it:
            r.append((value, it.index))
        assert r == [(0, 0), (1, 2), (2, 4), (3, 1), (4, 3), (5, 5)]

    def test_iters_with_different_order(self):
        from numpy import nditer, array

        a = array([[1, 2], [3, 4]], order="C")
        b = array([[1, 2], [3, 4]], order="F")

        it = nditer([a, b])
        r = list(it)
        assert r == zip(range(1, 5), range(1, 5))

    def test_interface(self):
        from numpy import arange, nditer, zeros
        import sys
        a = arange(6).reshape(2,3)
        r = []
        it = nditer(a, flags=['f_index'])
        while not it.finished:
            r.append((it[0], it.index))
            it.iternext()
        assert r == [(0, 0), (1, 2), (2, 4), (3, 1), (4, 3), (5, 5)]
        it = nditer(a, flags=['multi_index'], op_flags=['writeonly'])
        if '__pypy__' in sys.builtin_module_names:
            raises(NotImplementedError, 'it[0] = 3')
            skip('nditer.__setitem__ not implmented')
        while not it.finished:
            it[0] = it.multi_index[1] - it.multi_index[0]
            it.iternext()
        assert (a == [[0, 1, 2], [-1, 0, 1]]).all()
        # b = zeros((2, 3))
        # exc = raises(ValueError, nditer, b, flags=['c_index', 'external_loop'])
        # assert str(exc.value).startswith("Iterator flag EXTERNAL_LOOP cannot")

    def test_buffered(self):
        from numpy import arange, nditer, array, isscalar
        a = arange(24).reshape(2, 3, 4)
        r = []
        for x in nditer(a, flags=['external_loop'], order='F'):
            r.append(x)
        array_r = array(r)
        assert len(array_r.shape) == 2
        assert array_r.shape == (12, 2)
        assert (array_r == [[0, 12], [4, 16], [8, 20], [1, 13], [5, 17], [9, 21],
                      [2, 14], [6, 18], [10, 22], [3, 15], [7, 19], [11, 23]]).all
        assert (a == arange(24).reshape(2, 3, 4)).all()
        a[0,0,0] = 100
        assert r[0][0] == 100

        r = []
        it = nditer(a, flags=['buffered'], order='F')
        for x in it:
            r.append(x)
        array_r = array(r)
        assert len(array_r.shape) == 1
        assert array_r.shape == (24,)
        assert r[0].shape == ()
        assert not isscalar(r[0])
        assert (array_r == [0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21,
                      2, 14, 6, 18, 10, 22, 3, 15, 7, 19, 11, 23]).all
        assert a.shape == (2, 3, 4)
        a[0,0,0] = 0
        # buffered copies the data into a tmp array
        assert r[0] == 100
        assert (a == arange(24).reshape(2, 3, 4)).all()

        r = []
        for x in nditer(a, flags=['external_loop', 'buffered'], order='F'):
            r.append(x)
        assert r[0].shape == (24,)
        assert (array_r == [0, 12, 4, 16, 8, 20, 1, 13, 5, 17, 9, 21,
                      2, 14, 6, 18, 10, 22, 3, 15, 7, 19, 11, 23]).all
        assert a.shape == (2, 3, 4)
        assert (a == arange(24).reshape(2, 3, 4)).all()

    def test_zerosize(self):
        from numpy import nditer, array
        for a in [ array([]), array([1]), array([1, 2]) ]:
            buffersize = max(16 * 1024 ** 2 // a.itemsize, 1)
            r = []
            for chunk in nditer(a,
                    flags=['external_loop', 'buffered', 'zerosize_ok'],
                    buffersize=buffersize, order='C'):
                r.append(chunk)
            assert (r == a).all()

    def test_op_dtype(self):
        from numpy import arange, nditer, sqrt, array
        a = arange(6).reshape(2,3) - 3
        exc = raises(TypeError, nditer, a, op_dtypes=['complex'])
        assert str(exc.value).startswith("Iterator operand required copying or buffering")
        exc = raises(ValueError, nditer, a, op_flags=['copy'], op_dtypes=['complex128'])
        assert str(exc.value) == "None of the iterator flags READWRITE," \
                    " READONLY, or WRITEONLY were specified for an operand"
        r = []
        for x in nditer(a, op_flags=['readonly','copy'],
                        op_dtypes=['complex128']):
            r.append(sqrt(x))
        assert abs((array(r) - [1.73205080757j, 1.41421356237j, 1j, 0j,
                                1+0j, 1.41421356237+0j]).sum()) < 1e-5
        multi = nditer([None, array([2, 3], dtype='int64'), array(2., dtype='double')],
                       op_dtypes=['int64', 'int64', 'float64'],
                       op_flags=[['writeonly', 'allocate'], ['readonly'], ['readonly']])
        for a, b, c in multi:
            a[...] = b * c
        assert (multi.operands[0] == [4, 6]).all()

    def test_casting(self):
        from numpy import arange, nditer
        import sys
        a = arange(6.)
        exc = raises(TypeError, nditer, a, flags=['buffered'], op_dtypes=['float32'])
        assert str(exc.value) == "Iterator operand 0 dtype could not be " + \
            "cast from dtype('float64') to dtype('float32') according to the" +\
            " rule 'safe'"
        r = []
        for x in nditer(a, flags=['buffered'], op_dtypes=['float32'],
                                casting='same_kind'):
            r.append(x)
        assert r == [0., 1., 2., 3., 4., 5.]
        exc = raises(TypeError, nditer, a, flags=['buffered'],
                        op_dtypes=['int32'], casting='same_kind')
        assert str(exc.value).startswith("Iterator operand 0 dtype could not be cast")
        r = []
        b = arange(6)
        exc = raises(TypeError, nditer, b, flags=['buffered'], op_dtypes=['float64'],
                                op_flags=['readwrite'], casting='same_kind')
        assert str(exc.value).startswith("Iterator requested dtype could not be cast")

    def test_broadcast(self):
        from numpy import arange, nditer
        a = arange(3)
        b = arange(6).reshape(2,3)
        r = []
        it = nditer([a, b])
        assert it.itersize == 6
        for x,y in it:
            r.append((x, y))
        assert r == [(0, 0), (1, 1), (2, 2), (0, 3), (1, 4), (2, 5)]
        a = arange(2)
        exc = raises(ValueError, nditer, [a, b])
        assert str(exc.value).find('shapes (2,) (2,3)') > 0

    def test_outarg(self):
        from numpy import nditer, zeros, arange
        import sys

        def square1(a):
            it = nditer([a, None])
            for x,y in it:
                y[...] = x*x
            return it.operands[1]
        assert (square1([1, 2, 3]) == [1, 4, 9]).all()

        def square2(a, out=None):
            it = nditer([a, out], flags=['external_loop', 'buffered'],
                        op_flags=[['readonly'],
                                  ['writeonly', 'allocate', 'no_broadcast']])
            for x,y in it:
                y[...] = x*x
            return it.operands[1]
        assert (square2([1, 2, 3]) == [1, 4, 9]).all()
        b = zeros((3, ))
        c = square2([1, 2, 3], out=b)
        assert (c == [1., 4., 9.]).all()
        assert (b == c).all()
        exc = raises(ValueError, square2, arange(6).reshape(2, 3), out=b)
        assert str(exc.value).find("doesn't match the broadcast shape") > 0

    def test_outer_product(self):
        from numpy import nditer, arange
        a = arange(3)
        import sys
        b = arange(8).reshape(2,4)
        if '__pypy__' in sys.builtin_module_names:
            raises(NotImplementedError, nditer, [a, b, None], flags=['external_loop'],
                   op_axes=[[0, -1, -1], [-1, 0, 1], None])
            skip('nditer op_axes not implemented yet')
        it = nditer([a, b, None], flags=['external_loop'],
                    op_axes=[[0, -1, -1], [-1, 0, 1], None])
        for x, y, z in it:
            z[...] = x*y
        assert it.operands[2].shape == (3, 2, 4)
        for i in range(a.size):
            assert (it.operands[2][i] == a[i]*b).all()

    def test_reduction(self):
        from numpy import nditer, arange, array
        import sys
        a = arange(24).reshape(2, 3, 4)
        b = array(0)
        if '__pypy__' in sys.builtin_module_names:
            raises(NotImplementedError, nditer, [a, b], flags=['reduce_ok'])
            skip('nditer reduce_ok not implemented yet')
        #reduction operands must be readwrite
        for x, y in nditer([a, b], flags=['reduce_ok', 'external_loop'],
                            op_flags=[['readonly'], ['readwrite']]):
            y[...] += x
        assert b == 276
        assert b == a.sum()

        # reduction and allocation requires op_axes and initialization
        it = nditer([a, None], flags=['reduce_ok', 'external_loop'],
                    op_flags=[['readonly'], ['readwrite', 'allocate']],
                    op_axes=[None, [0,1,-1]])
        it.operands[1][...] = 0
        for x, y in it:
            y[...] += x

        assert (it.operands[1] == [[6, 22, 38], [54, 70, 86]]).all()
        assert (it.operands[1] == a.sum(axis=2)).all()

        # previous example with buffering, requires more flags and reset
        it = nditer([a, None], flags=['reduce_ok', 'external_loop',
                                      'buffered', 'delay_bufalloc'],
                    op_flags=[['readonly'], ['readwrite', 'allocate']],
                    op_axes=[None, [0,1,-1]])
        it.operands[1][...] = 0
        it.reset()
        for x, y in it:
            y[...] += x

        assert (it.operands[1] == [[6, 22, 38], [54, 70, 86]]).all()
        assert (it.operands[1] == a.sum(axis=2)).all()

    def test_get_dtypes(self):
        from numpy import array, nditer
        x = array([1, 2])
        y = array([1.0, 2.0])
        assert nditer([x, y]).dtypes == (x.dtype, y.dtype)

    def test_multi_index(self):
        import numpy as np
        a = np.arange(6).reshape(2, 3)
        it = np.nditer(a, flags=['multi_index'])
        res = []
        while not it.finished:
            res.append((it[0], it.multi_index))
            it.iternext()
        assert res == [(0, (0, 0)), (1, (0, 1)),
                       (2, (0, 2)), (3, (1, 0)),
                       (4, (1, 1)), (5, (1, 2))]

    def test_itershape(self):
        # Check that allocated outputs work with a specified shape
        from numpy import nditer, arange
        import sys
        if '__pypy__' in sys.builtin_module_names:
            skip("op_axes not totally supported yet")
        a = arange(6, dtype='i2').reshape(2,3)
        i = nditer([a, None], [], [['readonly'], ['writeonly','allocate']],
                            op_axes=[[0,1,None], None],
                            itershape=(-1,-1,4))
        assert i.operands[1].shape == (2,3,4)
        assert i.operands[1].strides, (24,8,2)

        i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']],
                            op_axes=[[0,1,None], None],
                            itershape=(-1,-1,4))
        assert i.operands[1].shape, (3,2,4)
        assert i.operands[1].strides, (8,24,2)

        i = nditer([a.T, None], [], [['readonly'], ['writeonly','allocate']],
                            order='F',
                            op_axes=[[0,1,None], None],
                            itershape=(-1,-1,4))
        assert i.operands[1].shape, (3,2,4)
        assert i.operands[1].strides, (2,6,12)

        # If we specify 1 in the itershape, it shouldn't allow broadcasting
        # of that dimension to a bigger value
        raises(ValueError, nditer, [a, None], [],
                            [['readonly'], ['writeonly','allocate']],
                            op_axes=[[0,1,None], None],
                            itershape=(-1,1,4))


/***************************************************************************
 *   Copyright (C) 2017 by Texas Instruments, Inc.                         *
 *                                                                         *
 *   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, see <http://www.gnu.org/licenses/>. *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "imp.h"
#include "cc26xx.h"
#include <helper/binarybuffer.h>
#include <helper/time_support.h>
#include <target/algorithm.h>
#include <target/armv7m.h>
#include <target/image.h>

#define FLASH_TIMEOUT 8000

struct cc26xx_bank {
	const char *family_name;
	uint32_t icepick_id;
	uint32_t user_id;
	uint32_t device_type;
	uint32_t sector_length;
	bool probed;
	struct working_area *working_area;
	struct armv7m_algorithm armv7m_info;
	const uint8_t *algo_code;
	uint32_t algo_size;
	uint32_t algo_working_size;
	uint32_t buffer_addr[2];
	uint32_t params_addr[2];
};

static int cc26xx_auto_probe(struct flash_bank *bank);

static uint32_t cc26xx_device_type(uint32_t icepick_id, uint32_t user_id)
{
	uint32_t device_type = 0;

	switch (icepick_id & ICEPICK_ID_MASK) {
		case CC26X0_ICEPICK_ID:
			device_type = CC26X0_TYPE;
			break;
		case CC26X1_ICEPICK_ID:
			device_type = CC26X1_TYPE;
			break;
		case CC13X0_ICEPICK_ID:
			device_type = CC13X0_TYPE;
			break;
		case CC13X2_CC26X2_ICEPICK_ID:
		default:
			if ((user_id & USER_ID_CC13_MASK) != 0)
				device_type = CC13X2_TYPE;
			else
				device_type = CC26X2_TYPE;
			break;
	}

	return device_type;
}

static uint32_t cc26xx_sector_length(uint32_t icepick_id)
{
	uint32_t sector_length;

	switch (icepick_id & ICEPICK_ID_MASK) {
		case CC26X0_ICEPICK_ID:
		case CC26X1_ICEPICK_ID:
		case CC13X0_ICEPICK_ID:
			/* Chameleon family device */
			sector_length = CC26X0_SECTOR_LENGTH;
			break;
		case CC13X2_CC26X2_ICEPICK_ID:
		default:
			/* Agama family device */
			sector_length = CC26X2_SECTOR_LENGTH;
			break;
	}

	return sector_length;
}

static int cc26xx_wait_algo_done(struct flash_bank *bank, uint32_t params_addr)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;

	uint32_t status_addr = params_addr + CC26XX_STATUS_OFFSET;
	uint32_t status = CC26XX_BUFFER_FULL;
	long long start_ms;
	long long elapsed_ms;

	int retval = ERROR_OK;

	start_ms = timeval_ms();
	while (CC26XX_BUFFER_FULL == status) {
		retval = target_read_u32(target, status_addr, &status);
		if (ERROR_OK != retval)
			return retval;

		elapsed_ms = timeval_ms() - start_ms;
		if (elapsed_ms > 500)
			keep_alive();
		if (elapsed_ms > FLASH_TIMEOUT)
			break;
	};

	if (CC26XX_BUFFER_EMPTY != status) {
		LOG_ERROR("%s: Flash operation failed", cc26xx_bank->family_name);
		return ERROR_FAIL;
	}

	return ERROR_OK;
}

static int cc26xx_init(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;

	int retval;

	/* Make sure we've probed the flash to get the device and size */
	retval = cc26xx_auto_probe(bank);
	if (ERROR_OK != retval)
		return retval;

	/* Check for working area to use for flash helper algorithm */
	if (NULL != cc26xx_bank->working_area)
		target_free_working_area(target, cc26xx_bank->working_area);
	retval = target_alloc_working_area(target, cc26xx_bank->algo_working_size,
				&cc26xx_bank->working_area);
	if (ERROR_OK != retval)
		return retval;

	/* Confirm the defined working address is the area we need to use */
	if (CC26XX_ALGO_BASE_ADDRESS != cc26xx_bank->working_area->address)
		return ERROR_TARGET_RESOURCE_NOT_AVAILABLE;

	/* Write flash helper algorithm into target memory */
	retval = target_write_buffer(target, CC26XX_ALGO_BASE_ADDRESS,
				cc26xx_bank->algo_size, cc26xx_bank->algo_code);
	if (ERROR_OK != retval) {
		LOG_ERROR("%s: Failed to load flash helper algorithm",
			cc26xx_bank->family_name);
		target_free_working_area(target, cc26xx_bank->working_area);
		return retval;
	}

	/* Initialize the ARMv7 specific info to run the algorithm */
	cc26xx_bank->armv7m_info.common_magic = ARMV7M_COMMON_MAGIC;
	cc26xx_bank->armv7m_info.core_mode = ARM_MODE_THREAD;

	/* Begin executing the flash helper algorithm */
	retval = target_start_algorithm(target, 0, NULL, 0, NULL,
				CC26XX_ALGO_BASE_ADDRESS, 0, &cc26xx_bank->armv7m_info);
	if (ERROR_OK != retval) {
		LOG_ERROR("%s: Failed to start flash helper algorithm",
			cc26xx_bank->family_name);
		target_free_working_area(target, cc26xx_bank->working_area);
		return retval;
	}

	/*
	 * At this point, the algorithm is running on the target and
	 * ready to receive commands and data to flash the target
	 */

	return retval;
}

static int cc26xx_quit(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;

	int retval;

	/* Regardless of the algo's status, attempt to halt the target */
	(void)target_halt(target);

	/* Now confirm target halted and clean up from flash helper algorithm */
	retval = target_wait_algorithm(target, 0, NULL, 0, NULL, 0, FLASH_TIMEOUT,
				&cc26xx_bank->armv7m_info);

	target_free_working_area(target, cc26xx_bank->working_area);
	cc26xx_bank->working_area = NULL;

	return retval;
}

static int cc26xx_mass_erase(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;
	struct cc26xx_algo_params algo_params;

	int retval;

	if (TARGET_HALTED != target->state) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	retval = cc26xx_init(bank);
	if (ERROR_OK != retval)
		return retval;

	/* Initialize algorithm parameters */
	buf_set_u32(algo_params.address, 0, 32, 0);
	buf_set_u32(algo_params.length,  0, 32, 4);
	buf_set_u32(algo_params.command, 0, 32, CC26XX_CMD_ERASE_ALL);
	buf_set_u32(algo_params.status,  0, 32, CC26XX_BUFFER_FULL);

	/* Issue flash helper algorithm parameters for mass erase */
	retval = target_write_buffer(target, cc26xx_bank->params_addr[0],
				sizeof(algo_params), (uint8_t *)&algo_params);

	/* Wait for command to complete */
	if (ERROR_OK == retval)
		retval = cc26xx_wait_algo_done(bank, cc26xx_bank->params_addr[0]);

	/* Regardless of errors, try to close down algo */
	(void)cc26xx_quit(bank);

	return retval;
}

FLASH_BANK_COMMAND_HANDLER(cc26xx_flash_bank_command)
{
	struct cc26xx_bank *cc26xx_bank;

	if (CMD_ARGC < 6)
		return ERROR_COMMAND_SYNTAX_ERROR;

	cc26xx_bank = malloc(sizeof(struct cc26xx_bank));
	if (NULL == cc26xx_bank)
		return ERROR_FAIL;

	/* Initialize private flash information */
	memset((void *)cc26xx_bank, 0x00, sizeof(struct cc26xx_bank));
	cc26xx_bank->family_name = "cc26xx";
	cc26xx_bank->device_type = CC26XX_NO_TYPE;
	cc26xx_bank->sector_length = 0x1000;

	/* Finish initialization of bank */
	bank->driver_priv = cc26xx_bank;
	bank->next = NULL;

	return ERROR_OK;
}

static int cc26xx_erase(struct flash_bank *bank, int first, int last)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;
	struct cc26xx_algo_params algo_params;

	uint32_t address;
	uint32_t length;
	int retval;

	if (TARGET_HALTED != target->state) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	/* Do a mass erase if user requested all sectors of flash */
	if ((first == 0) && (last == (bank->num_sectors - 1))) {
		/* Request mass erase of flash */
		return cc26xx_mass_erase(bank);
	}

	address = first * cc26xx_bank->sector_length;
	length = (last - first + 1) * cc26xx_bank->sector_length;

	retval = cc26xx_init(bank);
	if (ERROR_OK != retval)
		return retval;

	/* Set up algorithm parameters for erase command */
	buf_set_u32(algo_params.address, 0, 32, address);
	buf_set_u32(algo_params.length,  0, 32, length);
	buf_set_u32(algo_params.command, 0, 32, CC26XX_CMD_ERASE_SECTORS);
	buf_set_u32(algo_params.status,  0, 32, CC26XX_BUFFER_FULL);

	/* Issue flash helper algorithm parameters for erase */
	retval = target_write_buffer(target, cc26xx_bank->params_addr[0],
				sizeof(algo_params), (uint8_t *)&algo_params);

	/* If no error, wait for erase to finish */
	if (ERROR_OK == retval)
		retval = cc26xx_wait_algo_done(bank, cc26xx_bank->params_addr[0]);

	/* Regardless of errors, try to close down algo */
	(void)cc26xx_quit(bank);

	return retval;
}

static int cc26xx_write(struct flash_bank *bank, const uint8_t *buffer,
	uint32_t offset, uint32_t count)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;
	struct cc26xx_algo_params algo_params[2];
	uint32_t size = 0;
	long long start_ms;
	long long elapsed_ms;
	uint32_t address;

	uint32_t index;
	int retval;

	if (TARGET_HALTED != target->state) {
		LOG_ERROR("Target not halted");
		return ERROR_TARGET_NOT_HALTED;
	}

	retval = cc26xx_init(bank);
	if (ERROR_OK != retval)
		return retval;

	/* Initialize algorithm parameters to default values */
	buf_set_u32(algo_params[0].command, 0, 32, CC26XX_CMD_PROGRAM);
	buf_set_u32(algo_params[1].command, 0, 32, CC26XX_CMD_PROGRAM);

	/* Write requested data, ping-ponging between two buffers */
	index = 0;
	start_ms = timeval_ms();
	address = bank->base + offset;
	while (count > 0) {

		if (count > cc26xx_bank->sector_length)
			size = cc26xx_bank->sector_length;
		else
			size = count;

		/* Put next block of data to flash into buffer */
		retval = target_write_buffer(target, cc26xx_bank->buffer_addr[index],
					size, buffer);
		if (ERROR_OK != retval) {
			LOG_ERROR("Unable to write data to target memory");
			break;
		}

		/* Update algo parameters for next block */
		buf_set_u32(algo_params[index].address, 0, 32, address);
		buf_set_u32(algo_params[index].length,  0, 32, size);
		buf_set_u32(algo_params[index].status,  0, 32, CC26XX_BUFFER_FULL);

		/* Issue flash helper algorithm parameters for block write */
		retval = target_write_buffer(target, cc26xx_bank->params_addr[index],
					sizeof(algo_params[index]), (uint8_t *)&algo_params[index]);
		if (ERROR_OK != retval)
			break;

		/* Wait for next ping pong buffer to be ready */
		index ^= 1;
		retval = cc26xx_wait_algo_done(bank, cc26xx_bank->params_addr[index]);
		if (ERROR_OK != retval)
			break;

		count -= size;
		buffer += size;
		address += size;

		elapsed_ms = timeval_ms() - start_ms;
		if (elapsed_ms > 500)
			keep_alive();
	}

	/* If no error yet, wait for last buffer to finish */
	if (ERROR_OK == retval) {
		index ^= 1;
		retval = cc26xx_wait_algo_done(bank, cc26xx_bank->params_addr[index]);
	}

	/* Regardless of errors, try to close down algo */
	(void)cc26xx_quit(bank);

	return retval;
}

static int cc26xx_probe(struct flash_bank *bank)
{
	struct target *target = bank->target;
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;

	uint32_t sector_length;
	uint32_t value;
	int num_sectors;
	int max_sectors;

	int retval;

	retval = target_read_u32(target, FCFG1_ICEPICK_ID, &value);
	if (ERROR_OK != retval)
		return retval;
	cc26xx_bank->icepick_id = value;

	retval = target_read_u32(target, FCFG1_USER_ID, &value);
	if (ERROR_OK != retval)
		return retval;
	cc26xx_bank->user_id = value;

	cc26xx_bank->device_type = cc26xx_device_type(cc26xx_bank->icepick_id,
		cc26xx_bank->user_id);

	sector_length = cc26xx_sector_length(cc26xx_bank->icepick_id);

	/* Set up appropriate flash helper algorithm */
	switch (cc26xx_bank->icepick_id & ICEPICK_ID_MASK) {
		case CC26X0_ICEPICK_ID:
		case CC26X1_ICEPICK_ID:
		case CC13X0_ICEPICK_ID:
			/* Chameleon family device */
			cc26xx_bank->algo_code = cc26x0_algo;
			cc26xx_bank->algo_size = sizeof(cc26x0_algo);
			cc26xx_bank->algo_working_size = CC26X0_WORKING_SIZE;
			cc26xx_bank->buffer_addr[0] = CC26X0_ALGO_BUFFER_0;
			cc26xx_bank->buffer_addr[1] = CC26X0_ALGO_BUFFER_1;
			cc26xx_bank->params_addr[0] = CC26X0_ALGO_PARAMS_0;
			cc26xx_bank->params_addr[1] = CC26X0_ALGO_PARAMS_1;
			max_sectors = CC26X0_MAX_SECTORS;
			break;
		case CC13X2_CC26X2_ICEPICK_ID:
		default:
			/* Agama family device */
			cc26xx_bank->algo_code = cc26x2_algo;
			cc26xx_bank->algo_size = sizeof(cc26x2_algo);
			cc26xx_bank->algo_working_size = CC26X2_WORKING_SIZE;
			cc26xx_bank->buffer_addr[0] = CC26X2_ALGO_BUFFER_0;
			cc26xx_bank->buffer_addr[1] = CC26X2_ALGO_BUFFER_1;
			cc26xx_bank->params_addr[0] = CC26X2_ALGO_PARAMS_0;
			cc26xx_bank->params_addr[1] = CC26X2_ALGO_PARAMS_1;
			max_sectors = CC26X2_MAX_SECTORS;
			break;
	}

	retval = target_read_u32(target, CC26XX_FLASH_SIZE_INFO, &value);
	if (ERROR_OK != retval)
		return retval;
	num_sectors = value & 0xff;
	if (num_sectors > max_sectors)
		num_sectors = max_sectors;

	bank->sectors = malloc(sizeof(struct flash_sector) * num_sectors);
	if (NULL == bank->sectors)
		return ERROR_FAIL;

	bank->base = CC26XX_FLASH_BASE_ADDR;
	bank->num_sectors = num_sectors;
	bank->size = num_sectors * sector_length;
	bank->write_start_alignment = 0;
	bank->write_end_alignment = 0;
	cc26xx_bank->sector_length = sector_length;

	for (int i = 0; i < num_sectors; i++) {
		bank->sectors[i].offset = i * sector_length;
		bank->sectors[i].size = sector_length;
		bank->sectors[i].is_erased = -1;
		bank->sectors[i].is_protected = 0;
	}

	/* We've successfully determined the stats on the flash bank */
	cc26xx_bank->probed = true;

	/* If we fall through to here, then all went well */

	return ERROR_OK;
}

static int cc26xx_auto_probe(struct flash_bank *bank)
{
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;

	int retval = ERROR_OK;

	if (!cc26xx_bank->probed)
		retval = cc26xx_probe(bank);

	return retval;
}

static int cc26xx_info(struct flash_bank *bank, char *buf, int buf_size)
{
	struct cc26xx_bank *cc26xx_bank = bank->driver_priv;
	int printed = 0;
	const char *device;

	switch (cc26xx_bank->device_type) {
		case CC26X0_TYPE:
			device = "CC26x0";
			break;
		case CC26X1_TYPE:
			device = "CC26x1";
			break;
		case CC13X0_TYPE:
			device = "CC13x0";
			break;
		case CC13X2_TYPE:
			device = "CC13x2";
			break;
		case CC26X2_TYPE:
			device = "CC26x2";
			break;
		case CC26XX_NO_TYPE:
		default:
			device = "Unrecognized";
			break;
	}

	printed = snprintf(buf, buf_size,
		"%s device: ICEPick ID 0x%08x, USER ID 0x%08x\n",
		device, cc26xx_bank->icepick_id, cc26xx_bank->user_id);

	if (printed >= buf_size)
		return ERROR_BUF_TOO_SMALL;

	return ERROR_OK;
}

const struct flash_driver cc26xx_flash = {
	.name = "cc26xx",
	.flash_bank_command = cc26xx_flash_bank_command,
	.erase = cc26xx_erase,
	.write = cc26xx_write,
	.read = default_flash_read,
	.probe = cc26xx_probe,
	.auto_probe = cc26xx_auto_probe,
	.erase_check = default_flash_blank_check,
	.info = cc26xx_info,
	.free_driver_priv = default_flash_free_driver_priv,
};


S : Y "0" T ;
T : "0" T ;
  : "1" T ;
  : ;
Y : "0" Y ;
  : "1" T ;


/*
 * Copyright (c) 2013 Kevin Wolf <kwolf@redhat.com>
 *
 * 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.
 */

#include "libc.h"
#include "multiboot.h"

int test_main(uint32_t magic, struct mb_info *mbi)
{
    uintptr_t entry_addr;
    struct mb_mmap_entry *entry;

    (void) magic;

    printf("Lower memory: %dk\n", mbi->mem_lower);
    printf("Upper memory: %dk\n", mbi->mem_upper);

    printf("\ne820 memory map:\n");

    for (entry_addr = mbi->mmap_addr;
         entry_addr < mbi->mmap_addr + mbi->mmap_length;
         entry_addr += entry->size + 4)
    {
        entry = (struct mb_mmap_entry*) entry_addr;

        printf("%#llx - %#llx: type %d [entry size: %d]\n",
               entry->base_addr,
               entry->base_addr + entry->length,
               entry->type,
               entry->size);
    }

    printf("\nmmap start:       %#x\n", mbi->mmap_addr);
    printf("mmap end:         %#x\n", mbi->mmap_addr + mbi->mmap_length);
    printf("real mmap end:    %#x\n", entry_addr);

    return 0;
}


//
//  DateHelper.h
//  AppWage
//
//  Created by Kyle Hankinson on 2014-03-14.
//  Copyright (c) 2014 Hankinsoft. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AWDateHelper : NSObject

+ (NSDateFormatter*) dateTimeFormatter;
+ (NSDateFormatter*) dateFormatter;

@end