text:
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Microsoft.Rest.Azure.OData;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// AadPropertiesOperations operations.
    /// </summary>
    public partial interface IAadPropertiesOperations
    {
        /// <summary>
        /// Fetches the AAD properties from target region BCM stamp.
        /// </summary>
        /// <param name='azureRegion'>
        /// Azure region to hit Api
        /// </param>
        /// <param name='odataQuery'>
        /// OData parameters to apply to the operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="NewErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<AADPropertiesResource>> GetWithHttpMessagesAsync(string azureRegion, ODataQuery<BMSAADPropertiesQueryObject> odataQuery = default(ODataQuery<BMSAADPropertiesQueryObject>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import client.User;
import price.Price;

/**
 *
 * @author hieldc
 */
public class UserDisplayManager {

    private User user;
    private MarketDisplay marketDisplay;

    public UserDisplayManager(User u) {
        user = u;
        marketDisplay = new MarketDisplay(u);
    }

    public void showMarketDisplay() throws Exception {
        marketDisplay.setVisible(true);
    }

    public void updateMarketData(String product, Price bp, int bv, Price sp, int sv) {
        marketDisplay.updateMarketData(product, bp, bv, sp, sv);
    }

    public void updateLastSale(String product, Price p, int v) {
        marketDisplay.updateLastSale(product, p, v);
    }

    public void updateTicker(String product, Price p, char direction) {
        marketDisplay.updateTicker(product, p, direction);
    }

    public void updateMarketActivity(String activityText) {
        marketDisplay.updateMarketActivity(activityText);
    }

    public void updateMarketState(String message) {
        marketDisplay.updateMarketState(message);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using Microsoft.AspNet.Identity.EntityFramework;
using AssessmentApp.WebClient.Models;
using AssessmentApp.WebClient.Code;

namespace AssessmentApp.WebClient
{
    public partial class Startup
    {

        private bool MakeSureRolesExist(Models.AppIdentityDbContext context)
        {
            IdentityResult ir;
            var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            if (!rm.RoleExists("teacher"))
                ir = rm.Create(new IdentityRole("teacher"));

            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            var me = um.FindByEmail("toddhilehoffer@yahoo.com");
            if (me == null) {
                um.Create(new ApplicationUser {
                    Email = AppSettings.AdminUserEmail,
                    EmailConfirmed = true,
                    UserName = AppSettings.AdminUserEmail,
                    PhoneNumber = AppSettings.AdminUserPhoneNumber,
                    PhoneNumberConfirmed = true }, AppSettings.AdminUserPassword);
            }
            um.AddToRole(me.Id, "teacher");

            return true;

        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(AppIdentityDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            //Added this to make sure the teach roles exists
            MakeSureRolesExist(AppIdentityDbContext.Create());

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
    }
}


text:
package com.francelabs.datafari.solr.custom;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.V2RequestSupport;
import org.apache.solr.client.solrj.impl.BinaryResponseParser;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.request.V2Request;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.ContentStream;

/**
 * This class overrides and somewhat changes the behavior of the SolrJ
 * HttpSolrServer class. The point of all this is simply to get the right
 * information to Tika. When SolrJ uses GET or POST but not multipart-post, it
 * does not include multipart headers that Tika uses - specifically, the name of
 * the document and the length of the document. Patches have been submitted to
 * the SOLR ticket queue to address this problem in a method-insensitive way,
 * but so far there has been no sign that the Solr team is interested in
 * committing them.
 */
public class ModifiedHttpSolrClient extends HttpSolrClient {

  // Here we duplicate all the private fields we need

  /**
   *
   */
  private static final long serialVersionUID = 1L;

  private static final String DEFAULT_PATH = "/select";

  private static Charset UTF8_CHARSET;

  private final HttpClient httpClient;
  private final boolean useMultiPartPost = true;

  public ModifiedHttpSolrClient(final String baseURL, final HttpClient client, final ResponseParser parser, final boolean allowCompression) {
    super(baseURL, client, parser, allowCompression);
    httpClient = client;
  }

  @Override
  protected HttpRequestBase createMethod(SolrRequest request, final String collection) throws IOException, SolrServerException {
    if (request instanceof V2RequestSupport) {
      request = ((V2RequestSupport) request).getV2Request();
    }
    final SolrParams params = request.getParams();
    final RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(request);
    Collection<ContentStream> streams = contentWriter == null ? requestWriter.getContentStreams(request) : null;
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
      path = DEFAULT_PATH;
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
      parser = this.parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    final ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
      wparams.set(CommonParams.WT, parser.getWriterType());
      wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
      wparams.add(invariantParams);
    }

    String basePath = baseUrl;
    if (collection != null)
      basePath += "/" + collection;

    if (request instanceof V2Request) {
      if (System.getProperty("solr.v2RealPath") == null) {
        basePath = baseUrl.replace("/solr", "/api");
      } else {
        basePath = baseUrl + "/____v2";
      }
    }

    if (SolrRequest.METHOD.GET == request.getMethod()) {
      if (streams != null || contentWriter != null) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
      }

      return new HttpGet(basePath + path + toQueryString(wparams, false));
    }

    if (SolrRequest.METHOD.DELETE == request.getMethod()) {
      return new HttpDelete(basePath + path + toQueryString(wparams, false));
    }

    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {

      // System.out.println("Post or put");
      final String url = basePath + path;

      // UpdateRequest uses PUT now, and ContentStreamUpdateHandler uses POST.
      // We must override PUT with POST if multipart is required.
      // If useMultipart is on, we fall back to getting streams directly from
      // the request, for now.
      final String contentWriterUrl = url + toQueryString(wparams, false);

      final boolean isMultipart;
      if (this.useMultiPartPost) {
        final Collection<ContentStream> requestStreams = request.getContentStreams();
        // Do we have streams?
        if (requestStreams != null && requestStreams.size() > 0) {

          // Need to know if we have a stream name
          boolean hasNullStreamName = false;
          if (requestStreams != null) {
            for (final ContentStream cs : requestStreams) {
              if (cs.getName() == null) {
                hasNullStreamName = true;
                break;
              }
            }
          }

          // Also, is the contentWriter URL too big?
          final boolean urlTooBig = contentWriterUrl.length() > 4000;
          // System.out.println("RequestStreams present? "+(requestStreams !=
          // null && requestStreams.size() > 0)+"; hasNullStreamName?
          // "+hasNullStreamName+"; url length = "+contentWriterUrl.length());
          isMultipart = requestStreams != null && requestStreams.size() > 0 && ((request.getMethod() == SolrRequest.METHOD.POST && !hasNullStreamName) || urlTooBig);
          if (isMultipart) {
            // System.out.println("Overriding with multipart post");
            streams = requestStreams;
          }
        } else {
          isMultipart = false;
        }
      } else {
        isMultipart = false;
      }

      final SolrRequest.METHOD methodToUse = isMultipart ? SolrRequest.METHOD.POST : request.getMethod();

      /*
       * final boolean isMultipart = ((this.useMultiPartPost &&
       * SolrRequest.METHOD.POST == methodToUse) || (streams != null &&
       * streams.size() > 1)) && !hasNullStreamName;
       */
      // System.out.println("isMultipart = "+isMultipart);

      final LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();

      if (contentWriter != null && !isMultipart) {
        // System.out.println(" using contentwriter");
        final String fullQueryUrl = contentWriterUrl;
        final HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == methodToUse ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
        postOrPut.addHeader("Content-Type", contentWriter.getContentType());
        postOrPut.setEntity(new BasicHttpEntity() {
          @Override
          public boolean isStreaming() {
            return true;
          }

          @Override
          public void writeTo(final OutputStream outstream) throws IOException {
            contentWriter.write(outstream);
          }
        });
        return postOrPut;

      } else if (streams == null || isMultipart) {
        // send server list and request list as query string params
        final ModifiableSolrParams queryParams = calculateQueryParams(getQueryParams(), wparams);
        queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
        final String fullQueryUrl = url + toQueryString(queryParams, false);
        final HttpEntityEnclosingRequestBase postOrPut = fillContentStream(methodToUse, streams, wparams, isMultipart, postOrPutParams, fullQueryUrl);
        return postOrPut;
      }
      // It is has one stream, it is the post body, put the params in the URL
      else {
        final String fullQueryUrl = url + toQueryString(wparams, false);
        final HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == methodToUse ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
        fillSingleContentStream(streams, postOrPut);

        return postOrPut;
      }
    }

    throw new SolrServerException("Unsupported method: " + request.getMethod());

  }

  private void fillSingleContentStream(final Collection<ContentStream> streams, final HttpEntityEnclosingRequestBase postOrPut) throws IOException {
    // Single stream as body
    // Using a loop just to get the first one
    final ContentStream[] contentStream = new ContentStream[1];
    for (final ContentStream content : streams) {
      contentStream[0] = content;
      break;
    }
    final Long size = contentStream[0].getSize();
    postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
      @Override
      public Header getContentType() {
        return new BasicHeader("Content-Type", contentStream[0].getContentType());
      }

      @Override
      public boolean isRepeatable() {
        return false;
      }
    });

  }

  private HttpEntityEnclosingRequestBase fillContentStream(final SolrRequest.METHOD methodToUse, final Collection<ContentStream> streams, final ModifiableSolrParams wparams, final boolean isMultipart, final LinkedList<NameValuePair> postOrPutParams,
      final String fullQueryUrl) throws IOException {
    final HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == methodToUse ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);

    if (!isMultipart) {
      postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    }

    final List<FormBodyPart> parts = new LinkedList<>();
    final Iterator<String> iter = wparams.getParameterNamesIterator();
    while (iter.hasNext()) {
      final String p = iter.next();
      final String[] vals = wparams.getParams(p);
      if (vals != null) {
        for (final String v : vals) {
          if (isMultipart) {
            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
          } else {
            postOrPutParams.add(new BasicNameValuePair(p, v));
          }
        }
      }
    }

    // TODO: remove deprecated - first simple attempt failed, see {@link
    // MultipartEntityBuilder}
    if (isMultipart && streams != null) {
      for (final ContentStream content : streams) {
        String contentType = content.getContentType();
        if (contentType == null) {
          contentType = BinaryResponseParser.BINARY_CONTENT_TYPE; // default
        }
        String name = content.getName();
        if (name == null) {
          name = "";
        }
        parts.add(new FormBodyPart(encodeForHeader(name), new InputStreamBody(content.getStream(), ContentType.parse(contentType), encodeForHeader(content.getName()))));
      }
    }

    // System.out.println("Using multipart post!");
    if (parts.size() > 0) {
      final ModifiedMultipartEntity entity = new ModifiedMultipartEntity(HttpMultipartMode.STRICT, null, StandardCharsets.UTF_8);
      // MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
      for (final FormBodyPart p : parts) {
        entity.addPart(p);
      }
      postOrPut.setEntity(entity);
    } else {
      // not using multipart
      postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
    }
    return postOrPut;
  }

  public static String toQueryString(final SolrParams params, final boolean xml) {
    final StringBuilder sb = new StringBuilder(128);
    try {
      final String amp = xml ? "&" : "&";
      boolean first = true;
      final Iterator<String> names = params.getParameterNamesIterator();
      while (names.hasNext()) {
        final String key = names.next();
        final String[] valarr = params.getParams(key);
        if (valarr == null) {
          sb.append(first ? "?" : amp);
          sb.append(URLEncoder.encode(key, "UTF-8"));
          first = false;
        } else {
          for (final String val : valarr) {
            sb.append(first ? "?" : amp);
            sb.append(key);
            if (val != null) {
              sb.append('=');
              sb.append(URLEncoder.encode(val, "UTF-8"));
            }
            first = false;
          }
        }
      }
    } catch (final IOException e) {
      throw new RuntimeException(e);
    } // can't happen
    return sb.toString();
  }

  // This is a hack added by KDW on 6/21/2017 because HttpClient doesn't do any
  // character
  // escaping when it puts together header and file names
  private static String encodeForHeader(final String headerName) {
    if (headerName == null) {
      return null;
    }
    final StringBuilder sb = new StringBuilder();
    for (int i = 0; i < headerName.length(); i++) {
      final char x = headerName.charAt(i);
      if (x == '"' || x == '\\' || x == '\r') {
        sb.append("\\");
      }
      sb.append(x);
    }
    return sb.toString();
  }

}


