text:
package com.infinities.skyport.model.configuration.platform;

import java.io.Serializable;

import com.infinities.skyport.model.FunctionConfiguration;

public class PushNotificationConfiguration implements Serializable, Cloneable {

	private static final long serialVersionUID = 1L;
	private FunctionConfiguration confirmSubscription = new FunctionConfiguration();
	private FunctionConfiguration createTopic = new FunctionConfiguration();
	private FunctionConfiguration getTopic = new FunctionConfiguration();
	private FunctionConfiguration listSubscriptions = new FunctionConfiguration();
	private FunctionConfiguration listTopicStatus = new FunctionConfiguration();
	private FunctionConfiguration listTopics = new FunctionConfiguration();
	private FunctionConfiguration publish = new FunctionConfiguration();
	private FunctionConfiguration removeTopic = new FunctionConfiguration();
	private FunctionConfiguration subscribe = new FunctionConfiguration();
	private FunctionConfiguration unsubscribe = new FunctionConfiguration();

	public FunctionConfiguration getConfirmSubscription() {
		return confirmSubscription;
	}

	public void setConfirmSubscription(FunctionConfiguration confirmSubscription) {
		this.confirmSubscription = confirmSubscription;
	}

	public FunctionConfiguration getCreateTopic() {
		return createTopic;
	}

	public void setCreateTopic(FunctionConfiguration createTopic) {
		this.createTopic = createTopic;
	}

	public FunctionConfiguration getGetTopic() {
		return getTopic;
	}

	public void setGetTopic(FunctionConfiguration getTopic) {
		this.getTopic = getTopic;
	}

	public FunctionConfiguration getListSubscriptions() {
		return listSubscriptions;
	}

	public void setListSubscriptions(FunctionConfiguration listSubscriptions) {
		this.listSubscriptions = listSubscriptions;
	}

	public FunctionConfiguration getListTopicStatus() {
		return listTopicStatus;
	}

	public void setListTopicStatus(FunctionConfiguration listTopicStatus) {
		this.listTopicStatus = listTopicStatus;
	}

	public FunctionConfiguration getListTopics() {
		return listTopics;
	}

	public void setListTopics(FunctionConfiguration listTopics) {
		this.listTopics = listTopics;
	}

	public FunctionConfiguration getPublish() {
		return publish;
	}

	public void setPublish(FunctionConfiguration publish) {
		this.publish = publish;
	}

	public FunctionConfiguration getRemoveTopic() {
		return removeTopic;
	}

	public void setRemoveTopic(FunctionConfiguration removeTopic) {
		this.removeTopic = removeTopic;
	}

	public FunctionConfiguration getSubscribe() {
		return subscribe;
	}

	public void setSubscribe(FunctionConfiguration subscribe) {
		this.subscribe = subscribe;
	}

	public FunctionConfiguration getUnsubscribe() {
		return unsubscribe;
	}

	public void setUnsubscribe(FunctionConfiguration unsubscribe) {
		this.unsubscribe = unsubscribe;
	}

	@Override
	public PushNotificationConfiguration clone() {
		PushNotificationConfiguration clone = new PushNotificationConfiguration();
		clone.confirmSubscription = confirmSubscription.clone();
		clone.createTopic = createTopic.clone();
		clone.getTopic = getTopic.clone();
		clone.listSubscriptions = listSubscriptions.clone();
		clone.listTopicStatus = listTopicStatus.clone();
		clone.listTopics = listTopics.clone();
		clone.publish = publish.clone();
		clone.removeTopic = removeTopic.clone();
		clone.subscribe = subscribe.clone();
		clone.unsubscribe = unsubscribe.clone();
		return clone;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((confirmSubscription == null) ? 0 : confirmSubscription.hashCode());
		result = prime * result + ((createTopic == null) ? 0 : createTopic.hashCode());
		result = prime * result + ((getTopic == null) ? 0 : getTopic.hashCode());
		result = prime * result + ((listSubscriptions == null) ? 0 : listSubscriptions.hashCode());
		result = prime * result + ((listTopicStatus == null) ? 0 : listTopicStatus.hashCode());
		result = prime * result + ((listTopics == null) ? 0 : listTopics.hashCode());
		result = prime * result + ((publish == null) ? 0 : publish.hashCode());
		result = prime * result + ((removeTopic == null) ? 0 : removeTopic.hashCode());
		result = prime * result + ((subscribe == null) ? 0 : subscribe.hashCode());
		result = prime * result + ((unsubscribe == null) ? 0 : unsubscribe.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PushNotificationConfiguration other = (PushNotificationConfiguration) obj;
		if (confirmSubscription == null) {
			if (other.confirmSubscription != null)
				return false;
		} else if (!confirmSubscription.equals(other.confirmSubscription))
			return false;
		if (createTopic == null) {
			if (other.createTopic != null)
				return false;
		} else if (!createTopic.equals(other.createTopic))
			return false;
		if (getTopic == null) {
			if (other.getTopic != null)
				return false;
		} else if (!getTopic.equals(other.getTopic))
			return false;
		if (listSubscriptions == null) {
			if (other.listSubscriptions != null)
				return false;
		} else if (!listSubscriptions.equals(other.listSubscriptions))
			return false;
		if (listTopicStatus == null) {
			if (other.listTopicStatus != null)
				return false;
		} else if (!listTopicStatus.equals(other.listTopicStatus))
			return false;
		if (listTopics == null) {
			if (other.listTopics != null)
				return false;
		} else if (!listTopics.equals(other.listTopics))
			return false;
		if (publish == null) {
			if (other.publish != null)
				return false;
		} else if (!publish.equals(other.publish))
			return false;
		if (removeTopic == null) {
			if (other.removeTopic != null)
				return false;
		} else if (!removeTopic.equals(other.removeTopic))
			return false;
		if (subscribe == null) {
			if (other.subscribe != null)
				return false;
		} else if (!subscribe.equals(other.subscribe))
			return false;
		if (unsubscribe == null) {
			if (other.unsubscribe != null)
				return false;
		} else if (!unsubscribe.equals(other.unsubscribe))
			return false;
		return true;
	}

}


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.6.0] - 2022-06-15
### Changed
- Breaking: remove meaningless `-total` and `-total-short` options

## [0.5.1] - 2022-04-06
### Fixed
- Don't skip directories `.` and `..`

## [0.5.0] - 2022-03-22
### Changed
- Ignore `vendor` and `testdata` directories and directories with names
  that begin with `.` or `_`

## [0.4.0] - 2021-12-19
### Added
- Support method receivers with type parameters introduced in Go 1.18

### Changed
- Use more efficient filepath.WalkDir instead of filepath.Walk

## [0.3.1] - 2020-10-20
### Added
- Test coverage

### Fixed
- Fix cyclomatic complexity for function literals (base complexity of 1 was missing)

## [0.3.0] - 2020-10-17
### Added
- New `-avg-short` and `-total-short` options for printing average and total cyclomatic complexities without label
- Export the `AnalyzeASTFile` function in package API
- Doc comments for exported functions and types

### Fixed
- Ignore `default` cases

## [0.2.0] - 2020-10-17
### Added
- Support for gocyclo as a package
- Support for ignoring of individual functions via a new `gocyclo:ignore` directive
- New `-total` option to compute total cyclomatic complexity
- New `-ignore` option to ignore files matching a regular expression
- Analysis of function literals at declaration level

### Changed
- Breaking: installation changed to `go get github.com/fzipp/gocyclo/cmd/gocyclo`

## [0.1.0] - 2020-10-17

### Added
- `go.mod` file; beginning of versioning

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Virtual_ATM
{
    class Program
    {
        static void Main(string[] args)
        {
            Router router =new Router();
            router.Propmt();

        }
    }
}