text:
// Copyright 2014-2015 Boundary, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.boundary.sdk.event.util;

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

import org.apache.camel.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Uses Camel's conversion system to convert from a {@link List} to {@link Iterator}
 *
 * @author davidg
 *
 */
@Converter
public final class SelectListConverter {

	private static Logger LOG = LoggerFactory.getLogger(SelectListConverter.class);

	@Converter
	public static Iterator<Map<String, Object>> toIterator(List<Map<String,Object>> list) {
		LOG.info("CALLING CONVERTER");
		return list.iterator();
	}
}


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var hxy;
(function (hxy) {
    var JsGame;
    (function (JsGame) {
        var ConcreteSprite;
        (function (ConcreteSprite) {
            var Explosion = (function (_super) {
                __extends(Explosion, _super);
                function Explosion() {
                    _super.apply(this, arguments);
                    this._frameNow = 0;
                }
                Object.defineProperty(Explosion.prototype, "collisionType", {
                    get: function () {
                        return 16 /* Explosion */;
                    },
                    enumerable: true,
                    configurable: true
                });
                Explosion.prototype.UpdateFrame = function () {
                    this._frameNow += 1;
                    if (this._frameNow >= this.images.length) {
                        this._frameNow = 0;
                        //frame is over,kill me.
                        this.manager.Kill(this);
                    }
                    this.imageIndex = this._frameNow;
                };
                return Explosion;
            })(JsGame.Common.SpriteBase);
            ConcreteSprite.Explosion = Explosion;
        })(ConcreteSprite = JsGame.ConcreteSprite || (JsGame.ConcreteSprite = {}));
    })(JsGame = hxy.JsGame || (hxy.JsGame = {}));
})(hxy || (hxy = {}));
//# sourceMappingURL=Explosion.js.map


text:
using AnalogDiscovery

function go(fs::Float64)
  cDev = enumDevices()
  @show ("Available",cDev)
  myDev = Int32(0)
  if cDev > 0
    if enumDeviceIsOpened(myDev)
      error("Error opening device, already in use.")
    end
    hdwf = deviceOpen(myDev)
  else
    error("No devices available.")
  end

  analogInFrequencySet(hdwf,fs)
  bmin,bmax = analogInBufferSizeInfo(hdwf)
  bsize = min(Int32(round(fs)),bmax)
  analogInBufferSizeSet(hdwf,bsize)
  analogInAcquisitionModeSet(hdwf,ACQMODESINGLE)

  chVoltMin,chVoltMax,chSteps = analogInChannelRangeInfo(hdwf)
  chCount = analogInChannelCount(hdwf)
  for ch in Int32(0):Int32(chCount-1)
    analogInChannelEnableSet(hdwf,ch,true)
    analogInChannelFilterSet(hdwf,ch,FILTERAVERAGE)
    analogInChannelRangeSet(hdwf,ch,chVoltMax)
  end

  # Collect 10-sec worth of data from all channels
  blks = Int(ceil(10*fs/bsize))
  chData = [Vector{Float64}(blks*bsize) for i in 1:chCount]

  for b in 1:blks
    analogInConfigure(hdwf,false,true) # start a single acquistion
    while analogInStatus(hdwf,true) != DWFSTATEDONE
      sleep(0.001)
    end

    chDataBuf = Vector{Float64}(bsize)
    for ch in Int32(0):Int32(chCount-1)
      analogInStatusData!(chDataBuf,hdwf,ch)
      chData[ch+1][(b-1)*bsize+(1:bsize)] = chDataBuf[:]
      #showall(chDataBuf)
    end
  end

  deviceClose(hdwf)
  return chData
end

const fs = 128.0
chData = go(fs)


text:
<?php

/**
 * Created by PhpStorm.
 * User: kbsoft
 * Date: 12/29/14
 * Time: 10:05 PM
 */
class Modem
{

    function __construct()
    {
        $this->system_config = new System_Configuration();
        Requests::register_autoloader();
    }

    function ping($fd = null)
    {
        $headers = array('Accept' => 'application/json');
        $data = array('fd' => $fd);
        try{
            $response = Requests::get($this->system_config->service_url('modem/ping'), $headers, $data);
            $return_value = $response->body;
        }catch (Requests_Exception $e){
            $return_value = json_encode(array('result'=> false, 'status' => 'fail'));
        }
        return json_decode($return_value);
    }

    function all()
    {
        $headers = array('Accept' => 'application/json');
        try{
            $response = Requests::get($this->system_config->service_url('modem/all'), $headers);
            $return_value = $response->body;
        }catch (Requests_Exception $e){
            $return_value = json_encode(array('result'=> false, 'status' => 'fail'));
        }
        return json_decode($return_value);
    }

    function find($fd)
    {
        $headers = array('Accept' => 'application/json');
        $data = array('fd'=>$fd);
        try{
            $response = Requests::get($this->system_config->service_url('modem/all?'.http_build_query($data)), $headers);
            $return_value = $response->body;
        }catch (Requests_Exception $e){
            $return_value = json_encode(array('result'=> false, 'status' => 'fail'));
        }
        return json_decode($return_value);
    }

    function dial($number,$fd = null)
    {
        $headers = array('Accept' => 'application/json');
        $data = array(
            'fd'=>$fd,
            'number' => $number
        );
        try{
            $response = Requests::post($this->system_config->service_url('modem/dial'), $headers, $data);
            $return_value = $response->body;
        }catch (Requests_Exception $e){
            $return_value = json_encode(array('result'=> false, 'status' => 'fail'));
        }
        return json_decode($return_value);
    }
}


text:
/* Written by Paul Rubin, phr@ocf.berkeley.edu
   and David MacKenzie, djm@gnu.ai.mit.edu. */

#include <config.h>

#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>

/* Get mbstate_t, mbrtowc(), wcwidth().  */
#if HAVE_WCHAR_H
# include <wchar.h>
#endif

/* Get iswprint(), iswspace().  */
#if HAVE_WCTYPE_H
# include <wctype.h>
#endif
#if !defined iswprint && !HAVE_ISWPRINT
# define iswprint(wc) 1
#endif
#if !defined iswspace && !HAVE_ISWSPACE
# define iswspace(wc) \
    ((wc) == (unsigned char) (wc) && ISSPACE ((unsigned char) (wc)))
#endif

/* Include this after wctype.h so that we `#undef' ISPRINT
   (from Solaris's euc.h, from widec.h, from wctype.h) before
   redefining and using it. */
#include "system.h"

#include "closeout.h"
#include "error.h"
#include "inttostr.h"
#include "safe-read.h"

/* Some systems, like BeOS, have multibyte encodings but lack mbstate_t.  */
#if HAVE_MBRTOWC && defined mbstate_t
# define mbrtowc(pwc, s, n, ps) (mbrtowc) (pwc, s, n, 0)
#endif

#ifndef HAVE_DECL_WCWIDTH
"this configure-time declaration test was not run"
#endif
#if !HAVE_DECL_WCWIDTH
extern int wcwidth ();
#endif

/* If wcwidth() doesn't exist, assume all printable characters have
   width 1.  */
#if !defined wcwidth && !HAVE_WCWIDTH
# define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
#endif

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "wc"

#define AUTHORS N_ ("Paul Rubin and David MacKenzie")

/* Size of atomic reads. */
#define BUFFER_SIZE (16 * 1024)

/* The name this program was run with. */
char *program_name;

/* Cumulative number of lines, words, chars and bytes in all files so far.
   max_line_length is the maximum over all files processed so far.  */
static uintmax_t total_lines;
static uintmax_t total_words;
static uintmax_t total_chars;
static uintmax_t total_bytes;
static uintmax_t max_line_length;

/* Which counts to print. */
static int print_lines, print_words, print_chars, print_bytes;
static int print_linelength;

/* Nonzero if we have ever read the standard input. */
static int have_read_stdin;

/* The error code to return to the system. */
static int exit_status;

/* If nonzero, do not line up columns but instead separate numbers by
   a single space as specified in Single Unix Specification and POSIX. */
static int posixly_correct;

static struct option const longopts[] =
{
  {"bytes", no_argument, NULL, 'c'},
  {"chars", no_argument, NULL, 'm'},
  {"lines", no_argument, NULL, 'l'},
  {"words", no_argument, NULL, 'w'},
  {"max-line-length", no_argument, NULL, 'L'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {NULL, 0, NULL, 0}
};

void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
	     program_name);
  else
    {
      printf (_("\
Usage: %s [OPTION]... [FILE]...\n\
"),
	      program_name);
      fputs (_("\
Print byte, word, and newline counts for each FILE, and a total line if\n\
more than one FILE is specified.  With no FILE, or when FILE is -,\n\
read standard input.\n\
  -c, --bytes            print the byte counts\n\
  -m, --chars            print the character counts\n\
  -l, --lines            print the newline counts\n\
"), stdout);
      fputs (_("\
  -L, --max-line-length  print the length of the longest line\n\
  -w, --words            print the word counts\n\
"), stdout);
      fputs (HELP_OPTION_DESCRIPTION, stdout);
      fputs (VERSION_OPTION_DESCRIPTION, stdout);
      printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
    }
  exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}

static void
write_counts (uintmax_t lines,
	      uintmax_t words,
	      uintmax_t chars,
	      uintmax_t bytes,
	      uintmax_t linelength,
	      const char *file)
{
  char buf[INT_BUFSIZE_BOUND (uintmax_t)];
  char const *space = "";
  char const *format_int = (posixly_correct ? "%s" : "%7s");
  char const *format_sp_int = (posixly_correct ? "%s%s" : "%s%7s");

  if (print_lines)
    {
      printf (format_int, umaxtostr (lines, buf));
      space = " ";
    }
  if (print_words)
    {
      printf (format_sp_int, space, umaxtostr (words, buf));
      space = " ";
    }
  if (print_chars)
    {
      printf (format_sp_int, space, umaxtostr (chars, buf));
      space = " ";
    }
  if (print_bytes)
    {
      printf (format_sp_int, space, umaxtostr (bytes, buf));
      space = " ";
    }
  if (print_linelength)
    {
      printf (format_sp_int, space, umaxtostr (linelength, buf));
    }
  if (*file)
    printf (" %s", file);
  putchar ('\n');
}