text:
package org.apache.myfaces.shared.util.el;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * You can use this class to trigger an action when a boolean is set to true.
 *
 * Example : in JSF pages, for dataTable, to remove elements :
 * Backing bean (#{inboxFace}).
 * public ActionsMap getRemoveEmailUnid(){
 *         return new ActionsMap(){
 *            public void performAction(String unid) {
 *                InboxMailDAO<TInboxMail> dao = getInboxMailDAO();
 *                TInboxMail email = dao.getByPrimaryKey( unid );
 *                dao.remove( email );
 *            }
 *        };
 *    }
 * JSF page :
 * <h:selectBooleanCheckbox value="#{inboxFace.removeEmailUnid[email.unid]}"/>
 */
public abstract class ActionsMap implements Map
{

    private Set keys;

    public ActionsMap()
    {
        // NoOp
    }

    public ActionsMap(Set keys)
    {
        this.keys = keys;
    }

    /**
     * This method should fire the command.
     */
    public abstract void performAction(String command);

    public int size()
    {
        return keys.size();
    }

    public boolean isEmpty()
    {
        return keys.isEmpty();
    }

    public boolean containsKey(Object key)
    {
        return keys.contains( key );
    }

    public boolean containsValue(Object value)
    {
        if( ! (value instanceof Boolean) )
        {
            return false;
        }
        return ((Boolean)value).booleanValue();
    }

    public Object get( Object key)
    {
        return Boolean.FALSE;
    }

    public Boolean put(String key, Boolean value)
    {
        if( value!=null && value.booleanValue() )
        {
            performAction(key);
        }
        return Boolean.FALSE;
    }

    public Object remove(Object key)
    {
        if( keys.remove( key ) )
        {
            return Boolean.FALSE;
        }
        return null;
    }

    public void putAll(Map map)
    {
        Iterator it = map.entrySet().iterator();

        while (it.hasNext())
        {
            Entry entry = (Entry) it.next();
            Object obj = entry.getValue();
            if( (obj instanceof Boolean) && ((Boolean) obj).booleanValue() )
            {
                performAction((String) entry.getKey());
            }
        }
    }

    public void clear()
    {
        keys.clear();
    }

    public Set keySet()
    {
        return keys;
    }

    public Collection values()
    {
        return Collections.nCopies(keys.size(), Boolean.FALSE);
    }

    public Set entrySet()
    {
        Set set = new HashSet( keys.size() );

        Iterator it = keys.iterator();

        while (it.hasNext())
        {
            String command = (String) it.next();
            set.add( new CommandEntry(command) );
        }

        return set;
    }

    private class CommandEntry implements Entry
    {

        private final String command;
        private boolean commandPerformed = false;

        public CommandEntry(String command)
        {
            this.command = command;
        }

        public Object getKey()
        {
            return command;
        }

        public Object getValue()
        {
            return Boolean.valueOf(commandPerformed);
        }

        public Object setValue(Object performCommand)
        {
            if( (performCommand instanceof Boolean) && ((Boolean)performCommand).booleanValue() )
            {
                performAction( command );
                commandPerformed = true;
            }
            return Boolean.valueOf(commandPerformed);
        }
    }
}


text:
/**
 * Utility functions for parsing numbers from strings.
 */

#pragma once

#include "mongo/base/status.h"
#include "mongo/base/string_data.h"
#include "mongo/client/export_macros.h"

namespace mongo {

/**
 * Parses a number out of a StringData.
 *
 * Parses "stringValue", interpreting it as a number of the given "base".  On success, stores
 * the parsed value into "*result" and returns Status::OK().
 *
 * Valid values for "base" are 2-36, with 0 meaning "choose the base by inspecting the prefix
 * on the number", as in strtol.  Returns Status::BadValue if an illegal value is supplied for
 * "base".
 *
 * The entirety of the string must consist of digits in the given base, except optionally the
 * first character may be "+" or "-", and hexadecimal numbers may begin "0x".  Same as strtol,
 * without the property of stripping whitespace at the beginning, and fails to parse if there
 * are non-digit characters at the end of the string.
 *
 * See parse_number.cpp for the available instantiations, and add any new instantiations there.
 */
template <typename NumberType>
MONGO_CLIENT_API Status MONGO_CLIENT_FUNC
parseNumberFromStringWithBase(const StringData& stringValue, int base, NumberType* result);

template <typename NumberType>
static Status parseNumberFromString(const StringData& stringValue, NumberType* result) {
    return parseNumberFromStringWithBase(stringValue, 0, result);
}

}  // namespace mongo


text:
package com.bearprogrammer.resource.test;

import com.bearprogrammer.resource.ProcessingException;
import com.bearprogrammer.resource.Processor;

public class UnusedTestProcessor implements Processor {

	@Override
	public int compareTo(Processor another) {
		return 0;
	}

	@Override
	public String process(String content) throws ProcessingException {
		return "";
	}

	@Override
	public boolean supportType(String typeName) {
		return false;
	}

}


text:
<?php

declare(strict_types=1);

namespace ServiceType;

use SoapFault;
use SoapClient\SoapClientBase;

/**
 * This class stands for Expand ServiceType
 * @package Ews
 * @subpackage Services
 * @author WsdlToPhp <contact@wsdltophp.com>
 */
class EwsExpand extends SoapClientBase
{
    /**
     * Sets the ExchangeImpersonation SoapHeader param
     * @uses SoapClientBase::setSoapHeader()
     * @param \StructType\EwsExchangeImpersonationType $exchangeImpersonation
     * @param string $namespace
     * @param bool $mustUnderstand
     * @param string $actor
     * @return \ServiceType\EwsExpand
     */
    public function setSoapHeaderExchangeImpersonation(\StructType\EwsExchangeImpersonationType $exchangeImpersonation, string $namespace = 'http://schemas.microsoft.com/exchange/services/2006/types', bool $mustUnderstand = false, ?string $actor = null): self
    {
        return $this->setSoapHeader($namespace, 'ExchangeImpersonation', $exchangeImpersonation, $mustUnderstand, $actor);
    }
    /**
     * Sets the MailboxCulture SoapHeader param
     * @uses SoapClientBase::setSoapHeader()
     * @param \StructType\EwsMailboxCultureType $mailboxCulture
     * @param string $namespace
     * @param bool $mustUnderstand
     * @param string $actor
     * @return \ServiceType\EwsExpand
     */
    public function setSoapHeaderMailboxCulture(\StructType\EwsMailboxCultureType $mailboxCulture, string $namespace = 'http://schemas.microsoft.com/exchange/services/2006/types', bool $mustUnderstand = false, ?string $actor = null): self
    {
        return $this->setSoapHeader($namespace, 'MailboxCulture', $mailboxCulture, $mustUnderstand, $actor);
    }
    /**
     * Sets the RequestServerVersion SoapHeader param
     * @uses SoapClientBase::setSoapHeader()
     * @param \StructType\EwsRequestServerVersion $requestServerVersion
     * @param string $namespace
     * @param bool $mustUnderstand
     * @param string $actor
     * @return \ServiceType\EwsExpand
     */
    public function setSoapHeaderRequestServerVersion(\StructType\EwsRequestServerVersion $requestServerVersion, string $namespace = 'http://schemas.microsoft.com/exchange/services/2006/types', bool $mustUnderstand = false, ?string $actor = null): self
    {
        return $this->setSoapHeader($namespace, 'RequestServerVersion', $requestServerVersion, $mustUnderstand, $actor);
    }
    /**
     * Method to call the operation originally named ExpandDL
     * Meta information extracted from the WSDL
     * - SOAPHeaderNames: ExchangeImpersonation, MailboxCulture, RequestServerVersion
     * - SOAPHeaderNamespaces: http://schemas.microsoft.com/exchange/services/2006/types, http://schemas.microsoft.com/exchange/services/2006/types, http://schemas.microsoft.com/exchange/services/2006/types
     * - SOAPHeaderTypes: \StructType\EwsExchangeImpersonationType, \StructType\EwsMailboxCultureType, \StructType\EwsRequestServerVersion
     * - SOAPHeaders: required, required, required
     * @uses SoapClientBase::getSoapClient()
     * @uses SoapClientBase::setResult()
     * @uses SoapClientBase::saveLastError()
     * @param \StructType\EwsExpandDLType $request
     * @return \StructType\EwsExpandDLResponseType|bool
     */
    public function ExpandDL(\StructType\EwsExpandDLType $request)
    {
        try {
            $this->setResult($resultExpandDL = $this->getSoapClient()->__soapCall('ExpandDL', [
                $request,
            ], [], [], $this->outputHeaders));

            return $resultExpandDL;
        } catch (SoapFault $soapFault) {
            $this->saveLastError(__METHOD__, $soapFault);

            return false;
        }
    }
    /**
     * Returns the result
     * @see SoapClientBase::getResult()
     * @return \StructType\EwsExpandDLResponseType
     */
    public function getResult()
    {
        return parent::getResult();
    }
}


text:
Plupload Endpoint [![Build Status](https://travis-ci.org/FlowCommunications/PluploadEndpoint.svg?branch=master)](https://travis-ci.org/FlowCommunications/PluploadEndpoint)
=================

An endpoint handler for the Plupload uploader.

External dependencies
---------------------
- `Symfony\Component\HttpFoundation`
- `Symfony\Component\Filesystem`

Install
-------
```
composer require flow/plupload-endpoint:0.1.x
```

Usage
-----

### Framework agnostic request/response

```php
use Flow\PluploadEndpoint\JsonResponseHandler;
use Flow\PluploadEndpoint\Pluploader;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;

$request = Request::createFromGlobals();

$filesystem = new Filesystem();

$pluploader = new Pluploader($request, $filesystem, './uploads');

$handler = new JsonResponseHandler($pluploader);

$response = $handler->handle(); // returns Symfony\Component\HttpFoundation\Response

$response->send(); // Sends JSON to browser
```

### Laravel integration
```php
class Uploads extends Controller
{
	public function upload()
	{
        $pluploader = new Pluploader(
            App::make('request'),
            new \Symfony\Component\Filesystem\Filesystem(),
            '../app/storage/uploads'
        );

		$handler = new JsonResponseHandler($pluploader);

		return $handler->handle();
	}
}
```

Caveats
=======
- Not tested for Windows/IIS environments
- This package has no security features however here are a few tips:
    - Check the file extensions of uploaded files and exclude all extensions you're not expecting (ie. *.php files)
    - Don't put the uploaded files in a publicly accessible directory (ie. in the public_html folder)
    - Obfuscate the file name on upload


text:
require_relative '../../helper_spec.rb'

describe 'consul UI' do
    ui_port = 8500

    describe port(ui_port) do
      it { should be_listening }
    end

    describe command "curl -s  http://127.0.0.1:#{ui_port}/ui/ | grep '<title>'" do
        its(:exit_status) { should eq 0 }
        its(:stdout) { should contain "<title>Consul by HashiCorp</title>" }
    end

end


text:
<html>
    <head>
        <script type="text/javascript" src="./src/core.js"></script>
        <script type='text/javascript'>
            var messagingServerTest = MessagingIO();
            messagingServerTest.start();
        </script>
    </head>
    <body>
    </body>
</html>


text:
package buildah

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"time"

	"github.com/containers/buildah/define"
	"github.com/containers/buildah/docker"
	"github.com/containers/image/v5/types"
	encconfig "github.com/containers/ocicrypt/config"
	"github.com/containers/storage"
	"github.com/containers/storage/pkg/ioutils"
	v1 "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
)

const (
	// Package is the name of this package, used in help output and to
	// identify working containers.
	Package = define.Package
	// Version for the Package.  Bump version in contrib/rpm/buildah.spec
	// too.
	Version = define.Version
	// The value we use to identify what type of information, currently a
	// serialized Builder structure, we are using as per-container state.
	// This should only be changed when we make incompatible changes to
	// that data structure, as it's used to distinguish containers which
	// are "ours" from ones that aren't.
	containerType = Package + " 0.0.1"
	// The file in the per-container directory which we use to store our
	// per-container state.  If it isn't there, then the container isn't
	// one of our build containers.
	stateFile = Package + ".json"
)

// PullPolicy takes the value PullIfMissing, PullAlways, PullIfNewer, or PullNever.
type PullPolicy = define.PullPolicy

const (
	// PullIfMissing is one of the values that BuilderOptions.PullPolicy
	// can take, signalling that the source image should be pulled from a
	// registry if a local copy of it is not already present.
	PullIfMissing = define.PullIfMissing
	// PullAlways is one of the values that BuilderOptions.PullPolicy can
	// take, signalling that a fresh, possibly updated, copy of the image
	// should be pulled from a registry before the build proceeds.
	PullAlways = define.PullAlways
	// PullIfNewer is one of the values that BuilderOptions.PullPolicy
	// can take, signalling that the source image should only be pulled
	// from a registry if a local copy is not already present or if a
	// newer version the image is present on the repository.
	PullIfNewer = define.PullIfNewer
	// PullNever is one of the values that BuilderOptions.PullPolicy can
	// take, signalling that the source image should not be pulled from a
	// registry if a local copy of it is not already present.
	PullNever = define.PullNever
)

// NetworkConfigurationPolicy takes the value NetworkDefault, NetworkDisabled,
// or NetworkEnabled.
type NetworkConfigurationPolicy = define.NetworkConfigurationPolicy

const (
	// NetworkDefault is one of the values that BuilderOptions.ConfigureNetwork
	// can take, signalling that the default behavior should be used.
	NetworkDefault = define.NetworkDefault
	// NetworkDisabled is one of the values that BuilderOptions.ConfigureNetwork
	// can take, signalling that network interfaces should NOT be configured for
	// newly-created network namespaces.
	NetworkDisabled = define.NetworkDisabled
	// NetworkEnabled is one of the values that BuilderOptions.ConfigureNetwork
	// can take, signalling that network interfaces should be configured for
	// newly-created network namespaces.
	NetworkEnabled = define.NetworkEnabled
)

// Builder objects are used to represent containers which are being used to
// build images.  They also carry potential updates which will be applied to
// the image's configuration when the container's contents are used to build an
// image.
type Builder struct {
	store storage.Store

	// Logger is the logrus logger to write log messages with
	Logger *logrus.Logger `json:"-"`

	// Args define variables that users can pass at build-time to the builder
	Args map[string]string
	// Type is used to help identify a build container's metadata.  It
	// should not be modified.
	Type string `json:"type"`
	// FromImage is the name of the source image which was used to create
	// the container, if one was used.  It should not be modified.
	FromImage string `json:"image,omitempty"`
	// FromImageID is the ID of the source image which was used to create
	// the container, if one was used.  It should not be modified.
	FromImageID string `json:"image-id"`
	// FromImageDigest is the digest of the source image which was used to
	// create the container, if one was used.  It should not be modified.
	FromImageDigest string `json:"image-digest"`
	// Config is the source image's configuration.  It should not be
	// modified.
	Config []byte `json:"config,omitempty"`
	// Manifest is the source image's manifest.  It should not be modified.
	Manifest []byte `json:"manifest,omitempty"`

	// Container is the name of the build container.  It should not be modified.
	Container string `json:"container-name,omitempty"`
	// ContainerID is the ID of the build container.  It should not be modified.
	ContainerID string `json:"container-id,omitempty"`
	// MountPoint is the last location where the container's root
	// filesystem was mounted.  It should not be modified.
	MountPoint string `json:"mountpoint,omitempty"`
	// ProcessLabel is the SELinux process label associated with the container
	ProcessLabel string `json:"process-label,omitempty"`
	// MountLabel is the SELinux mount label associated with the container
	MountLabel string `json:"mount-label,omitempty"`

	// ImageAnnotations is a set of key-value pairs which is stored in the
	// image's manifest.
	ImageAnnotations map[string]string `json:"annotations,omitempty"`
	// ImageCreatedBy is a description of how this container was built.
	ImageCreatedBy string `json:"created-by,omitempty"`
	// ImageHistoryComment is a description of how our added layers were built.
	ImageHistoryComment string `json:"history-comment,omitempty"`

	// Image metadata and runtime settings, in multiple formats.
	OCIv1  v1.Image       `json:"ociv1,omitempty"`
	Docker docker.V2Image `json:"docker,omitempty"`
	// DefaultMountsFilePath is the file path holding the mounts to be mounted in "host-path:container-path" format.
	DefaultMountsFilePath string `json:"defaultMountsFilePath,omitempty"`

	// Isolation controls how we handle "RUN" statements and the Run() method.
	Isolation define.Isolation
	// NamespaceOptions controls how we set up the namespaces for processes that we run in the container.
	NamespaceOptions define.NamespaceOptions
	// ConfigureNetwork controls whether or not network interfaces and
	// routing are configured for a new network namespace (i.e., when not
	// joining another's namespace and not just using the host's
	// namespace), effectively deciding whether or not the process has a
	// usable network.
	ConfigureNetwork define.NetworkConfigurationPolicy
	// CNIPluginPath is the location of CNI plugin helpers, if they should be
	// run from a location other than the default location.
	CNIPluginPath string
	// CNIConfigDir is the location of CNI configuration files, if the files in
	// the default configuration directory shouldn't be used.
	CNIConfigDir string
	// ID mapping options to use when running processes in the container with non-host user namespaces.
	IDMappingOptions define.IDMappingOptions
	// Capabilities is a list of capabilities to use when running commands in the container.
	Capabilities []string
	// PrependedEmptyLayers are history entries that we'll add to a
	// committed image, after any history items that we inherit from a base
	// image, but before the history item for the layer that we're
	// committing.
	PrependedEmptyLayers []v1.History
	// AppendedEmptyLayers are history entries that we'll add to a
	// committed image after the history item for the layer that we're
	// committing.
	AppendedEmptyLayers []v1.History
	CommonBuildOpts     *define.CommonBuildOptions
	// TopLayer is the top layer of the image
	TopLayer string
	// Format for the build Image
	Format string
	// TempVolumes are temporary mount points created during container runs
	TempVolumes map[string]bool
	// ContentDigester counts the digest of all Add()ed content
	ContentDigester CompositeDigester
	// Devices are the additional devices to add to the containers
	Devices define.ContainerDevices
}

// BuilderInfo are used as objects to display container information
type BuilderInfo struct {
	Type                  string
	FromImage             string
	FromImageID           string
	FromImageDigest       string
	Config                string
	Manifest              string
	Container             string
	ContainerID           string
	MountPoint            string
	ProcessLabel          string
	MountLabel            string
	ImageAnnotations      map[string]string
	ImageCreatedBy        string
	OCIv1                 v1.Image
	Docker                docker.V2Image
	DefaultMountsFilePath string
	Isolation             string
	NamespaceOptions      define.NamespaceOptions
	Capabilities          []string
	ConfigureNetwork      string
	CNIPluginPath         string
	CNIConfigDir          string
	IDMappingOptions      define.IDMappingOptions
	History               []v1.History
	Devices               define.ContainerDevices
}

// GetBuildInfo gets a pointer to a Builder object and returns a BuilderInfo object from it.
// This is used in the inspect command to display Manifest and Config as string and not []byte.
func GetBuildInfo(b *Builder) BuilderInfo {
	history := copyHistory(b.OCIv1.History)
	history = append(history, copyHistory(b.PrependedEmptyLayers)...)
	history = append(history, copyHistory(b.AppendedEmptyLayers)...)
	sort.Strings(b.Capabilities)
	return BuilderInfo{
		Type:                  b.Type,
		FromImage:             b.FromImage,
		FromImageID:           b.FromImageID,
		FromImageDigest:       b.FromImageDigest,
		Config:                string(b.Config),
		Manifest:              string(b.Manifest),
		Container:             b.Container,
		ContainerID:           b.ContainerID,
		MountPoint:            b.MountPoint,
		ProcessLabel:          b.ProcessLabel,
		MountLabel:            b.MountLabel,
		ImageAnnotations:      b.ImageAnnotations,
		ImageCreatedBy:        b.ImageCreatedBy,
		OCIv1:                 b.OCIv1,
		Docker:                b.Docker,
		DefaultMountsFilePath: b.DefaultMountsFilePath,
		Isolation:             b.Isolation.String(),
		NamespaceOptions:      b.NamespaceOptions,
		ConfigureNetwork:      fmt.Sprintf("%v", b.ConfigureNetwork),
		CNIPluginPath:         b.CNIPluginPath,
		CNIConfigDir:          b.CNIConfigDir,
		IDMappingOptions:      b.IDMappingOptions,
		Capabilities:          b.Capabilities,
		History:               history,
		Devices:               b.Devices,
	}
}

// CommonBuildOptions are resources that can be defined by flags for both buildah from and build
type CommonBuildOptions = define.CommonBuildOptions

// BuilderOptions are used to initialize a new Builder.
type BuilderOptions struct {
	// Args define variables that users can pass at build-time to the builder
	Args map[string]string
	// FromImage is the name of the image which should be used as the
	// starting point for the container.  It can be set to an empty value
	// or "scratch" to indicate that the container should not be based on
	// an image.
	FromImage string
	// Container is a desired name for the build container.
	Container string
	// PullPolicy decides whether or not we should pull the image that
	// we're using as a base image.  It should be PullIfMissing,
	// PullAlways, or PullNever.
	PullPolicy define.PullPolicy
	// Registry is a value which is prepended to the image's name, if it
	// needs to be pulled and the image name alone can not be resolved to a
	// reference to a source image.  No separator is implicitly added.
	Registry string
	// BlobDirectory is the name of a directory in which we'll attempt
	// to store copies of layer blobs that we pull down, if any.  It should
	// already exist.
	BlobDirectory string
	// Mount signals to NewBuilder() that the container should be mounted
	// immediately.
	Mount bool
	// SignaturePolicyPath specifies an override location for the signature
	// policy which should be used for verifying the new image as it is
	// being written.  Except in specific circumstances, no value should be
	// specified, indicating that the shared, system-wide default policy
	// should be used.
	SignaturePolicyPath string
	// ReportWriter is an io.Writer which will be used to log the reading
	// of the source image from a registry, if we end up pulling the image.
	ReportWriter io.Writer
	// github.com/containers/image/types SystemContext to hold credentials
	// and other authentication/authorization information.
	SystemContext *types.SystemContext
	// DefaultMountsFilePath is the file path holding the mounts to be
	// mounted in "host-path:container-path" format
	DefaultMountsFilePath string
	// Isolation controls how we handle "RUN" statements and the Run()
	// method.
	Isolation define.Isolation
	// NamespaceOptions controls how we set up namespaces for processes that
	// we might need to run using the container's root filesystem.
	NamespaceOptions define.NamespaceOptions
	// ConfigureNetwork controls whether or not network interfaces and
	// routing are configured for a new network namespace (i.e., when not
	// joining another's namespace and not just using the host's
	// namespace), effectively deciding whether or not the process has a
	// usable network.
	ConfigureNetwork define.NetworkConfigurationPolicy
	// CNIPluginPath is the location of CNI plugin helpers, if they should be
	// run from a location other than the default location.
	CNIPluginPath string
	// CNIConfigDir is the location of CNI configuration files, if the files in
	// the default configuration directory shouldn't be used.
	CNIConfigDir string
	// ID mapping options to use if we're setting up our own user namespace.
	IDMappingOptions *define.IDMappingOptions
	// Capabilities is a list of capabilities to use when
	// running commands in the container.
	Capabilities    []string
	CommonBuildOpts *define.CommonBuildOptions
	// Format for the container image
	Format string
	// Devices are the additional devices to add to the containers
	Devices define.ContainerDevices
	//DefaultEnv for containers
	DefaultEnv []string
	// MaxPullRetries is the maximum number of attempts we'll make to pull
	// any one image from the external registry if the first attempt fails.
	MaxPullRetries int
	// PullRetryDelay is how long to wait before retrying a pull attempt.
	PullRetryDelay time.Duration
	// OciDecryptConfig contains the config that can be used to decrypt an image if it is
	// encrypted if non-nil. If nil, it does not attempt to decrypt an image.
	OciDecryptConfig *encconfig.DecryptConfig
}

// ImportOptions are used to initialize a Builder from an existing container
// which was created elsewhere.
type ImportOptions struct {
	// Container is the name of the build container.
	Container string
	// SignaturePolicyPath specifies an override location for the signature
	// policy which should be used for verifying the new image as it is
	// being written.  Except in specific circumstances, no value should be
	// specified, indicating that the shared, system-wide default policy
	// should be used.
	SignaturePolicyPath string
}

// ImportFromImageOptions are used to initialize a Builder from an image.
type ImportFromImageOptions struct {
	// Image is the name or ID of the image we'd like to examine.
	Image string
	// SignaturePolicyPath specifies an override location for the signature
	// policy which should be used for verifying the new image as it is
	// being written.  Except in specific circumstances, no value should be
	// specified, indicating that the shared, system-wide default policy
	// should be used.
	SignaturePolicyPath string
	// github.com/containers/image/types SystemContext to hold information
	// about which registries we should check for completing image names
	// that don't include a domain portion.
	SystemContext *types.SystemContext
}

// NewBuilder creates a new build container.
func NewBuilder(ctx context.Context, store storage.Store, options BuilderOptions) (*Builder, error) {
	if options.CommonBuildOpts == nil {
		options.CommonBuildOpts = &CommonBuildOptions{}
	}
	return newBuilder(ctx, store, options)
}

// ImportBuilder creates a new build configuration using an already-present
// container.
func ImportBuilder(ctx context.Context, store storage.Store, options ImportOptions) (*Builder, error) {
	return importBuilder(ctx, store, options)
}

// ImportBuilderFromImage creates a new builder configuration using an image.
// The returned object can be modified and examined, but it can not be saved
// or committed because it is not associated with a working container.
func ImportBuilderFromImage(ctx context.Context, store storage.Store, options ImportFromImageOptions) (*Builder, error) {
	return importBuilderFromImage(ctx, store, options)
}

// OpenBuilder loads information about a build container given its name or ID.
func OpenBuilder(store storage.Store, container string) (*Builder, error) {
	cdir, err := store.ContainerDirectory(container)
	if err != nil {
		return nil, err
	}
	buildstate, err := ioutil.ReadFile(filepath.Join(cdir, stateFile))
	if err != nil {
		return nil, err
	}
	b := &Builder{}
	if err = json.Unmarshal(buildstate, &b); err != nil {
		return nil, errors.Wrapf(err, "error parsing %q, read from %q", string(buildstate), filepath.Join(cdir, stateFile))
	}
	if b.Type != containerType {
		return nil, errors.Errorf("container %q is not a %s container (is a %q container)", container, define.Package, b.Type)
	}
	b.store = store
	b.fixupConfig(nil)
	b.setupLogger()
	return b, nil
}

// OpenBuilderByPath loads information about a build container given a
// path to the container's root filesystem
func OpenBuilderByPath(store storage.Store, path string) (*Builder, error) {
	containers, err := store.Containers()
	if err != nil {
		return nil, err
	}
	abs, err := filepath.Abs(path)
	if err != nil {
		return nil, err
	}
	builderMatchesPath := func(b *Builder, path string) bool {
		return (b.MountPoint == path)
	}
	for _, container := range containers {
		cdir, err := store.ContainerDirectory(container.ID)
		if err != nil {
			return nil, err
		}
		buildstate, err := ioutil.ReadFile(filepath.Join(cdir, stateFile))
		if err != nil {
			if os.IsNotExist(err) {
				logrus.Debugf("error reading %q: %v, ignoring container %q", filepath.Join(cdir, stateFile), err, container.ID)
				continue
			}
			return nil, err
		}
		b := &Builder{}
		err = json.Unmarshal(buildstate, &b)
		if err == nil && b.Type == containerType && builderMatchesPath(b, abs) {
			b.store = store
			b.fixupConfig(nil)
			b.setupLogger()
			return b, nil
		}
		if err != nil {
			logrus.Debugf("error parsing %q, read from %q: %v", string(buildstate), filepath.Join(cdir, stateFile), err)
		} else if b.Type != containerType {
			logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, define.Package, b.Type)
		}
	}
	return nil, storage.ErrContainerUnknown
}

// OpenAllBuilders loads all containers which have a state file that we use in
// their data directory, typically so that they can be listed.
func OpenAllBuilders(store storage.Store) (builders []*Builder, err error) {
	containers, err := store.Containers()
	if err != nil {
		return nil, err
	}
	for _, container := range containers {
		cdir, err := store.ContainerDirectory(container.ID)
		if err != nil {
			return nil, err
		}
		buildstate, err := ioutil.ReadFile(filepath.Join(cdir, stateFile))
		if err != nil {
			if os.IsNotExist(err) {
				logrus.Debugf("error reading %q: %v, ignoring container %q", filepath.Join(cdir, stateFile), err, container.ID)
				continue
			}
			return nil, err
		}
		b := &Builder{}
		err = json.Unmarshal(buildstate, &b)
		if err == nil && b.Type == containerType {
			b.store = store
			b.setupLogger()
			b.fixupConfig(nil)
			builders = append(builders, b)
			continue
		}
		if err != nil {
			logrus.Debugf("error parsing %q, read from %q: %v", string(buildstate), filepath.Join(cdir, stateFile), err)
		} else if b.Type != containerType {
			logrus.Debugf("container %q is not a %s container (is a %q container)", container.ID, define.Package, b.Type)
		}
	}
	return builders, nil
}

// Save saves the builder's current state to the build container's metadata.
// This should not need to be called directly, as other methods of the Builder
// object take care of saving their state.
func (b *Builder) Save() error {
	buildstate, err := json.Marshal(b)
	if err != nil {
		return err
	}
	cdir, err := b.store.ContainerDirectory(b.ContainerID)
	if err != nil {
		return err
	}
	if err = ioutils.AtomicWriteFile(filepath.Join(cdir, stateFile), buildstate, 0600); err != nil {
		return errors.Wrapf(err, "error saving builder state to %q", filepath.Join(cdir, stateFile))
	}
	return nil
}


text:
"""This contians a layer that handles input processing."""

from flax import linen as nn
import jax.numpy as jnp

Array = jnp.ndarray

class CausalConv(nn.Conv):
  """A (possibly) causal (1D) convolution."""
  is_causal: bool = False

  def __call__(self, inputs):
    """Apply (causal) covolution to inputs."""

    kernel_size = tuple(self.kernel_size)
    def maybe_broadcast(x):  # Copied from Flax.
      if x is None:
        # Backward compatibility with using None as sentinel for
        # broadcast 1.
        x = 1
      if isinstance(x, int):
        return (x,) * len(kernel_size)
      return x

    inputs_shape = inputs.shape
    if self.is_causal:
      if self.padding != 'VALID':
        raise ValueError(
            'Padding must be set to VALID for causal convolutions.')
      if len(kernel_size) != 1:
        raise ValueError('Only 1D causal convolutions are supported.')

      # Pad inputs to simulate causality.
      kernel_dilation = maybe_broadcast(self.kernel_dilation)
      padding = kernel_dilation[0] * (kernel_size[0] - 1)
      inputs = jnp.pad(inputs, [(0, 0), (padding, 0), (0, 0)])

    outputs = super().__call__(inputs)
    if self.is_causal:
      outputs = outputs[:, :inputs_shape[1], :]
    return outputs


text:
<!DOCTYPE HTML>

<title>Uses of Class org.opensextant.extractors.geo.CountryCount (Xponents Extraction Toolkit)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
org.opensextant.extractors.geo.CountryCount

Packages that use CountryCount

Package
Description

org.opensextant.extractors.geo

Geo Extraction: PlaceGeocoder, SolrGazetteer, GazetteerMatcher
      and related items

Uses of CountryCount in org.opensextant.extractors.geo

Methods in org.opensextant.extractors.geo that return types with arguments of type CountryCount

Modifier and Type
Method
Description

java.util.Map<java.lang.String,CountryCount>
CountryObserver.countryMentionCount()

Calculates totals and ratios for the discovered set of countries.

java.util.Map<java.lang.String,CountryCount>
PlaceGeocoder.countryMentionCount()

Calculate country mention totals and ratios.

java.util.Map<java.lang.String,CountryCount>
PostalGeocoder.countryMentionCount()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

Copyright © 2013–2022. All rights reserved.


text:
Magically editable settings for winged pony lovers.

## Why?

Because sometimes it's cool to set global configuration values through a nice
interface on the Django admin. And that's what SetMagic make possible. Enjoy!

## Install and set up

Install it into your project's virtual environment:

	$ pip install django-setmagic

Make sure you already have the [Django admin][1] set up! Then append to your
Django project's `INSTALLED_APPS` setting.

	INSTALLED_APPS = [
		...
		'django.contrib.admin',
		'setmagic',
		...
	]

Also enable the SetMagic template context processor, if you want to use it on
your templates, by adding it to the `TEMPLATE_CONTEXT_PROCESSORS` list:

	TEMPLATE_CONTEXT_PROCESSORS = [
		...
		'setmagic.context_processors.load_setmagic',
	]

Create the necessary tables, like usual:

	$ python manage.py syncdb

...and that's pretty much it. :)

## Usage

SetMagic will look into your project's settings for the name `SETMAGIC_SCHEMA`.
It should be defined as a pure Python list of groups like the example below:

	SETMAGIC_SCHEMA = [
	    ('Facebook App Credentials', [
	        dict(
	            name='FACEBOOK_APP_ID',
	            label=u'Facebook app ID',
	            help_text=u'Unique app identification code provided by Facebook.'),
	        dict(
	            name='FACEBOOK_APP_SECRET',
	            label=u'Facebook API secret',
	            help_text=u'Unique and secret API code provided by Facebook.'),
	    ]),
	    ('Tracking', [
	        dict(
	            name='GOOGLE_ANALYTICS_CODE',
	            label=u'Google Analytics code',
	            help_text=u'Domain to identify this site through the GA API.'),
	    ]),
	]

From now on, you should be able to set values for your configurations through
the Django admin. And you will, of course, be able to set and retrieve these
values on your code.

	from setmagic import settings

	# Instantly save onto the database!
	settings.FACEBOOK_APP_ID = '000000000000000'

	# Retrieve the setting value from the database
	print(settings.FACEBOOK_APP_ID)

	# Deletes it from the database
	del settings.FACEBOOK_APP_ID

If you added the template context processor like described above, you can also
use SetMagic values on your templates.

My Facebook app ID is {{ setmagic.FACEBOOK_APP_ID }}

See? No mistery. :)