static void
wc (int fd, const char *file)
{
  char buf[BUFFER_SIZE + 1];
  size_t bytes_read;
  uintmax_t lines, words, chars, bytes, linelength;
  int count_bytes, count_chars, count_complicated;

  lines = words = chars = bytes = linelength = 0;

  /* If in the current locale, chars are equivalent to bytes, we prefer
     counting bytes, because that's easier.  */
#if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
  if (MB_CUR_MAX > 1)
    {
      count_bytes = print_bytes;
      count_chars = print_chars;
    }
  else
#endif
    {
      count_bytes = print_bytes + print_chars;
      count_chars = 0;
    }
  count_complicated = print_words + print_linelength;

  /* We need binary input, since `wc' relies on `lseek' and byte counts.  */
  SET_BINARY (fd);

  /* When counting only bytes, save some line- and word-counting
     overhead.  If FD is a `regular' Unix file, using lseek is enough
     to get its `size' in bytes.  Otherwise, read blocks of BUFFER_SIZE
     bytes at a time until EOF.  Note that the `size' (number of bytes)
     that wc reports is smaller than stats.st_size when the file is not
     positioned at its beginning.  That's why the lseek calls below are
     necessary.  For example the command
     `(dd ibs=99k skip=1 count=0; ./wc -c) < /etc/group'
     should make wc report `0' bytes.  */

  if (count_bytes && !count_chars && !print_lines && !count_complicated)
    {
      off_t current_pos, end_pos;
      struct stat stats;

      if (fstat (fd, &stats) == 0 && S_ISREG (stats.st_mode)
	  && (current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
	  && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
	{
	  off_t diff;
	  /* Be careful here.  The current position may actually be
	     beyond the end of the file.  As in the example above.  */
	  bytes = (diff = end_pos - current_pos) < 0 ? 0 : diff;
	}
      else
	{
	  while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
	    {
	      if (bytes_read == SAFE_READ_ERROR)
		{
		  error (0, errno, "%s", file);
		  exit_status = 1;
		  break;
		}
	      bytes += bytes_read;
	    }
	}
    }
  else if (!count_chars && !count_complicated)
    {
      /* Use a separate loop when counting only lines or lines and bytes --
	 but not chars or words.  */
      while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
	{
	  register char *p = buf;

	  if (bytes_read == SAFE_READ_ERROR)
	    {
	      error (0, errno, "%s", file);
	      exit_status = 1;
	      break;
	    }

	  while ((p = memchr (p, '\n', (buf + bytes_read) - p)))
	    {
	      ++p;
	      ++lines;
	    }
	  bytes += bytes_read;
	}
    }
#if HAVE_MBRTOWC && (MB_LEN_MAX > 1)
# define SUPPORT_OLD_MBRTOWC 1
  else if (MB_CUR_MAX > 1)
    {
      int in_word = 0;
      uintmax_t linepos = 0;
      mbstate_t state;
      uintmax_t last_error_line = 0;
      int last_error_errno = 0;
# if SUPPORT_OLD_MBRTOWC
      /* Back-up the state before each multibyte character conversion and
	 move the last incomplete character of the buffer to the front
	 of the buffer.  This is needed because we don't know whether
	 the `mbrtowc' function updates the state when it returns -2, -
	 this is the ISO C 99 and glibc-2.2 behaviour - or not - amended
	 ANSI C, glibc-2.1 and Solaris 2.7 behaviour.  We don't have an
	 autoconf test for this, yet.  */
      size_t prev = 0; /* number of bytes carried over from previous round */
# else
      const size_t prev = 0;
# endif

      memset (&state, 0, sizeof (mbstate_t));
      while ((bytes_read = safe_read (fd, buf + prev, BUFFER_SIZE - prev)) > 0)
	{
	  const char *p;
# if SUPPORT_OLD_MBRTOWC
	  mbstate_t backup_state;
# endif
	  if (bytes_read == SAFE_READ_ERROR)
	    {
	      error (0, errno, "%s", file);
	      exit_status = 1;
	      break;
	    }

	  bytes += bytes_read;
	  p = buf;
	  bytes_read += prev;
	  do
	    {
	      wchar_t wide_char;
	      size_t n;

# if SUPPORT_OLD_MBRTOWC
	      backup_state = state;
# endif
	      n = mbrtowc (&wide_char, p, bytes_read, &state);
	      if (n == (size_t) -2)
		{
# if SUPPORT_OLD_MBRTOWC
		  state = backup_state;
# endif
		  break;
		}
	      if (n == (size_t) -1)
		{
		  /* Signal repeated errors only once per line.  */
		  if (!(lines + 1 == last_error_line
			&& errno == last_error_errno))
		    {
		      char line_number_buf[INT_BUFSIZE_BOUND (uintmax_t)];
		      last_error_line = lines + 1;
		      last_error_errno = errno;
		      error (0, errno, "%s:%s", file,
			     umaxtostr (last_error_line, line_number_buf));
		    }
		  p++;
		  bytes_read--;
		}
	      else
		{
		  if (n == 0)
		    {
		      wide_char = 0;
		      n = 1;
		    }
		  p += n;
		  bytes_read -= n;
		  chars++;
		  switch (wide_char)
		    {
		    case '\n':
		      lines++;
		      /* Fall through. */
		    case '\r':
		    case '\f':
		      if (linepos > linelength)
			linelength = linepos;
		      linepos = 0;
		      goto mb_word_separator;
		    case '\t':
		      linepos += 8 - (linepos % 8);
		      goto mb_word_separator;
		    case ' ':
		      linepos++;
		      /* Fall through. */
		    case '\v':
		    mb_word_separator:
		      if (in_word)
			{
			  in_word = 0;
			  words++;
			}
		      break;
		    default:
		      if (iswprint (wide_char))
			{
			  int width = wcwidth (wide_char);
			  if (width > 0)
			    linepos += width;
			  if (iswspace (wide_char))
			    goto mb_word_separator;
			  in_word = 1;
			}
		      break;
		    }
		}
	    }
	  while (bytes_read > 0);

# if SUPPORT_OLD_MBRTOWC
	  if (bytes_read > 0)
	    {
	      if (bytes_read == BUFFER_SIZE)
		{
		  /* Encountered a very long redundant shift sequence.  */
		  p++;
		  bytes_read--;
		}
	      memmove (buf, p, bytes_read);
	    }
	  prev = bytes_read;
# endif
	}
      if (linepos > linelength)
	linelength = linepos;
      if (in_word)
	words++;
    }
#endif
  else
    {
      int in_word = 0;
      uintmax_t linepos = 0;

      while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0)
	{
	  const char *p = buf;
	  if (bytes_read == SAFE_READ_ERROR)
	    {
	      error (0, errno, "%s", file);
	      exit_status = 1;
	      break;
	    }

	  bytes += bytes_read;
	  do
	    {
	      switch (*p++)
		{
		case '\n':
		  lines++;
		  /* Fall through. */
		case '\r':
		case '\f':
		  if (linepos > linelength)
		    linelength = linepos;
		  linepos = 0;
		  goto word_separator;
		case '\t':
		  linepos += 8 - (linepos % 8);
		  goto word_separator;
		case ' ':
		  linepos++;
		  /* Fall through. */
		case '\v':
		word_separator:
		  if (in_word)
		    {
		      in_word = 0;
		      words++;
		    }
		  break;
		default:
		  if (ISPRINT ((unsigned char) p[-1]))
		    {
		      linepos++;
		      if (ISSPACE ((unsigned char) p[-1]))
			goto word_separator;
		      in_word = 1;
		    }
		  break;
		}
	    }
	  while (--bytes_read);
	}
      if (linepos > linelength)
	linelength = linepos;
      if (in_word)
	words++;
    }

  if (count_chars < print_chars)
    chars = bytes;

  write_counts (lines, words, chars, bytes, linelength, file);
  total_lines += lines;
  total_words += words;
  total_chars += chars;
  total_bytes += bytes;
  if (linelength > max_line_length)
    max_line_length = linelength;
}

static void
wc_file (const char *file)
{
  if (STREQ (file, "-"))
    {
      have_read_stdin = 1;
      wc (0, file);
    }
  else
    {
      int fd = open (file, O_RDONLY);
      if (fd == -1)
	{
	  error (0, errno, "%s", file);
	  exit_status = 1;
	  return;
	}
      wc (fd, file);
      if (close (fd))
	{
	  error (0, errno, "%s", file);
	  exit_status = 1;
	}
    }
}

int
main (int argc, char **argv)
{
  int optc;
  int nfiles;

  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  atexit (close_stdout);

  exit_status = 0;
  posixly_correct = (getenv ("POSIXLY_CORRECT") != NULL);
  print_lines = print_words = print_chars = print_bytes = print_linelength = 0;
  total_lines = total_words = total_chars = total_bytes = max_line_length = 0;

  while ((optc = getopt_long (argc, argv, "clLmw", longopts, NULL)) != -1)
    switch (optc)
      {
      case 0:
	break;

      case 'c':
	print_bytes = 1;
	break;

      case 'm':
	print_chars = 1;
	break;

      case 'l':
	print_lines = 1;
	break;

      case 'w':
	print_words = 1;
	break;

      case 'L':
	print_linelength = 1;
	break;

      case_GETOPT_HELP_CHAR;

      case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

      default:
	usage (EXIT_FAILURE);
      }

  if (print_lines + print_words + print_chars + print_bytes + print_linelength
      == 0)
    print_lines = print_words = print_bytes = 1;

  nfiles = argc - optind;

  if (nfiles == 0)
    {
      have_read_stdin = 1;
      wc (0, "");
    }
  else
    {
      for (; optind < argc; ++optind)
	wc_file (argv[optind]);

      if (nfiles > 1)
	write_counts (total_lines, total_words, total_chars, total_bytes,
		      max_line_length, _("total"));
    }

  if (have_read_stdin && close (STDIN_FILENO) != 0)
    error (EXIT_FAILURE, errno, "-");

  exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}


text:
package org.apache.activemq.artemis.tests.unit.util;

import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.SoftValueLongObjectHashMap;
import org.jboss.logging.Logger;
import org.junit.Test;

public class SoftValueMapTest extends ActiveMQTestBase {
   private static final Logger log = Logger.getLogger(SoftValueMapTest.class);
   // Constants -----------------------------------------------------

   // Attributes ----------------------------------------------------

   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   // Public --------------------------------------------------------

   @Test
   public void testEvictions() {
      forceGC();
      long maxMemory = Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory();

      // each buffer will be 1/10th of the maxMemory
      int bufferSize = (int) (maxMemory / 100);

      SoftValueLongObjectHashMap<Value> softCache = new SoftValueLongObjectHashMap<>(100);

      final int MAX_ELEMENTS = 1000;

      for (long i = 0; i < MAX_ELEMENTS; i++) {
         softCache.put(i, new Value(new byte[bufferSize]));
      }

      assertTrue(softCache.size() < MAX_ELEMENTS);

      log.debug("SoftCache.size " + softCache.size());

      log.debug("Soft cache has " + softCache.size() + " elements");
   }

   @Test
   public void testEvictionsLeastUsed() {
      forceGC();

      SoftValueLongObjectHashMap<Value> softCache = new SoftValueLongObjectHashMap<>(200);

      for (long i = 0; i < 100; i++) {
         Value v = new Value(new byte[1]);
         v.setLive(true);
         softCache.put(i, v);
      }

      for (long i = 100; i < 200; i++) {
         Value v = new Value(new byte[1]);
         softCache.put(i, v);
      }

      assertNotNull(softCache.get(100L));

      softCache.put(300L, new Value(new byte[1]));

      // these are live, so they shouldn't go

      for (long i = 0; i < 100; i++) {
         assertNotNull(softCache.get(i));
      }

      // this was accessed, so it shouldn't go
      assertNotNull(softCache.get(100L));

      // this is the next one, so it should go
      assertNull(softCache.get(101L));

      log.debug("SoftCache.size " + softCache.size());

      log.debug("Soft cache has " + softCache.size() + " elements");
   }

   @Test
   public void testEvictOldestElement() {
      Value one = new Value(new byte[100]);
      Value two = new Value(new byte[100]);
      Value three = new Value(new byte[100]);

      SoftValueLongObjectHashMap<Value> softCache = new SoftValueLongObjectHashMap<>(2);
      softCache.put(3, three);
      softCache.put(2, two);
      softCache.put(1, one);

      assertNull(softCache.get(3));
      assertEquals(two, softCache.get(2));
      assertEquals(one, softCache.get(1));

   }

   class Value implements SoftValueLongObjectHashMap.ValueCache {

      byte[] payload;

      boolean live;

      Value(byte[] payload) {
         this.payload = payload;
      }

      /* (non-Javadoc)
       * @see org.apache.activemq.artemis.utils.SoftValueLongObjectHashMap.ValueCache#isLive()
       */
      @Override
      public boolean isLive() {
         return live;
      }

      public void setLive(boolean live) {
         this.live = live;
      }
   }

   // Package protected ---------------------------------------------

   // Protected -----------------------------------------------------

   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------

}


text:
package org.basex.query.util.ft;

import java.util.*;

import org.basex.data.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;

/**
 * This class provides a container for query full-text positions,
 * which is evaluated by the visualizations.
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Christian Gruen
 * @author Sebastian Gath
 */
public final class FTPosData {
  /** Position references. */
  private FTPos[] pos = new FTPos[1];
  /** Data reference. */
  private Data dt;
  /** Number of values. */
  private int size;

  /**
   * Adds position data.
   *
   * @param data data reference
   * @param pre pre value
   * @param all full-text matches
   */
  public void add(final Data data, final int pre, final FTMatches all) {
    if(dt == null) dt = data;
    else if(dt != data) return;

    // cache all positions
    final IntSet set = new IntSet();
    for(final FTMatch ftm : all) {
      for(final FTStringMatch sm : ftm) {
        for(int s = sm.start; s <= sm.end; ++s) set.add(s);
      }
    }

    // sort and store all positions
    final IntList il = new IntList(set.toArray()).sort();
    int c = find(pre);
    if(c < 0) {
      c = -c - 1;
      final int sz = size;
      if(sz == pos.length) pos = Arrays.copyOf(pos, Array.newCapacity(sz));
      Array.insert(pos, c, 1, sz, null);
      pos[c] = new FTPos(pre, il);
      size++;
    } else {
      pos[c].union(il);
    }
  }

  /**
   * Gets full-text data from the container.
   * If no data is stored for a pre value, {@code null} is returned.
   * int[0] : [pos0, ..., posn]
   * int[1] : [poi0, ..., poin]
   * @param data data reference
   * @param pre int pre value
   * @return int[2][n] full-text data or {@code null}
   */
  public FTPos get(final Data data, final int pre) {
    final int p = find(pre);
    return p < 0 || dt != data ? null : pos[p];
  }

  /**
   * Returns the number of entries.
   * @return size
   */
  public int size() {
    int c = 0;
    for(int i = 0; i < size; ++i) c += pos[i].size();
    return c;
  }

  /**
   * Returns the index of the specified pre value.
   * @param pre int pre value
   * @return index, or negative index - 1 if pre value is not found
   */
  private int find(final int pre) {
    // binary search
    int l = 0, h = size - 1;
    while(l <= h) {
      final int m = l + h >>> 1;
      final int c = pos[m].pre - pre;
      if(c == 0) return m;
      if(c < 0) l = m + 1;
      else h = m - 1;
    }
    return -l - 1;
  }

  @Override
  public boolean equals(final Object obj) {
    if(this == obj) return true;
    if(!(obj instanceof FTPosData)) return false;
    final FTPosData ft = (FTPosData) obj;
    if(size != ft.size) return false;
    for(int p = 0; p < size; p++) {
      if(pos[p].pre != ft.pos[p].pre || !pos[p].equals(ft.pos[p])) return false;
    }
    return true;
  }
}


text:
import numpy as np

from .base import HomogFamilyAlignment
from .affine import DiscreteAffine
from .similarity import Similarity

class Translation(DiscreteAffine, Similarity):
    r"""
    An ``n_dims``-dimensional translation transform.

    Parameters
    ----------
    translation : ``(n_dims,)`` `ndarray`
        The translation in each axis.
    skip_checks : `bool`, optional
        If ``True`` avoid sanity checks on ``h_matrix`` for performance.
    """

    def __init__(self, translation, skip_checks=False):
        translation = np.asarray(translation)
        h_matrix = np.eye(translation.shape[0] + 1)
        h_matrix[:-1, -1] = translation
        Similarity.__init__(self, h_matrix, copy=False,
                            skip_checks=skip_checks)

    @classmethod
    def init_identity(cls, n_dims):
        r"""
        Creates an identity transform.

        Parameters
        ----------
        n_dims : `int`
            The number of dimensions.

        Returns
        -------
        identity : :class:`Translation`
            The identity matrix transform.
        """
        return Translation(np.zeros(n_dims))

    def _transform_str(self):
        message = 'Translation by {}'.format(self.translation_component)
        return message

    @property
    def n_parameters(self):
        r"""
        The number of parameters: ``n_dims``

        :type: `int`
        """
        return self.n_dims

    def _as_vector(self):
        r"""
        Return the parameters of the transform as a 1D array. These parameters
        are parametrised as deltas from the identity warp. The parameters
        are output in the order ``[t0, t1, ...]``.

        +-----------+--------------------------------------------+
        |parameter | definition                                  |
        +==========+=============================================+
        |t0        | The translation in the first axis           |
        |t1        | The translation in the second axis          |
        |...       | ...                                         |
        |tn        | The translation in the nth axis             |
        +----------+---------------------------------------------+

        Returns
        -------
        ts : ``(n_dims,)`` `ndarray`
            The translation in each axis.
        """
        return self.h_matrix[:-1, -1]

    def from_vector_inplace(self, p):
        r"""
        Updates the :class:`Translation` inplace.

        Parameters
        ----------
        vector : ``(n_dims,)`` `ndarray`
            The array of parameters.
        """
        self.h_matrix[:-1, -1] = p

    def pseudoinverse(self):
        r"""
        The inverse translation (negated).

        :type: :class:`Translation`
        """
        return Translation(-self.translation_component, skip_checks=True)

class AlignmentTranslation(HomogFamilyAlignment, Translation):
    r"""
    Constructs a :class:`Translation` by finding the optimal translation
    transform to align `source` to `target`.

    Parameters
    ----------
    source : :map:`PointCloud`
        The source pointcloud instance used in the alignment
    target : :map:`PointCloud`
        The target pointcloud instance used in the alignment
    """

    def __init__(self, source, target):
        HomogFamilyAlignment.__init__(self, source, target)
        Translation.__init__(self, target.centre() - source.centre())

    def from_vector_inplace(self, p):
        r"""
        Updates the :class:`Translation` inplace.

        Parameters
        ----------
        vector : ``(n_dims,)`` `ndarray`
            The array of parameters.
        """
        Translation.from_vector_inplace(self, p)
        self._sync_target_from_state()

    def _sync_state_from_target(self):
        translation = self.target.centre() - self.source.centre()
        self.h_matrix[:-1, -1] = translation

    def as_non_alignment(self):
        r"""
        Returns a copy of this translation without its alignment nature.

        Returns
        -------
        transform : :map:`Translation`
            A version of this transform with the same transform behavior but
            without the alignment logic.
        """
        return Translation(self.translation_component)


text:
require('normalize.css/normalize.css');
require('styles/App.css');

import React from 'react';

//let yeomanImage = require('../images/yeoman.png');
//获取图片
var imageDatas = require('../data/image.json');
//拉出URL
imageDatas = (function getImages(imageDatas) {
  for (var i = 0, j = imageDatas.length; i < j; i++) {
    var image = imageDatas[i];

    image.imageURL = require('../images/' + image.fileName);

    imageDatas[i] = image;
  }
  return imageDatas;
})(imageDatas);

//获取区间内的一个随机值
function getRangeRandom(low,hign) {
  return Math.ceil(Math.random()*(hign - low) + low);
}
function get30DegRandom() {
  return Math.random() > 0.5 ? '' : '-' +  Math.ceil(Math.random() * 30)
}
//控制组件
var ControllerUnit=React.createClass({
  handleClick:function(e) {
    //如果电机的是选中态的按钮,翻转,否则居中
    if(this.props.arrange.isCenter){
      this.props.inverse();
    }else{
      this.props.center();
    }
    e.preventDefault();
    e.stopPropagation();
  },
  render:function() {
    var controllerUnitClasssName = 'controller-unit';

    //如果对应的是居中的图片,显示控制按钮居中
    if(this.props.arrange.isCenter){
      controllerUnitClasssName +=' is-center';
      //如果同时对应的是翻转图片,翻转
      if(this.props.arrange.isInvers){
        controllerUnitClasssName += ' is-inverse';
      }
    }
    return (

    );
  }
});
var ImgFigure = React.createClass( {
  //图片点击事件
  handleClick:function(e) {
    if(this.props.arrange.isCenter){
      this.props.isInvers();
    }else{
      this.props.center();
    }

    e.stopPropagation();
    e.preventDefault();
  },
  render:function (){

  var styleObj = {};

  //如果props属性中指定了这张图片的位置,则使用
  if(this.props.arrange.pos){
    styleObj = this.props.arrange.pos;
  }
  //如果图片的旋转角度有值并且不为0,添加旋转角度
  if(this.props.arrange.rotate){
    (['MozTransform','msTransform','WebkitTransform','transform']).forEach(function (value) {
      styleObj[ value ] = 'rotate(' + this.props.arrange.rotate + 'deg)';
    }.bind(this));
  }
  var imgFigureClassName = 'img-figure';
      imgFigureClassName += this.props.arrange.isInvers ? ' is-inverse':'';

    return (

{this.props.data.description}

              {this.props.data.description}

    );
  }
})

var AppComponent = React.createClass( {
  Constant : {
      centerPos:{
        left:0,
        right:0
      },
      hPosRange:{//水平方向取值范围
        leftSecX:[0,0],
        rightSecX:[0,0],
        y:[0,0]
      },
      vPosRange:{//垂直方向取值范围
        x:[0,0],
        topY:[0,0]
      }
  },
  /*
  *翻转图片param index输入当前被执行inverse操作的图片对应的图片信息数组的index值
  *return 一个闭包函数,其内return一个真正被执行的函数
  */
  isInvers: function(index) {
    return function() {
      var imgsArrangeArr = this.state.imgsArrangeArr;

      imgsArrangeArr[index].isInvers = !imgsArrangeArr[index].isInvers;

      this.setState({
        imgsArrangeArr:imgsArrangeArr
      })
    }.bind(this);
  },
  //重新布局所有图片,指定哪个图片居中
  rearrange:function(centerIndex) {
    var imgsArrangeArr = this.state.imgsArrangeArr,
        Constant = this.Constant,
        centerPos= Constant.centerPos,
        hPosRange= Constant.hPosRange,
        vPosRange= Constant.vPosRange,
        hPosRangeLeftSecX = hPosRange.leftSecX,
        hPosRangeRightSecX= hPosRange.rightSecX,
        hPosRangeY = hPosRange.y,
        vPosRangeTopY = vPosRange.topY,
        vPosRangeX = vPosRange.x,

        imgsArrangeTopArr=[],
        topImgNum = Math.floor(Math.random()*2),//一个或者不取
        topImgSpliceIndex = 0,

        imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);

        //首先居中centerIndex的图片,无需旋转
        imgsArrangeCenterArr[0]={
          pos:centerPos,
          rotate:0,
          isCenter:true
        }

        //取出要布局上侧的状态信息
        topImgSpliceIndex = Math.ceil(Math.random()*(imgsArrangeArr.length - topImgNum));

        imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);

        //布局位于上侧的图片
        imgsArrangeTopArr.forEach(function(value,index) {
          imgsArrangeTopArr[index]={
            pos : {
              top : getRangeRandom(vPosRangeTopY[0],vPosRangeTopY[1]),
              left: getRangeRandom(vPosRangeX[0],vPosRangeX[1])
            },
            rotate:get30DegRandom(),
            isCenter:false
          }
        });

        //布局左右两侧的图片
        for(var i=0,j=imgsArrangeArr.length,k=j/2;i<j;i++){
          var hPosRangeLORX = null;

          //前半部分布局左边,后半部分布局右边
          if(i<k){
            hPosRangeLORX = hPosRangeLeftSecX;
          }else{
            hPosRangeLORX = hPosRangeRightSecX;
          }

          imgsArrangeArr[i] = {
              pos : {
              top: getRangeRandom(hPosRangeY[0],hPosRangeY[1]),
              left:getRangeRandom(hPosRangeLORX[0],hPosRangeLORX[1])
            },
            rotate : get30DegRandom(),
            isCenter:false
          }
        }

        if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
          imgsArrangeArr.splice(topImgSpliceIndex,0,imgsArrangeTopArr[0]);
        }

        imgsArrangeArr.splice(centerIndex,0,imgsArrangeCenterArr[0]);

        this.setState({
          imgsArrangeArr:imgsArrangeArr
        });
  },
  /*
  *利用rearrange凹函数,居中对应index图片
  *@param  index ,需要被居中的图片信息的index值
  *@return{function}
  */
  center:function(index) {
    return function() {
      this.rearrange(index);
    }.bind(this);
  },
  getInitialState:function () {
    return{
      imgsArrangeArr:[
        /*{
          pos:{
            left:0,
            top:0
          },
          rotate:0,
          isInverse:false, //图片正反面,默认正面
          isCenter:false   //是否居中
        }*/
      ]
    }
  },
  //组件加载后,计算图片范围
  componentDidMount:function (){debugger;
    //舞台大小
    var stageDOM=this.refs.stage,
        stageW = stageDOM.scrollWidth,
        stageH = stageDOM.scrollHeight,
        halfStageW= Math.ceil(stageW/2),
        halfStageH=Math.ceil(stageH/2);

    var imgFigureDOM = document.getElementsByTagName('img')[0],//component无法用ref获取未知原因
        imgW = imgFigureDOM.parentNode.scrollWidth,
        imgH = imgFigureDOM.parentNode.scrollHeight,
        halfImgW = Math.ceil(imgW/2),
        halfImgH = Math.ceil(imgH/2);

    //中心图片位置点
    this.Constant.centerPos = {
      left:halfStageW-halfImgW,
      top :halfStageH-halfImgH
    }
    //计算左右区域图片排布位置范围
    this.Constant.hPosRange.leftSecX[0] = -halfImgW;
    this.Constant.hPosRange.leftSecX[1] = halfStageW-halfImgW*3;
    this.Constant.hPosRange.rightSecX[0]= halfImgW + halfStageW;
    this.Constant.hPosRange.rightSecX[1]= stageW-halfImgW;
    this.Constant.hPosRange.y[0] = -halfImgH;
    this.Constant.hPosRange.y[1] = stageH - halfImgH;

    //计算上侧区域图片排布取值范围
    this.Constant.vPosRange.topY[0] = -halfImgH;
    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH*3;
    this.Constant.vPosRange.x[0]    = halfStageW - imgW;
    this.Constant.vPosRange.x[1]    = halfStageW;

    this.rearrange(0);

  },
  render:function (){
    var controllerUnits = [],
      imgFigures = [];

      imageDatas.forEach(function(element,index) {

        if(!this.state.imgsArrangeArr[index]){
          this.state.imgsArrangeArr[index] = {
            pos:{
              left:0,
              top:0
            },
            rotate:0,
            isInvers:false,
            isCenter:false
          }
        }

        imgFigures.push(
          <ImgFigure data={element} key = {index} ref = {'imgFigure'+index}  key = {'imgFigure'+index}   arrange={this.state.imgsArrangeArr[index]} isInvers={this.isInvers(index)} center={this.center(index)} />)
          controllerUnits.push(<ControllerUnit key = {index} arrange={this.state.imgsArrangeArr[index]} inverse={this.isInvers(index)} center={this.center(index)}/>);
        }.bind(this));
    return (

          {imgFigures}

          {controllerUnits}

    )
  }
})