## Platform support

	* Python 2.6+
	* Python 3.x
	* Django 1.5+

## Contribute

You can play with the code at SetMagic's reposity on [GitHub][2] or [donate][3]
me a few bucks from heart so I can write open source code without worrying too
much about bills.

[1]: https://docs.djangoproject.com/en/dev/ref/contrib/admin/
[2]: http://github.com/7ws/django-setmagic
[3]: https://gratipay.com/emyller/


text:
package com.algocrafts.chapter4;

import org.openqa.selenium.By;

public class ByConstants {

    public static final By QUANTITY = By.name("cartDS.shoppingcart_ROW0_m_orderItemVector_ROW0_m_quantity");

    public static final By SF_JS_ENABLED = By.className("sf-js-enabled");
    public static final By TOOLS_LOCATION = By.className("tools-location");

    public static final By UI_DATEPICKER_CALENDAR = By.className("ui-datepicker-calendar");
    public static final By UI_DATEPICKER_NEXT = By.className("ui-datepicker-next");
    public static final By UI_DATEPICKER_PREV = By.className("ui-datepicker-prev");
    public static final By UI_DATEPICKER_MONTH = By.className("ui-datepicker-month");
    public static final By UI_DATEPICKER_YEAR = By.className("ui-datepicker-year");
    public static final By UI_DATEPICKER_HEADER = By.className("ui-datepicker-header");
    public static final By PAGE_TITLE = By.className("page-title");
    public static final By UI_DATEPICKER_CLOSE = By.className("ui-datepicker-close");