export default AppComponent;


text:
<!--
  ~ Copyright (c) 2017 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->
<role oid="97cc13ac-5660-11e7-8687-d76f3a88c78d"
        xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
        xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3">
    <name>Read Self Modify Orgunit</name>
    <authorization>
        <name>self-read</name>
        <description>
            Allow to read all the properties of "self" object. I.e. every logged-in user can read
            object that represent his own identity.
        </description>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
        <object>
            <special>self</special>
        </object>
    </authorization>
    <authorization>
        <name>self-accounts-read</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#read</action>
        <object>
            <type>ShadowType</type>
            <owner>
                <special>self</special>
            </owner>
        </object>
    </authorization>
    <authorization>
        <name>modify-self-orgunit</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
        <object>
            <special>self</special>
        </object>
        <item>organizationalUnit</item>
    </authorization>
    <authorization>
        <name>modify-exec</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
        <phase>execution</phase>
    </authorization>
    <authorization>
        <name>self-accounts-write-exec</name>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#add</action>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#modify</action>
        <action>http://midpoint.evolveum.com/xml/ns/public/security/authorization-model-3#delete</action>
        <phase>execution</phase>
        <object>
            <type>ShadowType</type>
            <owner>
                <special>self</special>
            </owner>
        </object>
    </authorization>
</role>


text:
/*
 * 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.overlord.rtgov.activity.model.bpm;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import javax.persistence.Entity;

/**
 * This activity type represents a process variable being set.
 *
 */
@Entity
public class ProcessVariableSet extends BPMActivityType implements java.io.Externalizable {

    private static final int VERSION = 1;

    private String _variableName=null;
    private String _variableType=null;
    private String _variableValue=null;

    /**
     * The default constructor.
     */
    public ProcessVariableSet() {
    }

    /**
     * The copy constructor.
     *
     * @param ba The bpm activity to copy
     */
    public ProcessVariableSet(ProcessVariableSet ba) {
        super(ba);
        _variableName = ba._variableName;
        _variableType = ba._variableType;
        _variableValue = ba._variableValue;
    }

    /**
     * This method sets the variable name.
     *
     * @param name The name
     */
    public void setVariableName(String name) {
        _variableName = name;
    }

    /**
     * This method gets the variable name.
     *
     * @return The name
     */
    public String getVariableName() {
        return (_variableName);
    }

    /**
     * This method sets the variable type.
     *
     * @param type The type
     */
    public void setVariableType(String type) {
        _variableType = type;
    }

    /**
     * This method gets the variable type.
     *
     * @return The type
     */
    public String getVariableType() {
        return (_variableType);
    }

    /**
     * This method sets the variable value.
     *
     * @param value The value
     */
    public void setVariableValue(String value) {
        _variableValue = value;
    }

    /**
     * This method gets the variable value.
     *
     * @return The value
     */
    public String getVariableValue() {
        return (_variableValue);
    }

    /**
     * {@inheritDoc}
     */
    public void writeExternal(ObjectOutput out) throws IOException {
        super.writeExternal(out);

        out.writeInt(VERSION);

        out.writeObject(_variableName);
        out.writeObject(_variableType);
        out.writeObject(_variableValue);
    }

    /**
     * {@inheritDoc}
     */
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        super.readExternal(in);

        in.readInt(); // Consume version, as not required for now

        _variableName = (String)in.readObject();
        _variableType = (String)in.readObject();
        _variableValue = (String)in.readObject();
    }
}


text:
/*-************************************
*  Tuning parameters
**************************************/
#ifndef ZSTDCLI_CLEVEL_DEFAULT
#  define ZSTDCLI_CLEVEL_DEFAULT 3
#endif

#ifndef ZSTDCLI_CLEVEL_MAX
#  define ZSTDCLI_CLEVEL_MAX 19   /* when not using --ultra */
#endif

/*-************************************
*  Dependencies
**************************************/
#include "platform.h" /* IS_CONSOLE, PLATFORM_POSIX_VERSION */
#include "util.h"     /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList */
#include <string.h>   /* strcmp, strlen */
#include <errno.h>    /* errno */
#include "fileio.h"
#ifndef ZSTD_NOBENCH
#  include "bench.h"  /* BMK_benchFiles, BMK_SetNbSeconds */
#endif
#ifndef ZSTD_NODICT
#  include "dibio.h"
#endif
#define ZSTD_STATIC_LINKING_ONLY   /* ZSTD_maxCLevel */
#include "zstd.h"     /* ZSTD_VERSION_STRING */

/*-************************************
*  Constants
**************************************/
#define COMPRESSOR_NAME "zstd command line interface"
#ifndef ZSTD_VERSION
#  define ZSTD_VERSION "v" ZSTD_VERSION_STRING
#endif
#define AUTHOR "Yann Collet"
#define WELCOME_MESSAGE "*** %s %i-bits %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR

#define ZSTD_EXTENSION ".zst"
#define ZSTD_CAT "zstdcat"
#define ZSTD_UNZSTD "unzstd"

#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)

#define DEFAULT_DISPLAY_LEVEL 2

static const char*    g_defaultDictName = "dictionary";
static const unsigned g_defaultMaxDictSize = 110 KB;
static const int      g_defaultDictCLevel = 3;
static const unsigned g_defaultSelectivityLevel = 9;
#define OVERLAP_LOG_DEFAULT 9999
static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;

/*-************************************
*  Display Macros
**************************************/
#define DISPLAY(...)           fprintf(displayOut, __VA_ARGS__)
#define DISPLAYLEVEL(l, ...)   if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
static FILE* displayOut;
static unsigned displayLevel = DEFAULT_DISPLAY_LEVEL;   /* 0 : no display,  1: errors,  2 : + result + interaction + warnings,  3 : + progression,  4 : + information */

/*-************************************
*  Command Line
**************************************/
static int usage(const char* programName)
{
    DISPLAY( "Usage :\n");
    DISPLAY( "      %s [args] [FILE(s)] [-o file]\n", programName);
    DISPLAY( "\n");
    DISPLAY( "FILE    : a filename\n");
    DISPLAY( "          with no FILE, or when FILE is - , read standard input\n");
    DISPLAY( "Arguments :\n");
#ifndef ZSTD_NOCOMPRESS
    DISPLAY( " -#     : # compression level (1-%d, default:%d) \n", ZSTDCLI_CLEVEL_MAX, ZSTDCLI_CLEVEL_DEFAULT);
#endif
#ifndef ZSTD_NODECOMPRESS
    DISPLAY( " -d     : decompression \n");
#endif
    DISPLAY( " -D file: use `file` as Dictionary \n");
    DISPLAY( " -o file: result stored into `file` (only if 1 input file) \n");
    DISPLAY( " -f     : overwrite output without prompting \n");
    DISPLAY( "--rm    : remove source file(s) after successful de/compression \n");
    DISPLAY( " -k     : preserve source file(s) (default) \n");
    DISPLAY( " -h/-H  : display help/long help and exit\n");
    return 0;
}