    public static final By UPDATE = By.cssSelector("input[value='Update']");
    public static final By CONTINUE = By.cssSelector("input[value='Continue']");
    public static final By NEED_CONIRM = By.cssSelector("input[value='Need Confirm']");
    public static final By SUBMIT = By.cssSelector("input[type='Submit']");

    public static final By LOCATION = By.id("location");
    public static final By MAIN = By.id("main");
    public static final By MAIN_NAV = By.id("main-nav");
    public static final By UI_DATEPICKER_DIV = By.id("ui-datepicker-div");
    public static final By CONTENT = By.id("content");
    public static final By EXTJS_DATEPICKER_TRIGGER = By.id("menuitem-1017-textEl");
    public static final By EXTJS_CALENDAR = By.id("datemenu-1014");
    public static final By EXTJS_CALENDAR_MONTH_YEAR = By.id("splitbutton-1020-btnInnerEl");
    public static final By EXTJS_CALENDAR_PREV_MONTH = By.id("datepicker-1015-prevEl");
    public static final By EXTJS_CALENDAR_NEXT_MONTH = By.id("datepicker-1015-nextEl");
    public static final By DATE_PICKER = By.id("datepicker");
}


text:
from pyrseas.relation import Attribute, RelVar
from pyrseas.relation import ProjAttribute, Projection, JoinRelation

def film_repr(tup):
    return "%s - %d" % (tup.title, tup.release_year)

Film_RV = RelVar('film', [
    Attribute('id', int),
    Attribute('title'),
    Attribute('release_year', int)],
    key=['id'])

Film_List = JoinRelation([
    Projection('film',
               [ProjAttribute('id', int),
                ProjAttribute('title'),
                ProjAttribute('release_year', int)])])


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using U2PhoneApp.U2_CodeFirst_oData_Service;
using System.Data.Services.Client;

namespace U2PhoneApp
{
    public class MyModel
    {
        public string Title { get; set; }
        public string Rating { get; set; }
    }
    public partial class EDM_Details_Page : PhoneApplicationPage
    {
        // Declare the data service objects and URIs.
        private ProductContext context;
        private readonly Uri northwindUri =
            new Uri("http://9.72.199.235/U2_oData/U2_CodeFirst_oData_WcfDataService.svc/");
        private DataServiceCollection<Product> products;

        public EDM_Details_Page()
        {
            InitializeComponent();
            //List<MyModel> lList = new List<MyModel>();
            //MyModel l = new MyModel();
            //l.Title = "aaa";
            //l.Rating = "R";
            //lList.Add(l);

            //this.MainLongListSelector.ItemsSource = lList;

        }

        private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void CodeFirst_Page_Loaded(object sender, RoutedEventArgs e)
        {
            // Initialize the context and the binding collection
            context = new ProductContext(northwindUri);

            products = new DataServiceCollection<Product>(context);

            context.Products.AddQueryOption("$top", 10);

            // Define a LINQ query that returns all customers.
            var query = from cust in context.Products
                        //where cust.ProductId == 2761685473
                        select cust;

            var query2 = context.Products.Take(10);

            // Register for the LoadCompleted event.
            products.LoadCompleted
                += new EventHandler<LoadCompletedEventArgs>(products_LoadCompleted);

            // Load the customers feed by executing the LINQ query.
            products.LoadAsync(query);

        }

        void products_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Handling for a paged data feed.
                if (products.Continuation != null)
                {
                    // Automatically load the next page.
                    products.LoadNextPartialSetAsync();
                }
                else
                {
                    // Set the data context of the list box control to the sample data.
                    //this.MainLongListSelector.DataContext = products;
                    this.MainLongListSelector.ItemsSource = products;
                }
            }
            else
            {
                MessageBox.Show(string.Format("An error has occurred: {0}", e.Error.Message));
            }
        }

    }
}


text:
//
//  KxTarArchiveReader.m
//  https://github.com/kolyvan/kybookfmt
//
//  Created by Konstantin Bukreev on 05.02.16.
//  Copyright © 2016 Konstantin Bukreev. All rights reserved.
//

#import "KxTarArchiveReader.h"
#import "archive.h"
#import "archive_entry.h"

static NSString *const KxTarArchiveReaderDomain = @"com.kolyvan.tar.reader";

@interface KxTarArchiveReaderEntry()
@property (readwrite, nonatomic, strong) NSString *path;
@property (readwrite, nonatomic) int64_t offset;
@property (readwrite, nonatomic) int64_t size;
@property (readwrite, nonatomic, strong) NSData *content;
@end

@implementation KxTarArchiveReaderEntry
@end

@implementation KxTarArchiveReader

+ (NSArray *) entriesWithPath:(NSString *)path
                  withContent:(BOOL)withContent
                        error:(NSError **)error
{
    struct archive *archive = [self openArchive:path error:error];
    if (!archive) {
        return nil;
    }

    NSArray *entries = [self entriesWithArchive:archive withContent:withContent error:error];
    [self closeArchive:archive];
    return entries;
}

+ (NSArray *) entriesWithArchive:(struct archive *)archive
                     withContent:(BOOL)withContent
                           error:(NSError **)error
{
    NSMutableArray *result = [NSMutableArray array];

    struct archive_entry *entry;

    while (1) {

        const int r = archive_read_next_header(archive, &entry);
        if (r == ARCHIVE_EOF) {

            break; // ok, eof

        } else if (r == ARCHIVE_OK) {

            if (S_ISREG(archive_entry_mode(entry))) {

                const char *path = archive_entry_pathname(entry);
                if (path) {

                    NSString *nspath = [NSString stringWithUTF8String:path];
                    if (nspath) {

                        KxTarArchiveReaderEntry *p = [KxTarArchiveReaderEntry new];

                        p.path = nspath;
                        p.size = archive_entry_size(entry);

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                        p.offset = archive_position_uncompressed(archive);
#pragma clang diagnostic pop

                        if (withContent) {
                            p.content = [self readContent:archive];
                        }

                        [result addObject:p];
                    }
                }
            }

        } else {

            if (error) {
                *error = [self errorWithCode:KxTarArchiveReaderErrorNext archive:archive message:nil];
            }
            break;
        }
    }

    return [result copy];
}

+ (NSData *) readContent:(struct archive *)archive
{
    NSMutableData *data;

    while (1) {

        const void *buff = NULL;
        off_t offset = 0;
        size_t size = 0;

        const int r = archive_read_data_block(archive, &buff, &size, &offset);

        if (r == ARCHIVE_EOF) {
            break;
        }

        if (r == ARCHIVE_OK) {

            if (size > 0) {

                if (!data) {
                    data = [NSMutableData new];
                }
                [data appendBytes:buff length:size];
            }

        } else {

            return nil;
        }
    }

    return data;
}

+ (NSData *) contentOfEntry:(NSString *)entryPath
                   filePath:(NSString *)filePath
                      error:(NSError **)error
{
    if (!entryPath.length) {
        if (error) {
            *error = [self errorWithCode:KxTarArchiveReaderErrorEntry
                                 archive:nil
                                 message:NSLocalizedString(@"Bad Entry", nil)];
        }
        return nil;
    }

    struct archive *archive = [self openArchive:filePath error:error];
    if (!archive) {
        return nil;
    }

    NSData *content = [self contentOfEntry:entryPath
                                   archive:archive
                                     error:error];
    [self closeArchive:archive];
    return content;
}