static int usage_advanced(const char* programName)
{
    DISPLAY(WELCOME_MESSAGE);
    usage(programName);
    DISPLAY( "\n");
    DISPLAY( "Advanced arguments :\n");
    DISPLAY( " -V     : display Version number and exit\n");
    DISPLAY( " -v     : verbose mode; specify multiple times to increase log level (default:%d)\n", DEFAULT_DISPLAY_LEVEL);
    DISPLAY( " -q     : suppress warnings; specify twice to suppress errors too\n");
    DISPLAY( " -c     : force write to standard output, even if it is the console\n");
#ifdef UTIL_HAS_CREATEFILELIST
    DISPLAY( " -r     : operate recursively on directories \n");
#endif
#ifndef ZSTD_NOCOMPRESS
    DISPLAY( "--ultra : enable levels beyond %i, up to %i (requires more memory)\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
    DISPLAY( "--no-dictID : don't write dictID into header (dictionary compression)\n");
    DISPLAY( "--[no-]check : integrity check (default:enabled) \n");
#ifdef ZSTD_MULTITHREAD
    DISPLAY( " -T#    : use # threads for compression (default:1) \n");
    DISPLAY( " -B#    : select size of independent sections (default:0==automatic) \n");
#endif
#endif
#ifndef ZSTD_NODECOMPRESS
    DISPLAY( "--test  : test compressed file integrity \n");
    DISPLAY( "--[no-]sparse : sparse mode (default:enabled on file, disabled on stdout)\n");
#endif
    DISPLAY( " -M#    : Set a memory usage limit for decompression \n");
    DISPLAY( "--      : All arguments after \"--\" are treated as files \n");
#ifndef ZSTD_NODICT
    DISPLAY( "\n");
    DISPLAY( "Dictionary builder :\n");
    DISPLAY( "--train ## : create a dictionary from a training set of files \n");
    DISPLAY( "--cover=k=#,d=# : use the cover algorithm with parameters k and d \n");
    DISPLAY( "--optimize-cover[=steps=#,k=#,d=#] : optimize cover parameters with optional parameters\n");
    DISPLAY( " -o file : `file` is dictionary name (default: %s) \n", g_defaultDictName);
    DISPLAY( "--maxdict ## : limit dictionary to specified size (default : %u) \n", g_defaultMaxDictSize);
    DISPLAY( " -s#    : dictionary selectivity level (default: %u)\n", g_defaultSelectivityLevel);
    DISPLAY( "--dictID ## : force dictionary ID to specified value (default: random)\n");
#endif
#ifndef ZSTD_NOBENCH
    DISPLAY( "\n");
    DISPLAY( "Benchmark arguments :\n");
    DISPLAY( " -b#    : benchmark file(s), using # compression level (default : 1) \n");
    DISPLAY( " -e#    : test all compression levels from -bX to # (default: 1)\n");
    DISPLAY( " -i#    : minimum evaluation time in seconds (default : 3s)\n");
    DISPLAY( " -B#    : cut file into independent blocks of size # (default: no block)\n");
#endif
    return 0;
}

static int badusage(const char* programName)
{
    DISPLAYLEVEL(1, "Incorrect parameters\n");
    if (displayLevel >= 1) usage(programName);
    return 1;
}

static void waitEnter(void)
{
    int unused;
    DISPLAY("Press enter to continue...\n");
    unused = getchar();
    (void)unused;
}

/*! readU32FromChar() :
    @return : unsigned integer value read from input in `char` format
    allows and interprets K, KB, KiB, M, MB and MiB suffix.
    Will also modify `*stringPtr`, advancing it to position where it stopped reading.
    Note : function result can overflow if digit string > MAX_UINT */
static unsigned readU32FromChar(const char** stringPtr)
{
    unsigned result = 0;
    while ((**stringPtr >='0') && (**stringPtr <='9'))
        result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
    if ((**stringPtr=='K') || (**stringPtr=='M')) {
        result <<= 10;
        if (**stringPtr=='M') result <<= 10;
        (*stringPtr)++ ;
        if (**stringPtr=='i') (*stringPtr)++;
        if (**stringPtr=='B') (*stringPtr)++;
    }
    return result;
}

/** longCommandWArg() :
 *  check if *stringPtr is the same as longCommand.
 *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
 *  @return 0 and doesn't modify *stringPtr otherwise.
 */
static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
{
    size_t const comSize = strlen(longCommand);
    int const result = !strncmp(*stringPtr, longCommand, comSize);
    if (result) *stringPtr += comSize;
    return result;
}

#ifndef ZSTD_NODICT
/**
 * parseCoverParameters() :
 * reads cover parameters from *stringPtr (e.g. "--cover=smoothing=100,kmin=48,kstep=4,kmax=64,d=8") into *params
 * @return 1 means that cover parameters were correct
 * @return 0 in case of malformed parameters
 */
static unsigned parseCoverParameters(const char* stringPtr, COVER_params_t *params)
{
    memset(params, 0, sizeof(*params));
    for (; ;) {
        if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        return 0;
    }
    if (stringPtr[0] != 0) return 0;
    DISPLAYLEVEL(4, "k=%u\nd=%u\nsteps=%u\n", params->k, params->d, params->steps);
    return 1;
}
#endif

/** parseCompressionParameters() :
 *  reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,slen=3,tlen=48,strat=6") into *params
 *  @return 1 means that compression parameters were correct
 *  @return 0 in case of malformed parameters
 */
static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
{
    for ( ; ;) {
        if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "searchLength=") || longCommandWArg(&stringPtr, "slen=")) { params->searchLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(1 + readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
        return 0;
    }

    if (stringPtr[0] != 0) return 0; /* check the end of string */
    DISPLAYLEVEL(4, "windowLog=%d\nchainLog=%d\nhashLog=%d\nsearchLog=%d\n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
    DISPLAYLEVEL(4, "searchLength=%d\ntargetLength=%d\nstrategy=%d\n", params->searchLength, params->targetLength, params->strategy);
    return 1;
}

typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train } zstd_operation_mode;

#define CLEAN_RETURN(i) { operationResult = (i); goto _end; }

int main(int argCount, const char* argv[])
{
    int argNb,
        forceStdout=0,
        main_pause=0,
        nextEntryIsDictionary=0,
        operationResult=0,
        nextArgumentIsOutFileName=0,
        nextArgumentIsMaxDict=0,
        nextArgumentIsDictID=0,
        nextArgumentsAreFiles=0,
        ultra=0,
        lastCommand = 0,
        nbThreads = 1;
    unsigned bench_nbSeconds = 3;   /* would be better if this value was synchronized from bench */
    size_t blockSize = 0;
    zstd_operation_mode operation = zom_compress;
    ZSTD_compressionParameters compressionParams;
    int cLevel = ZSTDCLI_CLEVEL_DEFAULT;
    int cLevelLast = 1;
    unsigned recursive = 0;
    unsigned memLimit = 0;
    const char** filenameTable = (const char**)malloc(argCount * sizeof(const char*));   /* argCount >= 1 */
    unsigned filenameIdx = 0;
    const char* programName = argv[0];
    const char* outFileName = NULL;
    const char* dictFileName = NULL;
    unsigned maxDictSize = g_defaultMaxDictSize;
    unsigned dictID = 0;
    int dictCLevel = g_defaultDictCLevel;
    unsigned dictSelect = g_defaultSelectivityLevel;
#ifdef UTIL_HAS_CREATEFILELIST
    const char** extendedFileList = NULL;
    char* fileNamesBuf = NULL;
    unsigned fileNamesNb;
#endif
#ifndef ZSTD_NODICT
    COVER_params_t coverParams;
    int cover = 0;
#endif

    /* init */
    (void)recursive; (void)cLevelLast;    /* not used when ZSTD_NOBENCH set */
    (void)dictCLevel; (void)dictSelect; (void)dictID;  (void)maxDictSize; /* not used when ZSTD_NODICT set */
    (void)ultra; (void)cLevel; /* not used when ZSTD_NOCOMPRESS set */
    (void)memLimit;   /* not used when ZSTD_NODECOMPRESS set */
    if (filenameTable==NULL) { DISPLAY("zstd: %s \n", strerror(errno)); exit(1); }
    filenameTable[0] = stdinmark;
    displayOut = stderr;
    /* Pick out program name from path. Don't rely on stdlib because of conflicting behavior */
    {   size_t pos;
        for (pos = (int)strlen(programName); pos > 0; pos--) { if (programName[pos] == '/') { pos++; break; } }
        programName += pos;
    }

    /* preset behaviors */
    if (!strcmp(programName, ZSTD_UNZSTD)) operation=zom_decompress;
    if (!strcmp(programName, ZSTD_CAT)) { operation=zom_decompress; forceStdout=1; FIO_overwriteMode(); outFileName=stdoutmark; displayLevel=1; }
    memset(&compressionParams, 0, sizeof(compressionParams));

    /* command switches */
    for (argNb=1; argNb<argCount; argNb++) {
        const char* argument = argv[argNb];
        if(!argument) continue;   /* Protection if argument empty */

        if (nextArgumentsAreFiles==0) {
            /* "-" means stdin/stdout */
            if (!strcmp(argument, "-")){
                if (!filenameIdx) {
                    filenameIdx=1, filenameTable[0]=stdinmark;
                    outFileName=stdoutmark;
                    displayLevel-=(displayLevel==2);
                    continue;
            }   }

            /* Decode commands (note : aggregated commands are allowed) */
            if (argument[0]=='-') {

                if (argument[1]=='-') {
                    /* long commands (--long-word) */
                    if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; }   /* only file names allowed from now on */
                    if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
                    if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
                    if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
                    if (!strcmp(argument, "--force")) { FIO_overwriteMode(); continue; }
                    if (!strcmp(argument, "--version")) { displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0); }
                    if (!strcmp(argument, "--help")) { displayOut=stdout; CLEAN_RETURN(usage_advanced(programName)); }
                    if (!strcmp(argument, "--verbose")) { displayLevel++; continue; }
                    if (!strcmp(argument, "--quiet")) { displayLevel--; continue; }
                    if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; displayLevel-=(displayLevel==2); continue; }
                    if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
                    if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(2); continue; }
                    if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(0); continue; }
                    if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(2); continue; }
                    if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(0); continue; }
                    if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
                    if (!strcmp(argument, "--train")) { operation=zom_train; outFileName=g_defaultDictName; continue; }
                    if (!strcmp(argument, "--maxdict")) { nextArgumentIsMaxDict=1; lastCommand=1; continue; }
                    if (!strcmp(argument, "--dictID")) { nextArgumentIsDictID=1; lastCommand=1; continue; }
                    if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(0); continue; }
                    if (!strcmp(argument, "--keep")) { FIO_setRemoveSrcFile(0); continue; }
                    if (!strcmp(argument, "--rm")) { FIO_setRemoveSrcFile(1); continue; }

                    /* long commands with arguments */
#ifndef  ZSTD_NODICT
                    if (longCommandWArg(&argument, "--cover=")) {
                      cover=1; if (!parseCoverParameters(argument, &coverParams)) CLEAN_RETURN(badusage(programName));
                      continue;
                    }
                    if (longCommandWArg(&argument, "--optimize-cover")) {
                      cover=2;
                      /* Allow optional arguments following an = */
                      if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
                      else if (*argument++ != '=') { CLEAN_RETURN(badusage(programName)); }
                      else if (!parseCoverParameters(argument, &coverParams)) { CLEAN_RETURN(badusage(programName)); }
                      continue;
                    }