+ (NSData *) contentOfEntry:(NSString *)entryPath
                    archive:(struct archive *)archive
                      error:(NSError **)error
{
    struct archive_entry *entry;

    while (1) {

        const int r = archive_read_next_header(archive, &entry);
        if (r == ARCHIVE_EOF) {

            break;

        } else if (r == ARCHIVE_OK) {

            if (S_ISREG(archive_entry_mode(entry))) {

                const char *path = archive_entry_pathname(entry);
                if (path) {

                    NSString *nspath = [NSString stringWithUTF8String:path];
                    if (nspath && [nspath isEqualToString:entryPath]) {
                        return [self readContent:archive];
                    }
                }
            }

        } else {

            if (error) {
                *error = [self errorWithCode:KxTarArchiveReaderErrorNext archive:archive message:nil];
            }
            return nil;
        }
    }

    if (error) {
        *error = [self errorWithCode:KxTarArchiveReaderErrorNotFound
                             archive:nil
                             message:NSLocalizedString(@"Not Found", nil)];
    }

    return nil;
}

+ (KxTarArchiveReaderEntry *) entry:(NSString *)entryPath
                           filePath:(NSString *)filePath
                        withContent:(BOOL)withContent
                              error:(NSError **)error
{
    if (!entryPath.length) {
        if (error) {
            *error = [self errorWithCode:KxTarArchiveReaderErrorEntry
                                 archive:nil
                                 message:NSLocalizedString(@"Bad Entry", nil)];
        }
        return nil;
    }

    struct archive *archive = [self openArchive:filePath error:error];
    if (!archive) {
        return nil;
    }

    KxTarArchiveReaderEntry *entry = [self entry:entryPath
                                         archive:archive
                                     withContent:withContent
                                           error:error];

    [self closeArchive:archive];
    return entry;
}

+ (KxTarArchiveReaderEntry *) entry:(NSString *)entryPath
                            archive:(struct archive *)archive
                        withContent:(BOOL)withContent
                              error:(NSError **)error
{
    struct archive_entry *entry;

    while (1) {

        const int r = archive_read_next_header(archive, &entry);
        if (r == ARCHIVE_EOF) {

            break;

        } else if (r == ARCHIVE_OK) {

            if (S_ISREG(archive_entry_mode(entry))) {

                const char *path = archive_entry_pathname(entry);
                if (path) {

                    NSString *nspath = [NSString stringWithUTF8String:path];
                    if (nspath && [nspath isEqualToString:entryPath]) {

                        KxTarArchiveReaderEntry *p = [KxTarArchiveReaderEntry new];

                        p.path = nspath;
                        p.size = archive_entry_size(entry);

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                        p.offset = archive_position_uncompressed(archive);
#pragma clang diagnostic pop

                        if (withContent) {
                            p.content = [self readContent:archive];
                        }

                        return p;
                    }
                }
            }

        } else {

            if (error) {
                *error = [self errorWithCode:KxTarArchiveReaderErrorNext archive:archive message:nil];
            }
            return nil;
        }
    }

    if (error) {
        *error = [self errorWithCode:KxTarArchiveReaderErrorNotFound
                             archive:nil
                             message:NSLocalizedString(@"Not Found", nil)];
    }

    return nil;
}

+ (struct archive *) openArchive:(NSString *)path
                           error:(NSError **)error
{
    if (!path.length) {
        if (error) {
            *error = [self errorWithCode:KxTarArchiveReaderErrorPath
                                 archive:NULL
                                 message:NSLocalizedString(@"Bad Path", nil)];
        }
        return NULL;
    }

    struct archive *archive = archive_read_new();
    if (!archive) {
        if (error) {
            *error = [self errorWithCode:KxTarArchiveReaderErrorInternal archive:NULL message:nil];
        }
        return NULL;
    }

    archive_read_support_format_tar(archive);

    const int r = archive_read_open_filename(archive, path.UTF8String, 10240);

    if (r != ARCHIVE_OK) {
        if (error) {
            *error = [self errorWithCode:KxTarArchiveReaderErrorOpen archive:archive message:nil];
        }
        [self closeArchive:archive];
        return NULL;
    }

    return archive;
}

+ (void) closeArchive:(struct archive *)archive
{
    archive_read_close(archive);

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    archive_read_finish(archive);
#pragma clang diagnostic pop
}

+ (NSError *) errorWithCode:(KxTarArchiveReaderError)code
                    archive:(struct archive *)archive
                    message:(NSString *)message
{
    NSString *errString;

    if (archive) {
        const char *str = archive_error_string(archive);
        if (str && strlen(str) > 0) {
            errString = [NSString stringWithUTF8String:str];
        }
    }

    if (!errString) {
        errString = message ?: NSLocalizedString(@"ERROR", nil);
    }

    if (archive) {
        const int errNo = archive_errno(archive);
        if (errNo) {
            errString = [errString stringByAppendingFormat:@" #%d", errNo];
        }
    }

    return [NSError errorWithDomain:KxTarArchiveReaderDomain
                               code:code
                           userInfo:@{ NSLocalizedDescriptionKey : errString }];
}

+ (nullable NSData *) dataWithURL:(NSURL *)URL
                            error:(NSError **)error
{
    return [self dataWithURL:URL range:NSMakeRange(NSNotFound, 0) entrySize:NULL error:error];
}

+ (NSData *) dataWithURL:(NSURL *)URL
                   range:(NSRange)range
               entrySize:(NSUInteger *)entrySize
                   error:(NSError **)error
{
    NSString *entryName = URL.query.stringByRemovingPercentEncoding;
    NSString *filePath = URL.path;

    if (range.location != NSNotFound && range.length > 0) {

        KxTarArchiveReaderEntry *entry;
        entry = [KxTarArchiveReader entry:entryName
                                 filePath:filePath
                              withContent:NO
                                    error:error];
        if (!entry) {
            return nil;
        }

        if (entrySize) {
            *entrySize = (NSUInteger)entry.size;
        }

        return [self dataWithPath:filePath
                            entry:entry
                            range:range
                            error:error];
    } else {

        NSData *data = [KxTarArchiveReader contentOfEntry:entryName
                                                 filePath:filePath
                                                    error:error];
        if (data && entrySize) {
            *entrySize = data.length;
        }

        return data;
    }
}

+ (NSData *) dataWithPath:(NSString *)filePath
                    entry:(KxTarArchiveReaderEntry *)entry
                    range:(NSRange)range
                   error:(NSError **)error
{
    NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:filePath];
    if (!fh) {
        return nil;
    }

    NSData *data;
    NSInteger length, offset;

    if (range.location == NSNotFound ||
        (range.location == 0 && range.length == entry.size)) {

        offset = (NSInteger)entry.offset;
        length = (NSInteger)entry.size;

    } else {

        if (NSMaxRange(range) > entry.size) {
            length = (NSInteger)(entry.size - range.location);
        } else {
            length = range.length;
        }

        if (length <= 0) {
            return  nil; // EOF
        }

        offset = (NSInteger)(entry.offset + range.location);
    }

    [fh seekToFileOffset:offset];
    data = [fh readDataOfLength:length];
    [fh closeFile];

    return data;
}

+ (NSData *) dataWithPath:(NSString *)filePath
                entryPath:(NSString *)entryPath
                    range:(NSRange)range
                    error:(NSError **)error
{
    NSURLComponents *components = [NSURLComponents new];
    components.scheme = @"file";
    components.path = filePath;
    components.query = entryPath;

    return [self dataWithURL:components.URL
                       range:range
                   entrySize:NULL
                       error:error];
}

+ (NSData *) dataWithPath:(NSString *)filePath
                entryPath:(NSString *)entryPath
                    error:(NSError **)error
{
    return [self dataWithPath:filePath
                    entryPath:entryPath
                        range:NSMakeRange(NSNotFound, 0)
                        error:error];
}

@end


text:
namespace nonstd
{
	template <typename Enumeration>
	inline
	constexpr
	typename std::underlying_type<Enumeration>::type as_integer(const Enumeration value)
	{
		return static_cast<typename std::underlying_type<Enumeration>::type>(value);
	}

	inline
	bool file_is_readable(const std::string& filePath)
	{
		return std::ifstream(filePath.c_str()).good();
	}

	inline
	std::string directory_name(const std::string& filename)
	{
		size_t pos = filename.find_last_of("\\/");
		return (pos == std::string::npos) ? "" : filename.substr(0, pos);
	}

	inline
	std::string trim_whitespace(const std::string& string)
	{
		if (string.length() <= 0)
		{
			return "";
		}

		size_t first = string.find_first_not_of(' ');
		size_t last = string.find_last_not_of(' ');
		return string.substr(first, (last - first + 1));
	}
}


text:
package abd.pr1.seguidoresSeries;

import java.util.Iterator;
import java.util.List;

import javax.sql.DataSource;

import abd.pr1.mappers.ActorMapper;
import abd.pr1.mappers.ActuacionMapper;
import abd.pr1.mappers.EpisodioMapper;
import abd.pr1.mappers.PersonajeMapper;
import abd.pr1.mappers.SerieMapper;
import abd.pr1.observables.ActuaObserver;
import abd.pr1.observables.Observable;
import abd.pr1.tiposDeDatos.Actor;
import abd.pr1.tiposDeDatos.Actuacion;
import abd.pr1.tiposDeDatos.Episodio;
import abd.pr1.tiposDeDatos.Personaje;
import abd.pr1.tiposDeDatos.Serie;

public class GestionActuar extends Observable<ActuaObserver>{

	private DataSource ds;

	public GestionActuar(DataSource ds) {
		this.ds = ds;
	}

	public void datosActua(String nombreActor) {
		ActorMapper actorMapper = new ActorMapper(ds);
		Actor actor = actorMapper.buscarUnActor(nombreActor);
		ActuacionMapper actuacionMapper = new ActuacionMapper(ds);

		List<Actuacion> actuaciones = actuacionMapper.buscarActuaciones(actor.getNif());
		if(!actuaciones.isEmpty()) {

			EpisodioMapper episodioMapper = new EpisodioMapper(ds);
			Episodio episodio;

			PersonajeMapper personajeMapper = new PersonajeMapper(ds);
			Personaje personaje;

			SerieMapper serieMapper = new SerieMapper(ds);
			Serie serie;

			Actuacion actuacion;

			Iterator<Actuacion> it = actuaciones.iterator();
			while(it.hasNext()) {
				actuacion = it.next();
				episodio = episodioMapper.findById(actuacion.getIdEpisodio());
				serie = serieMapper.findById( episodio.getIdSerie());
				personaje = personajeMapper.findById(actuacion.getIdPersonaje());
				avisarDatosActua(serie.getNombre(), episodio.getTitulo(), personaje.getNombre());
			}

		}

	}

	private void avisarDatosActua(String nombreSerie, String nombreEpisodio, String personaje) {
		Iterator<ActuaObserver> it = super.iterator();
		while(it.hasNext()) {
			it.next().datosActua(nombreSerie, nombreEpisodio, personaje);
		}
	}

}


text:
<?php

namespace Pakettikauppa;

class Client
{
    /**
     * @var array|null
     */
    private $configs            = null;

    /**
     * @var string|null
     */
    private $api_key            = null;
    /**
     * @var string|null
     */
    private $secret             = null;
    /**
     * @var string|null
     */
    private $base_uri           = null;
    /**
     * @var string
     */
    private $user_agent         = 'pk-client-lib/2.0';
    /**
     * @var null
     */
    private $comment            = null;
    /**
     * @var null
     */
    private $response           = null;

    /**
     * @var null
     */
    private $use_posti_auth     = null;
    /**
     * @var null
     */
    private $posti_auth_url     = null;
    /**
     * @var null
     */
    private $access_token       = null;

    public $http_response_code;
    public $http_error;
    public $http_response;
    public $http_request;

    /** @var \Closure null */
    private $logClosure = null;
    const LOG_LEVEL_ERROR = 1;
    const LOG_LEVEL_DEBUG = 10;

    /**
     * Client constructor.
     *
     * ```php
     *      $client = new Client(array('test_mode' => true)); // Test mode
     *
     *      $client = new Client(array('api_key' => '123ABC...', 'secret' => 'ABC321...')); // Production mode
     *
     *      $client = new Client(array(
     *              'test_config' => array('api_key' => '123ABC...', 'secret' => 'ABC321...', 'base_uri' => 'https://testserver'),
     *              'staging_config' => array('api_key' => '123ABC...', 'secret' => 'ABC321...', 'base_uri' => 'https://apitest.pakettikauppa.fi'),
     *          ),
     *          'test_config'
     *      );
     *
     *      $client = new Client(array(
     *              'posti_configs' => array(
     *                  'use_posti_auth' => true    // Changes authentication method to Posti OAuth 2.0 token
     *                  'api_key' => 'ABC123',      // Posti OAuth username
     *                  'secret' => 'ABC321...',    // Posti OAuth secret
     *                  'base_uri' => ''            // Url to Posti server
     *                  'posti_auth_url' => ''      // Url to Posti OAuth server
     *              )
     *          ),
     *          'posti_configs'
     *      );
     * ```
     *
     * @param array $configs Accepted params are api_key, secret & base_uri.
     * @param string $use_config If configs contains more then one possible configuration, $use_config defines which to use
     * @throws \Exception
     */
    public function __construct(array $configs = null, $use_config = null)
    {
        $this->configs = $configs;

        if( (isset($configs['test_mode']) and $configs['test_mode'] === true) or empty($configs))
        {
            $this->api_key      = '00000000-0000-0000-0000-000000000000';
            $this->secret       = '1234567890ABCDEF';
            $this->base_uri     = 'https://apitest.pakettikauppa.fi';
        }
        else
        {

            if(isset($configs['api_key'])) {
                $this->api_key  = $configs['api_key'];
            }

            if(isset($configs['secret'])) {
                $this->secret   = $configs['secret'];
            }

            if(isset($configs['base_uri'])) {
                $this->base_uri = $configs['base_uri'];
            } else {
                $this->base_uri = 'https://api.pakettikauppa.fi';
            }
        }

        if($use_config and isset($configs[$use_config]))
        {
            if(isset($this->configs[$use_config]))
            {
                foreach ($this->configs[$use_config] as $key => $value) {
                    if(property_exists($this, $key)) {
                        $this->{$key} = $value;
                    }
                }
            }
        }
    }

    /**
     * Fetches access token from Posti authentication service, if class param $posti_auth_url is not defined
     * in constructor uses test server. Cache the result until it expires.
     *
     * @see https://api.posti.fi/api-authentication.html
     * @return array
     */
    public function getToken()
    {
        if(empty($this->posti_auth_url)) {
            $this->posti_auth_url = 'https://oauth.barium.posti.com';
        }

        return json_decode($this->getPostiToken($this->posti_auth_url ."/oauth/token?grant_type=client_credentials", $this->api_key, $this->secret));
    }

    /**
     * Set the access token
     *
     * @param string $access_token
     */
    public function setAccessToken($access_token)
    {
        $this->access_token = $access_token;
    }

    /**
     * Sets comment for the request. You can set there information for Pakettikauppa. Like
     * "Generated from Foobar platform"
     *
     * @param string $comment
     */
    public function setComment($comment) {
        $this->comment = $comment;
    }
    /**
     * Posts shipment data to Pakettikauppa, if request was successful
     * sets $reference and $tracking_code params to given shipment.
     *
     * @param Shipment $shipment
     * @return string
     * @throws \Exception
     */
    public function createTrackingCode(Shipment &$shipment, $language = "fi")
    {
        return $this->createShipment($shipment, false, $language);
    }

    /**
     * @param Shipment $shipment
     * @param bool     $draft
     *
     * @throws \Exception
     */
    private function createShipment(Shipment &$shipment, $draft = false, $language = "fi")
    {
        if($draft) {
            throw new \Exception("Creating draft shipment is deprecated");
        }

        $id             = str_replace('.', '', microtime(true));
        $shipment_xml   = $shipment->asSimpleXml();

        $shipment_xml->{"ROUTING"}->{"Routing.Id"}          = $id;

        if($this->use_posti_auth === true)
        {
            if(empty($this->access_token)) {
                throw new \Exception("Access token must be set");

            }

            $shipment_xml->{"ROUTING"}->{"Routing.Token"}       = $this->access_token;
        } else {
            $shipment_xml->{"ROUTING"}->{"Routing.Account"}     = $this->api_key;
            $shipment_xml->{"ROUTING"}->{"Routing.Version"}     = 2;
            $shipment_xml->{"ROUTING"}->{"Routing.Key"}         = hash_hmac('sha256',"{$this->api_key}{$id}", $this->secret);
        }

        if($this->comment != null) {
            $shipment_xml->{"ROUTING"}->{"Routing.Comment"} = $this->comment;
        }

        $response = $this->doPost("/prinetti/create-shipment?lang={$language}", null, $shipment_xml->asXML());

        $response_xml = simplexml_load_string($response);

        if(!$response_xml) {
            throw new \Exception("Failed to load response xml: " .var_export($response, true));
        }

        $this->response = $response_xml;

        if($response_xml->{'response.status'} != 0) {
            throw new \Exception("Error: {$response_xml->{'response.status'}}, {$response_xml->{'response.message'}}");
        }

        $response_xml = $this->response;

        $shipment->setReference($response_xml->{'response.reference'});
        $shipment->setTrackingCode($response_xml->{'response.trackingcode'});

        return $response_xml->{'response.trackingcode'};
    }

    /**
     * Returns latest response as XML
     *
     * @return \SimpleXMLElement
     */
    public function getResponse() {
        return $this->response;
    }

    /**a
     * Fetches the shipping label pdf for a given Shipment and
     * saves it as base64 encoded string to $pdf parameter on the Shipment.
     * The shipment must have $tracking_code and $reference set.
     *
     * @param Shipment $shipment
     * @return string
     * @throws \Exception
     */
    public function fetchShippingLabel(Shipment &$shipment, $size = null, $labels_count = null, $cn23_count = null)
    {
        $response_xml = $this->fetchShippingLabels(array($shipment->getTrackingCode()), $size , $labels_count, $cn23_count);

        $shipment->setPdf($response_xml->{'response.file'});

        return $response_xml->{'response.file'};
    }

    /**
     * Fetches the shipping labels in one pdf for a given tracking_codes and
     * saves it as base64 encoded string inside XML.
     *
     * @param array $trackingCodes
     * @return xml
     * @throws \Exception
     */
    public function fetchShippingLabels($trackingCodes, $size = null, $labels_count = null, $cn23_count = null)
    {
        $id     = str_replace('.', '', microtime(true));
        $xml    = new \SimpleXMLElement('<eChannel/>');

        $routing = $xml->addChild('ROUTING');

        $routing->addChild('Routing.Id', $id);

        if($this->use_posti_auth === true) {
            if(empty($this->access_token)) {
                throw new \Exception("Access token must be set");
            }

            $routing->addChild('Routing.Token', $this->access_token);
        } else {
            $routing->addChild('Routing.Account', $this->api_key);
            $routing->addChild("Routing.Version", 2);
            $routing->addChild("Routing.Key", hash_hmac('sha256',"{$this->api_key}{$id}", $this->secret));
        }

        $label = $xml->addChild('PrintLabel');
        $label['responseFormat'] = 'File';

        if ($size && in_array($size, ['A5', '107x225'])) {
            $label['size'] = $size;
        }

        $rules = array();
        if ($labels_count !== null) {
            $rules[] = "label:{$labels_count}";
        }
        if ($cn23_count !== null) {
            $rules[] = "cn23:{$cn23_count}";
        }
        if (!empty($rules)) {
            $label['rules'] = implode('%', $rules);
        }

        if (!is_array($trackingCodes)) {
            $trackingCodes = [$trackingCodes];
        }
        foreach($trackingCodes as $trackingCode) {
            $label->addChild('TrackingCode', $trackingCode);
        }

        $response = $this->doPost('/prinetti/get-shipping-label', null, $xml->asXML());

        $response_xml = simplexml_load_string($response);

        if(!$response_xml) {
            throw new \Exception("Failed to load response xml: " . var_export($response, true));
        }

        $this->response = $response_xml;

        if($response_xml->{'response.status'} != 0) {
            throw new \Exception("Error: {$response_xml->{'response.status'}}, {$response_xml->{'response.message'}}");
        }

        return $response_xml;
    }
    /**
     *  Fetches a cost estimation for a shipment from Pakettikauppa.
     *  To get an estimation for a parcel the shipment must have shipping
     *  method set and at least 1 parcel with weight. When estimating cargo sender
     *  and receiver info should also be set.
     *
     *
     */
    public function estimateShippingCost(Shipment &$shipment)
    {
        $sender                 = $shipment->getSender();
        $receiver               = $shipment->getReceiver();
        $parcels                = $shipment->getParcels();
        $additional_services    = $shipment->getAdditionalServices();

        $shipment_data = array(
            'sender' => array(
                'postcode'  => $sender->getPostcode(),
                'country'   => $sender->getCountry(),
            ),
            'receiver' => array(
                'postcode'  => $receiver->getPostcode(),
                'country'   => $receiver->getCountry(),
            ),

            'product_code'          => $shipment->getShippingMethod(),
            'parcels'               => array(),
            'additional_services'   => array()
        );

        foreach ($parcels as $parcel)
        {
            $shipment_data['parcels'][] = array(
                'weight'    => $parcel->getWeight(),
                'volume'    => $parcel->getVolume(),
                'type'      => $parcel->getPackageType(),
                'x_dimension' => $parcel->getX(),
                'y_dimension' => $parcel->getY(),
                'z_dimension' => $parcel->getZ(),
            );
        }

        foreach ($additional_services as $service)
        {
            $shipment_data['additional_services'][] = $service->getServiceCode();
        }

        $response =  $this->doPost('/shipment/estimate-price', ['shipment' => json_encode($shipment_data)]);

        return json_decode($response);
    }