#endif
                    if (longCommandWArg(&argument, "--memlimit=")) { memLimit = readU32FromChar(&argument); continue; }
                    if (longCommandWArg(&argument, "--memory=")) { memLimit = readU32FromChar(&argument); continue; }
                    if (longCommandWArg(&argument, "--memlimit-decompress=")) { memLimit = readU32FromChar(&argument); continue; }
                    if (longCommandWArg(&argument, "--block-size=")) { blockSize = readU32FromChar(&argument); continue; }
                    if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) CLEAN_RETURN(badusage(programName)); continue; }
                    /* fall-through, will trigger bad_usage() later on */
                }

                argument++;
                while (argument[0]!=0) {
                    if (lastCommand) {
                        DISPLAY("error : command must be followed by argument \n");
                        return 1;
                    }
#ifndef ZSTD_NOCOMPRESS
                    /* compression Level */
                    if ((*argument>='0') && (*argument<='9')) {
                        dictCLevel = cLevel = readU32FromChar(&argument);
                        continue;
                    }
#endif

                    switch(argument[0])
                    {
                        /* Display help */
                    case 'V': displayOut=stdout; DISPLAY(WELCOME_MESSAGE); CLEAN_RETURN(0);   /* Version Only */
                    case 'H':
                    case 'h': displayOut=stdout; CLEAN_RETURN(usage_advanced(programName));

                         /* Compress */
                    case 'z': operation=zom_compress; argument++; break;

                         /* Decoding */
                    case 'd':
#ifndef ZSTD_NOBENCH
                            if (operation==zom_bench) { BMK_setDecodeOnlyMode(1); argument++; break; }  /* benchmark decode (hidden option) */
#endif
                            operation=zom_decompress; argument++; break;

                        /* Force stdout, even if stdout==console */
                    case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;

                        /* Use file content as dictionary */
                    case 'D': nextEntryIsDictionary = 1; lastCommand = 1; argument++; break;

                        /* Overwrite */
                    case 'f': FIO_overwriteMode(); forceStdout=1; argument++; break;

                        /* Verbose mode */
                    case 'v': displayLevel++; argument++; break;

                        /* Quiet mode */
                    case 'q': displayLevel--; argument++; break;

                        /* keep source file (default); for gzip/xz compatibility */
                    case 'k': FIO_setRemoveSrcFile(0); argument++; break;

                        /* Checksum */
                    case 'C': argument++; FIO_setChecksumFlag(2); break;

                        /* test compressed file */
                    case 't': operation=zom_test; argument++; break;

                        /* destination file name */
                    case 'o': nextArgumentIsOutFileName=1; lastCommand=1; argument++; break;

                        /* limit decompression memory */
                    case 'M':
                        argument++;
                        memLimit = readU32FromChar(&argument);
                        break;

#ifdef UTIL_HAS_CREATEFILELIST
                        /* recursive */
                    case 'r': recursive=1; argument++; break;
#endif

#ifndef ZSTD_NOBENCH
                        /* Benchmark */
                    case 'b':
                        operation=zom_bench;
                        argument++;
                        break;

                        /* range bench (benchmark only) */
                    case 'e':
                        /* compression Level */
                        argument++;
                        cLevelLast = readU32FromChar(&argument);
                        break;

                        /* Modify Nb Iterations (benchmark only) */
                    case 'i':
                        argument++;
                        bench_nbSeconds = readU32FromChar(&argument);
                        break;

                        /* cut input into blocks (benchmark only) */
                    case 'B':
                        argument++;
                        blockSize = readU32FromChar(&argument);
                        break;

#endif   /* ZSTD_NOBENCH */

                        /* nb of threads (hidden option) */
                    case 'T':
                        argument++;
                        nbThreads = readU32FromChar(&argument);
                        break;

                        /* Dictionary Selection level */
                    case 's':
                        argument++;
                        dictSelect = readU32FromChar(&argument);
                        break;

                        /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
                    case 'p': argument++;
#ifndef ZSTD_NOBENCH
                        if ((*argument>='0') && (*argument<='9')) {
                            BMK_setAdditionalParam(readU32FromChar(&argument));
                        } else
#endif
                            main_pause=1;
                        break;
                        /* unknown command */
                    default : CLEAN_RETURN(badusage(programName));
                    }
                }
                continue;
            }   /* if (argument[0]=='-') */

            if (nextArgumentIsMaxDict) {
                nextArgumentIsMaxDict = 0;
                lastCommand = 0;
                maxDictSize = readU32FromChar(&argument);
                continue;
            }

            if (nextArgumentIsDictID) {
                nextArgumentIsDictID = 0;
                lastCommand = 0;
                dictID = readU32FromChar(&argument);
                continue;
            }

        }   /* if (nextArgumentIsAFile==0) */

        if (nextEntryIsDictionary) {
            nextEntryIsDictionary = 0;
            lastCommand = 0;
            dictFileName = argument;
            continue;
        }

        if (nextArgumentIsOutFileName) {
            nextArgumentIsOutFileName = 0;
            lastCommand = 0;
            outFileName = argument;
            if (!strcmp(outFileName, "-")) outFileName = stdoutmark;
            continue;
        }

        /* add filename to list */
        filenameTable[filenameIdx++] = argument;
    }

    if (lastCommand) { DISPLAY("error : command must be followed by argument \n"); return 1; }  /* forgotten argument */

    /* Welcome message (if verbose) */
    DISPLAYLEVEL(3, WELCOME_MESSAGE);
#ifdef _POSIX_C_SOURCE
    DISPLAYLEVEL(4, "_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
#endif
#ifdef _POSIX_VERSION
    DISPLAYLEVEL(4, "_POSIX_VERSION defined: %ldL\n", (long) _POSIX_VERSION);
#endif
#ifdef PLATFORM_POSIX_VERSION
    DISPLAYLEVEL(4, "PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
#endif

#ifdef UTIL_HAS_CREATEFILELIST
    if (recursive) {  /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
        extendedFileList = UTIL_createFileList(filenameTable, filenameIdx, &fileNamesBuf, &fileNamesNb);
        if (extendedFileList) {
            unsigned u;
            for (u=0; u<fileNamesNb; u++) DISPLAYLEVEL(4, "%u %s\n", u, extendedFileList[u]);
            free((void*)filenameTable);
            filenameTable = extendedFileList;
            filenameIdx = fileNamesNb;
        }
    }
#endif

    /* Check if benchmark is selected */
    if (operation==zom_bench) {
#ifndef ZSTD_NOBENCH
        BMK_setNotificationLevel(displayLevel);
        BMK_setBlockSize(blockSize);
        BMK_setNbThreads(nbThreads);
        BMK_setNbSeconds(bench_nbSeconds);
        BMK_benchFiles(filenameTable, filenameIdx, dictFileName, cLevel, cLevelLast, &compressionParams);
#endif
        (void)bench_nbSeconds;
        goto _end;
    }

    /* Check if dictionary builder is selected */
    if (operation==zom_train) {
#ifndef ZSTD_NODICT
        if (cover) {
            coverParams.nbThreads = nbThreads;
            coverParams.compressionLevel = dictCLevel;
            coverParams.notificationLevel = displayLevel;
            coverParams.dictID = dictID;
            DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, NULL, &coverParams, cover - 1);
        } else {
            ZDICT_params_t dictParams;
            memset(&dictParams, 0, sizeof(dictParams));
            dictParams.compressionLevel = dictCLevel;
            dictParams.selectivityLevel = dictSelect;
            dictParams.notificationLevel = displayLevel;
            dictParams.dictID = dictID;
            DiB_trainFromFiles(outFileName, maxDictSize, filenameTable, filenameIdx, &dictParams, NULL, 0);
        }
#endif
        goto _end;
    }

    /* No input filename ==> use stdin and stdout */
    filenameIdx += !filenameIdx;   /* filenameTable[0] is stdin by default */
    if (!strcmp(filenameTable[0], stdinmark) && !outFileName) outFileName = stdoutmark;   /* when input is stdin, default output is stdout */

    /* Check if input/output defined as console; trigger an error in this case */
    if (!strcmp(filenameTable[0], stdinmark) && IS_CONSOLE(stdin) ) CLEAN_RETURN(badusage(programName));
    if (outFileName && !strcmp(outFileName, stdoutmark) && IS_CONSOLE(stdout) && strcmp(filenameTable[0], stdinmark) && !(forceStdout && (operation==zom_decompress)))
        CLEAN_RETURN(badusage(programName));

    /* user-selected output filename, only possible with a single file */
    if (outFileName && strcmp(outFileName,stdoutmark) && strcmp(outFileName,nulmark) && (filenameIdx>1)) {
        DISPLAY("Too many files (%u) on the command line. \n", filenameIdx);
        CLEAN_RETURN(filenameIdx);
    }

#ifndef ZSTD_NOCOMPRESS
    /* check compression level limits */
    {   int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
        if (cLevel > maxCLevel) {
            DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
            cLevel = maxCLevel;
    }   }
#endif

    /* No status message in pipe mode (stdin - stdout) or multi-files mode */
    if (!strcmp(filenameTable[0], stdinmark) && outFileName && !strcmp(outFileName,stdoutmark) && (displayLevel==2)) displayLevel=1;
    if ((filenameIdx>1) & (displayLevel==2)) displayLevel=1;

    /* IO Stream/File */
    FIO_setNotificationLevel(displayLevel);
    if (operation==zom_compress) {
#ifndef ZSTD_NOCOMPRESS
        FIO_setNbThreads(nbThreads);
        FIO_setBlockSize((U32)blockSize);
        if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(g_overlapLog);
        if ((filenameIdx==1) && outFileName)
          operationResult = FIO_compressFilename(outFileName, filenameTable[0], dictFileName, cLevel, &compressionParams);
        else
          operationResult = FIO_compressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : ZSTD_EXTENSION, dictFileName, cLevel, &compressionParams);
#else
        DISPLAY("Compression not supported\n");
#endif
    } else {  /* decompression or test */
#ifndef ZSTD_NODECOMPRESS
        if (operation==zom_test) { outFileName=nulmark; FIO_setRemoveSrcFile(0); } /* test mode */
        FIO_setMemLimit(memLimit);
        if (filenameIdx==1 && outFileName)
            operationResult = FIO_decompressFilename(outFileName, filenameTable[0], dictFileName);
        else
            operationResult = FIO_decompressMultipleFilenames(filenameTable, filenameIdx, outFileName ? outFileName : ZSTD_EXTENSION, dictFileName);
#else
        DISPLAY("Decompression not supported\n");
#endif
    }

_end:
    if (main_pause) waitEnter();
#ifdef UTIL_HAS_CREATEFILELIST
    if (extendedFileList)
        UTIL_freeFileList(extendedFileList, fileNamesBuf);
    else
#endif
        free((void*)filenameTable);
    return operationResult;
}


text:
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Trix</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="csp-nonce" content="topsecret">
    <link rel="icon" href="data:,">
    <link rel="stylesheet" type="text/css" href="trix.css">
    <style type="text/css">
      * {
        box-sizing: border-box;
      }

      main {
        margin: 20px auto;
        max-width: 700px;
      }

      #output {
        margin: 1rem 0 0;
      }

      #output textarea {
        width: 100%;
        height: 6rem;
        resize: vertical;
        font-family: monospace;
        border-radius: 5px;
        border: solid 1px #444;
        padding: 10px;
      }
    </style>
    <script type="module" src="trix.esm.js"></script>
    <script type="module" src="inspector.js"></script>
    <script type="module">
      Trix.config.attachments.preview.caption.name = true
      Trix.config.attachments.preview.caption.size = false

      document.addEventListener("trix-initialize", function(event) {
        Trix.Inspector.install(event.target);
      });

      document.addEventListener("trix-attachment-add", function(event) {
        var attachment = event.attachment;
        if (attachment.file) {
          var xhr = new XMLHttpRequest;
          xhr.open("POST", "/attachments", true);

          xhr.upload.onprogress = function(event) {
            var progress = event.loaded / event.total * 100;
            attachment.setUploadProgress(progress);
          };

          xhr.onload = function() {
            if (xhr.status === 201) {
              setTimeout(function() {
                var url = xhr.responseText;
                attachment.setAttributes({ url: url, href: url });
              }, 30)
            }
          };

          attachment.setUploadProgress(10);

          setTimeout(function() {
            xhr.send(attachment.file);
          }, 30)
        }
      });
    </script>
  </head>
  <body>
    <main>
      <trix-editor autofocus class="trix-content" input="input"></trix-editor>
      <details id="output">
        <summary>Output</summary>
        <textarea readonly id="input"></textarea>
      </details>
    </main>
  </body>
</html>