    /**
     * @param $tracking_code
     * @return array
     * @param string $lang
     * @return mixed
     */
    public function getShipmentStatus($tracking_code, $lang = 'fi')
    {
        return json_decode($this->doPost('/shipment/status', array('tracking_code' => $tracking_code, 'language' => $lang)));
    }

    /**
     * @return array
     */
    public function listAdditionalServices()
    {
        return json_decode($this->doPost('/additional-services/list', array()));
    }

    /**
     * @param $postcode
     *
     * @return bool|string
     */
    public function findCityByPostcode($postcode, $country) {
        return json_decode($this->doPost('/info/find-city', array('postcode' => $postcode, 'country' => $country)));
    }

    /**
     * @return array
     */
    public function listShippingMethods()
    {
        return json_decode($this->doPost('/shipping-methods/list', array()));
    }

    /**
     * Search pickup points.
     *
     * @param int $postcode
     * @param string $street_address
     * @param string $country
     * @param string $service_provider Limits results for to certain providers possible values are packet service codes (like 2103 for Postipaketti. Use listShippingMethods to get service codes).
     * @param int $limit 1 - 15
     * @param string $type PRIVATE_LOCKER, PICKUP_POINT, PARCEL_LOCKER, OUTDOOR_LOCKER, AGENCY
     * @return array
     */
    public function searchPickupPoints($postcode = null, $street_address = null, $country = null, $service_provider = null, $limit = 5, $type = null)
    {
        if ( ($postcode == null && $street_address == null) || (trim($postcode) == '' && trim($street_address) == '') ) {
            return array();
        }

        $post_params = array(
            'postcode'          => (string) trim($postcode),
            'address'           => (string) trim($street_address),
            'country'           => (string) $country,
            'service_provider'  => (string) $service_provider,
            'limit'             => (int) $limit
        );

        if ( $type !== null ) {
            $post_params['type'] = (string) trim($type);
        }

        return json_decode($this->doPost('/pickup-points/search', $post_params));
    }

    /**
     * Searches pickup points with a text query. For best results the query should contain a full address
     *
     * @param $query_text Text containing the full address, for example: "Keskustori 1, 33100 Tampere"
     * @param string $service_provider $service_provider Limits results for to certain providers possible values: Posti, Matkahuolto, Db Schenker.
     * @param int $limit 1 - 15
     * @param string $type PRIVATE_LOCKER, PICKUP_POINT, PARCEL_LOCKER, OUTDOOR_LOCKER, AGENCY
     * @return array
     */
    public function searchPickupPointsByText($query_text, $service_provider = null, $limit = 5, $type = null)
    {
        if ( $query_text == null || trim($query_text) == '' ) {
            return array();
        }

        $post_params = array(
            'query'             => (string) trim($query_text),
            'service_provider'  => (string) $service_provider,
            'limit'             => (int) $limit
        );

        if ( $type !== null ) {
            $post_params['type'] = (string) trim($type);
        }

        return json_decode($this->doPost('/pickup-points/search', $post_params));
    }

    /**
     *
     * Searches info about a single pickup point.
     *
     * @param string $point_id  is an id for a single pickup point. For example: 905253201
     * @param  $service is used to identify service provider. It can shipping method code like '2103'
     *          or name of the service provider: "Posti", "Matkahuolto" or "Db Schenker".
     * @return string|null
     */
    public function getPickupPointInfo($point_id, $service)
    {
        if (empty($service) or empty($point_id))
        {
            return null;
        }

        $post_params = array(
            'point_id'  => (string) $point_id,
            'timestamp' => time()
        );

        if(is_numeric($service))
        {
            $post_params['service_code'] = $service;
        }else {
            $post_params['service_provider'] = $service;
        }

        return $this->doPost('/pickup-point/info', $post_params);
    }

    /**
     * Creates an activation code (Helposti-koodi, aktivointikoodi) to shipment.
     * Only Posti shipments are supported for now.
     *
     * @param string $tracking_code
     *
     * @return mixed
     */
    public function createActivationCode($tracking_code)
    {
        if (empty($tracking_code)) {
            return null;
        }

        $post_params = array('tracking_code' => $tracking_code);

        return $this->doPost('/shipment/create-activation-code', $post_params);
    }

    /**
     * @param $url_action
     * @param null $post_params
     * @param null $body
     * @return bool|string
     */
    private function doPost($url_action, $post_params = null, $body = null)
    {
        $requestId = $this->randomId();

        $headers = array();

        if(is_array($post_params))
        {
            if($this->use_posti_auth === true) {
                if(empty($this->access_token)) {
                    throw new \Exception("Access token must be set");
                }

                $post_params['token'] = $this->access_token;
            } else {
                if(!isset($post_params['api_key'])) {
                    $post_params['api_key'] = $this->api_key;
                }

                if(!isset($post_params['timestamp'])) {
                    $post_params['timestamp'] = time();
                }

                ksort($post_params);

                $post_params['hash'] = hash_hmac('sha256', join('&', $post_params), $this->secret);
            }

            $post_data = http_build_query($post_params);
        }

        if(!is_null($body)) {
            $headers[] = 'Content-type: text/xml; charset=utf-8';
            $post_data = $body;
        } else {
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
        }

        $options = array(
                CURLOPT_POST            =>  1,
                CURLOPT_HEADER          =>  0,
                CURLOPT_URL             =>  $this->base_uri.$url_action,
                CURLOPT_FRESH_CONNECT   =>  1,
                CURLOPT_RETURNTRANSFER  =>  1,
                CURLOPT_FORBID_REUSE    =>  1,
                CURLOPT_USERAGENT       =>  $this->user_agent,
                CURLOPT_TIMEOUT         =>  30,
                CURLOPT_HTTPHEADER      =>  $headers,
                CURLOPT_POSTFIELDS      =>  $post_data
        );

        $this->log(sprintf("Request: %s\nPOST %s\nHeaders\n%s\nData\n%s\n",
          $requestId,
          $this->base_uri.$url_action,
          json_encode($headers),
          json_encode($post_data)
        ));

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        $this->http_request         = $post_data;
        $this->http_response_code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $this->http_error           = curl_errno($ch);
        $this->http_response        = $response;

        $this->log(sprintf("Response: %s\nData\n%s\n",
          $requestId,
          json_encode($response)
        ));

        return $response;
    }

    /**
     *
     * @param $url
     * @param $user
     * @param $secret
     * @return bool|string
     */
    private function getPostiToken($url, $user, $secret)
    {
        $requestId = $this->randomId();
        $headers = array();

        $headers[] = 'Accept: application/json';
        $headers[] = 'Authorization: Basic ' .base64_encode("$user:$secret");
        $headers[] = 'Content-Length: 0';
        $headers[] = 'Expect:';

        $options = array(
            CURLOPT_POST            => 1,
            CURLOPT_HEADER          => 0,
            CURLOPT_URL             => $url,
            CURLOPT_FRESH_CONNECT   => 1,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_FORBID_REUSE    => 1,
            CURLOPT_USERAGENT       => $this->user_agent,
            CURLOPT_TIMEOUT         => 30,
            CURLOPT_HTTPHEADER      => $headers,

        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);

        $this->log(sprintf("Request: %s\nPOST %s\nHeaders\n%s\n",
          $requestId,
          $url,
          json_encode($headers)
        ));

        $response                   = curl_exec($ch);

        $this->http_response_code   = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $this->http_error           = (curl_errno($ch)) ? curl_error($ch) : '';
        $this->http_response        = $response;

        $this->log(sprintf("Response: %s\nData\n%s\n",
          $requestId,
          json_encode($response)
        ));

        curl_close($ch);

        return $response;
    }

  /**
   * @return ?\Closure
   */
  public function getLogClosure()
  {
    return $this->logClosure;
  }

  /**
   * @param ?\Closure $logClosure
   * @return static
   * @throws \ReflectionException
   */
  public function setLogClosure($logClosure)
  {
    if (!(($logClosure instanceof \Closure) || $logClosure === null))
    {
      throw new \Exception('logClosure must be function or null');
    }

    $reflection = new \ReflectionFunction($logClosure);
    if ($reflection->getNumberOfParameters() !== 2)
    {
      throw new \Exception('Function should have two parameters: message and level.');
    }

    $this->logClosure = $logClosure;
    return $this;
  }

  public function log($message, $level = self::LOG_LEVEL_DEBUG)
  {
    if ($this->getLogClosure() instanceof \Closure)
    {
      call_user_func($this->getLogClosure(), $message, $level);
    }
    return $this;
  }

  public function logError($message)
  {
    return $this->log($message, self::LOG_LEVEL_ERROR);
  }

  public function randomId()
  {
    if (function_exists('openssl_random_pseudo_bytes'))
    {
      $data = openssl_random_pseudo_bytes(16);
      $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
      $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
      return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
    return uniqid('ID-');
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia evodiae-trichotomae J.Y. Zhuang

### Remarks
null