text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.OpsWorks.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Update App Request Marshaller
    /// </summary>
    internal class UpdateAppRequestMarshaller : IMarshaller<IRequest, UpdateAppRequest>
    {

        public IRequest Marshall(UpdateAppRequest updateAppRequest)
        {

            IRequest request = new DefaultRequest(updateAppRequest, "AmazonOpsWorks");
            string target = "OpsWorks_20130218.UpdateApp";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";

            string uriResourcePath = "";

            if (uriResourcePath.Contains("?"))
            {
                string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
                uriResourcePath    = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));

                foreach (string s in queryString.Split('&', ';'))
                {
                    string[] nameValuePair = s.Split('=');
                    if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
                    {
                        request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
                    }
                    else
                    {
                        request.Parameters.Add(nameValuePair[0], null);
                    }
                }
            }

            request.ResourcePath = uriResourcePath;

            using (StringWriter stringWriter = new StringWriter())
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();

                if (updateAppRequest != null && updateAppRequest.IsSetAppId())
                {
                    writer.WritePropertyName("AppId");
                    writer.Write(updateAppRequest.AppId);
                }
                if (updateAppRequest != null && updateAppRequest.IsSetName())
                {
                    writer.WritePropertyName("Name");
                    writer.Write(updateAppRequest.Name);
                }
                if (updateAppRequest != null && updateAppRequest.IsSetDescription())
                {
                    writer.WritePropertyName("Description");
                    writer.Write(updateAppRequest.Description);
                }
                if (updateAppRequest != null && updateAppRequest.IsSetType())
                {
                    writer.WritePropertyName("Type");
                    writer.Write(updateAppRequest.Type);
                }

                if (updateAppRequest != null)
                {
                    Source appSource = updateAppRequest.AppSource;
                    if (appSource != null)
                    {
                        writer.WritePropertyName("AppSource");
                        writer.WriteObjectStart();
                        if (appSource != null && appSource.IsSetType())
                        {
                            writer.WritePropertyName("Type");
                            writer.Write(appSource.Type);
                        }
                        if (appSource != null && appSource.IsSetUrl())
                        {
                            writer.WritePropertyName("Url");
                            writer.Write(appSource.Url);
                        }
                        if (appSource != null && appSource.IsSetUsername())
                        {
                            writer.WritePropertyName("Username");
                            writer.Write(appSource.Username);
                        }
                        if (appSource != null && appSource.IsSetPassword())
                        {
                            writer.WritePropertyName("Password");
                            writer.Write(appSource.Password);
                        }
                        if (appSource != null && appSource.IsSetSshKey())
                        {
                            writer.WritePropertyName("SshKey");
                            writer.Write(appSource.SshKey);
                        }
                        if (appSource != null && appSource.IsSetRevision())
                        {
                            writer.WritePropertyName("Revision");
                            writer.Write(appSource.Revision);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                if (updateAppRequest != null && updateAppRequest.Domains != null && updateAppRequest.Domains.Count > 0)
                {
                    List<string> domainsList = updateAppRequest.Domains;
                    writer.WritePropertyName("Domains");
                    writer.WriteArrayStart();

                    foreach (string domainsListValue in domainsList)
                    {
                        writer.Write(StringUtils.FromString(domainsListValue));
                    }

                    writer.WriteArrayEnd();
                }
                if (updateAppRequest != null && updateAppRequest.IsSetEnableSsl())
                {
                    writer.WritePropertyName("EnableSsl");
                    writer.Write(updateAppRequest.EnableSsl);
                }

                if (updateAppRequest != null)
                {
                    SslConfiguration sslConfiguration = updateAppRequest.SslConfiguration;
                    if (sslConfiguration != null)
                    {
                        writer.WritePropertyName("SslConfiguration");
                        writer.WriteObjectStart();
                        if (sslConfiguration != null && sslConfiguration.IsSetCertificate())
                        {
                            writer.WritePropertyName("Certificate");
                            writer.Write(sslConfiguration.Certificate);
                        }
                        if (sslConfiguration != null && sslConfiguration.IsSetPrivateKey())
                        {
                            writer.WritePropertyName("PrivateKey");
                            writer.Write(sslConfiguration.PrivateKey);
                        }
                        if (sslConfiguration != null && sslConfiguration.IsSetChain())
                        {
                            writer.WritePropertyName("Chain");
                            writer.Write(sslConfiguration.Chain);
                        }
                        writer.WriteObjectEnd();
                    }
                }
                if (updateAppRequest != null)
                {
                    if (updateAppRequest.Attributes != null && updateAppRequest.Attributes.Count > 0)
                    {
                        writer.WritePropertyName("Attributes");
                        writer.WriteObjectStart();
                        foreach (string updateAppRequestAttributesKey in updateAppRequest.Attributes.Keys)
                        {
                            string attributesListValue;
                            bool attributesListValueHasValue = updateAppRequest.Attributes.TryGetValue(updateAppRequestAttributesKey, out attributesListValue);
                            writer.WritePropertyName(updateAppRequestAttributesKey);

                        writer.Write(attributesListValue);
                        }
                        writer.WriteObjectEnd();
                    }
                }

                writer.WriteObjectEnd();

                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Namespace danperron\danmvc\Core | danmvc</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

danperron

danmvc

Core

Config

Log

Http

PHP

Classes

Application

Controller

Filter

Input

Route

Router

Session

View

Exceptions

MvcException

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

Namespace

Class

				Tree

Namespace danperron\danmvc\Core

Namespaces summary

		danperron\danmvc\Core\Config

		danperron\danmvc\Core\Log

Classes summary

	Application
	Description of Application

	Controller
	Description of Controller

	Filter
	Description of Filter

	Input
	Handle input from request

	Route
	Description of Route

	Router
	Description of Router

	Session
	Description of Session

	View
	Description of View

Exceptions summary

	MvcException
	Description of MvcException

		danmvc API documentation generated by ApiGen 2.8.0


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

namespace Recorder.Converters
{
    public class TimespanToStringConverter:IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is TimeSpan))
            {
                return string.Empty;
            }

            var timespan = (TimeSpan) value;
            return $@"{timespan:hh\:mm\:ss\.ff}";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal">

        <me.itangqi.waveloadingview.WaveLoadingView
            android:id="@+id/progress_ring"
            android:layout_width="140dp"
            android:layout_height="140dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="32dp"
            android:layout_marginBottom="24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:wlv_borderColor="?android:colorSecondary"
            app:wlv_borderWidth="2dp"
            app:wlv_progressValue="0"
            app:wlv_shapeType="circle"
            app:wlv_titleBottomColor="?android:attr/colorAccent"
            app:wlv_titleBottomSize="14sp"
            app:wlv_titleBottomStrokeWidth="2dp"
            app:wlv_titleCenterColor="?android:attr/colorAccent"
            app:wlv_titleCenterSize="26sp"
            app:wlv_titleCenterStrokeWidth="2dp"
            app:wlv_waveAmplitude="30"
            app:wlv_waveColor="?android:attr/colorAccent" />

        <TextView
            android:id="@+id/non_bjut"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:paddingTop="8dp"
            android:paddingBottom="16dp"
            android:textSize="20sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/user"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="48dp"
            android:layout_marginTop="16dp"
            android:textSize="20sp"
            app:layout_constraintEnd_toStartOf="@id/guideline"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/time"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="48dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toStartOf="@id/guideline"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/user" />

        <TextView
            android:id="@+id/fee"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="48dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toStartOf="@id/guideline"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/time" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/sign_in_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="60dp"
            android:text="@string/action_sign_in"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/sign_out_button"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/fee" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/sign_out_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="5dp"
            android:minWidth="60dp"
            android:text="@string/action_sign_out"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/guideline"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/sign_in_button"
            app:layout_constraintTop_toBottomOf="@id/fee" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/info_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:constraint_referenced_ids="fee,time" />

        <androidx.constraintlayout.widget.Group
            android:id="@+id/buttons_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:constraint_referenced_ids="sign_out_button,sign_in_button" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>


text:
@implementation NSObject (PerformSel)

- (id)performSelector:(SEL)aSelector withParameters:(void *)firstParameter, ... {
    NSMethodSignature *signature = [self methodSignatureForSelector:aSelector];
    NSUInteger length = [signature numberOfArguments];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setTarget:self];
    [invocation setSelector:aSelector];

    [invocation setArgument:&firstParameter atIndex:2];
    va_list arg_ptr;
    va_start(arg_ptr, firstParameter);
    for (NSUInteger i = 3; i < length; ++i) {
        void *parameter = va_arg(arg_ptr, void *);
        [invocation setArgument:&parameter atIndex:i];
    }
    va_end(arg_ptr);

    [invocation invoke];

    if ([signature methodReturnLength]) {
        id data;
        [invocation getReturnValue:&data];
        return data;
    }
    return nil;
}

@end


text:
{{fields[field].name}}

{{users[$stateParams.user_id].data[field].value}}

NO DATA!


text:
#ifndef NEW_APPLELAYOUT_H
#define NEW_APPLELAYOUT_H
#include "../common/AppleLayout.h"
#include <iterator>

struct method_t
{
	const char* selName;
	const char* types;
	void* impl;
};

struct method_list_t
{
	uint32_t entsize_and_flags;
	uint32_t count;
	method_t method_list[];

	uint32_t entsize() const { return entsize_and_flags & ~uint32_t(3); }
};

struct ivar_t
{
	uintptr_t* offset;
	const char* name;
	const char* type;
	uint32_t alignment, size;
};

struct ivar_list_t
{
	uint32_t entsize, count;
	ivar_t ivar_list[];
};

struct protocol_list_t;
struct property_list_t;
struct protocol_t
{
	id isa;
	const char* name;
	protocol_list_t* protocols; // inherited protocols
	method_list_t *methods, *staticMethods, *optMethods, *optStaticMethods;
	property_list_t* properties;
	uint32_t size, flags;
	const char** extMethTypes; // reflects the order and count of methods above as listed in this struct

	inline const protocol_t* next() const
	{
		uintptr_t ptr = reinterpret_cast<uintptr_t>(this);
		ptr += size;
		return reinterpret_cast<const protocol_t*>(ptr);
	}
};

template <typename ProtoList>
class protocol_iterator : public std::iterator<std::input_iterator_tag, const protocol_t*>
{
	const ProtoList* m_list;
	size_t m_index;
	intptr_t m_slide;
public:
	protocol_iterator(const ProtoList* list, size_t index, intptr_t slide) : m_list(list), m_index(index), m_slide(slide) {}
	protocol_iterator(const protocol_iterator& that) : m_list(that.m_list), m_index(that.m_index), m_slide(that.m_slide) {}
	protocol_iterator& operator++() { m_index++; return *this; }
	bool operator==(const protocol_iterator& that) { return that.m_index == m_index; }
	bool operator!=(const protocol_iterator& that) { return that.m_index != m_index; }
	const protocol_t* operator*() { return m_list->elem(m_index, m_slide); }
};

struct protocol_list_t
{
	uintptr_t count;
	uintptr_t list[]; // the compiler doesn't add a rebase here
	inline const protocol_t* elem(size_t i, uintptr_t slide) const
	{
		return reinterpret_cast<const protocol_t*>(list[i] + 0);
	}
	protocol_iterator<protocol_list_t> begin(intptr_t slide) const { return protocol_iterator<protocol_list_t>(this, 0, 0); }
	protocol_iterator<protocol_list_t> end(intptr_t slide) const { return protocol_iterator<protocol_list_t>(this, count, 0); }
};

struct property_t
{
	const char *name, *attributes;
};

struct property_list_t
{
	uint32_t entsize, count;
	property_t list[];
};

struct class_ro_t
{
	uint32_t flags, instStart, instSize;
#ifdef __x86_64__
	uint32_t nothing;
#endif
	void* ivarLayout;
	const char* className;
	const method_list_t* baseMethods; // instance methods for classes, static methods for metaclasses
	const protocol_list_t* baseProtocols;
	const ivar_list_t* ivars;

	void* todo[1]; // TODO: more pointers
	const property_list_t* baseProperties;
};

struct class_t
{
	class_t* isa; // instance of
	class_t* superclass;
	void* cache; // empty cache imported here
	void* vtable;
	uintptr_t data_and_flags;

	class_ro_t* data() const
	{
		uintptr_t p = data_and_flags & ~uintptr_t(3);
		return reinterpret_cast<class_ro_t*>(p);
	}
};

struct category_t
{
	const char* name;
	id cls;
	method_list_t *methods, *staticMethods;
	protocol_list_t *protocols;
	property_list_t *properties;
};

#ifndef CLS_CLASS
#define CLS_CLASS               0x1
#define CLS_META                0x2
#define CLS_POSING              0x8
#define CLS_METHOD_ARRAY        0x100
#define CLS_HAS_CXX_STRUCTORS   0x2000
#define CLS_NO_METHOD_ARRAY     0x4000
#define CLS_HAS_LOAD_METHOD     0x8000
#define CLS_NO_PROPERTY_ARRAY	0x80000
#endif

static const char* SEG_DATA = "__DATA";
static const char* SEG_OBJC_CLASSLIST_NEW = SEG_DATA;
static const char* SECT_OBJC_CLASSLIST_NEW = "__objc_classlist";
static const char* SEG_OBJC_CLASSREFS_NEW = SEG_DATA;
static const char* SECT_OBJC_CLASSREFS_NEW = "__objc_classrefs";
static const char* SEG_OBJC_SUPERREFS_NEW = SEG_DATA;
static const char* SECT_OBJC_SUPERREFS_NEW = "__objc_superrefs";
static const char* SEG_OBJC_SELREFS_NEW = SEG_DATA;
static const char* SECT_OBJC_SELREFS_NEW = "__objc_selrefs";
static const char* SEG_OBJC_MSGREFS_NEW = SEG_DATA; // used with objc_msgSend_fixup
static const char* SECT_OBJC_MSGREFS_NEW = "__objc_msgrefs";
static const char* SEG_OBJC_PROTOREFS_NEW = SEG_DATA;
static const char* SECT_OBJC_PROTOREFS_NEW = "__objc_protorefs";
static const char* SEG_OBJC_PROTOLIST_NEW = SEG_DATA;
static const char* SECT_OBJC_PROTOLIST_NEW = "__objc_protolist";
static const char* SEG_OBJC_CATLIST_NEW = SEG_DATA;
static const char* SECT_OBJC_CATLIST_NEW = "__objc_catlist";

/* TODO?
 * __DATA,__objc_classlist  was __OBJC2,__class_list
 * __DATA,__objc_catlist  was __OBJC2,__category_list
 * __DATA,__objc_protolist  was __OBJC2,__protocol_list
 * __DATA,__objc_msgrefs  was __OBJC2,__message_refs
 * __DATA,__objc_classrefs  was __OBJC2,__class_refs
 * __DATA,__objc_superrefs  was __OBJC2,__super_refs
 * __DATA,__objc_imageinfo  was __OBJC,__image_info
 * */

#endif


text:
//
//  ___FILENAME___
//  ___PROJECTNAME___
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//___COPYRIGHT___
//

#import "___FILEBASENAME___.h"

@implementation ___FILEBASENAMEASIDENTIFIER___

- (void)awakeFromNib
{
    [super awakeFromNib];
    // Additional configuration
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
package net.caseif.voxem;

import net.caseif.voxem.entity.Entity;
import net.caseif.voxem.entity.living.Mob;
import net.caseif.voxem.entity.living.player.Player;
import net.caseif.voxem.threading.Scheduler;
import net.caseif.voxem.util.Timing;
import net.caseif.voxem.vector.Vector3f;
import net.caseif.voxem.world.Block;
import net.caseif.voxem.world.SaveManager;
import net.caseif.voxem.world.TickManager;
import net.caseif.voxem.world.World;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;

public class Main {

    public static World world = null;

    public static Player player;

    public static boolean closed = false;

    public static final Object lock = new Object();

    public static GameState state = GameState.MAIN_MENU;

    public static int charTexture;

    public static int dank = -1;

    public static void main(String[] args) {

        boolean launchedProperly = true;
        try {
            // verify libraries are present and LWJGL is in path
            for (DisplayMode mode : Display.getAvailableDisplayModes()) {
                if (mode.getWidth() == Display.getDesktopDisplayMode().getWidth() &&
                        mode.getHeight() == Display.getDesktopDisplayMode()
                                .getHeight() && mode.isFullscreenCapable()) {
                    Display.setDisplayMode(mode);
                    break;
                }
            }
            Display.destroy();
        } catch (Exception ex) {
            ex.printStackTrace();
            launchedProperly = false;
        }
        if (!launchedProperly) {
            new DummyMain();
            return;
        }

        Thread t = new Thread(new GraphicsHandler());
        t.start();

        InputManager.initialize();
        Mob.initialize();
        SoundManager.initialize();

        while (!closed) {
            Timing.calculateDelta();
            Scheduler.checkTasks();
            InputManager.manage();
            if (world != null && player != null) {
                Player.calculateLight();
                TickManager.checkForTick();
                for (Entity e : player.getLevel().getEntities()) {
                    e.manageMovement();
                }
                Block.updateSelectedBlock();
            }
            Timing.throttleCpu();
        }
        SoundManager.soundSystem.cleanup();
        if (world != null) {
            SaveManager.writeWorldToDisk(world);
        }

    }

}


text:
package org.odmg;

/**
 * The interface that defines the operations of an ODMG array.
 * Nearly all of its operations are defined by the JavaSoft List interface.
 * All of the operations defined by the JavaSoft List
 * interface are supported by an ODMG implementation of DArray,
 * the exception UnsupportedOperationException is not thrown when a
 * call is made to any of the List methods.
 * An instance of a class implementing this interface can be obtained
 * by calling the method Implementation.newDArray.
 * @author	David Jordan (as Java Editor of the Object Data Management Group)
 * @version ODMG 3.0
 */
// @see java.lang.UnsupportedOperationException

public interface DArray extends org.odmg.DCollection, java.util.List
{
    /**
     * Resize the array to have newSize elements.
     * @param	newSize	The new size of the array.
     */
    public void resize(int newSize);
}


text:
<?php

declare(strict_types=1);

namespace Spiral\Tests\Boot\Fixtures;

use Spiral\Config\Loader\FileLoaderInterface;

class TestLoader implements FileLoaderInterface
{
    public function loadFile(string $section, string $filename): array
    {
        return [
            'test-key' => 'test value',
        ];
    }
}


text:
/*
 * Input File Description:
 * The input file can be an output of dcmdump.  One element (tag, VR, value)
 * must be written into one line separated by arbitrary spaces or tab characters.
 * A '#' begins a comment that ends at the line end.  Empty lines are allowed.
 * The individual parts of a line have the following syntax:
 * Tag:   (gggg,eeee)
 *        with gggg and eeee are 4 character hexadecimal values representing
 *        group and element tag.  Spaces and tabs can be anywhere in a tag
 *        specification.
 * VR:    Value Representation must be written as 2 characters as in Part 6
 *        of the DICOM standard.  No spaces or tabs are allowed between the
 *        two characters.  If the VR can determined from the tag, this part
 *        of a line is optional.
 * Value: There are several rules for writing values:
 *        1. US, SS, SL, UL, FD, FL, OD, OF and OL are written as decimal
 *           strings that can be read by scanf().
 *        2. AT is written as '(gggg,eeee)' with additional spaces stripped
 *           off automatically and gggg and eeee being decimal strings that
 *           can be read by scanf().
 *        3. OB and OW values are written as byte or word hexadecimal values
 *           separated by '\' character.  Alternatively, OB or OW values can
 *           be read from a separate file by writing the filename prefixed
 *           by a '=' character (e.g. '=largepix.dat').  The contents of the
 *           file will be read as is.  By default, OW data is expected to be
 *           little endian ordered and will be swapped if necessary.  No
 *           checks will be made to ensure that the amount of data is
 *           reasonable in terms of other attributes such as Rows or Columns.
 *           In case of compressed pixel data, the line should start with
 *           '(7fe0,0010) OB (PixelSequence' in order to distinguish from
 *           uncompressed pixel data.
 *        4. UI is written as '=Name' in data dictionary or as unique
 *           identifier string (see 6.) , e.g. '[1.2.840.....]'
 *        5. Strings without () <> [] spaces, tabs and # can be written
 *           directly.
 *        6. Other strings must be surrounded by '[' and ']'.  No bracket
 *           structure is passed.  The value ends at the last ']' in the
 *           line.  Anything after the ']' is interpreted as comment.
 *        7. '(' and '<' are interpreted special and may not be used when
 *           writing an input file by hand as beginning characters of a
 *           string.  Multiple Value are separated by '\'.  The sequence of
 *           lines must not be ordered but they can.  References in DICOM
 *           Directories are not supported.  Semantic errors are not detected.
 *
 * Examples:
 *  (0008,0020) DA  [19921012]          #     8,  1  StudyDate
 *  (0008,0016) UI  =MRImageStorage     #    26,  1  SOPClassUID
 *  (0002,0012) UI  [1.2.276.0.7230010.100.1.1]
 *  (0020,0032) DS  [0.0\0.0]           #     8,  2  ImagePositionPatient
 *  (0028,0009) AT  (3004,000c)         #     4,  1  FrameIncrementPointer
 *  (0028,0010) US  256                 #     4,  1  Rows
 *  (0002,0001) OB  01\00
 *
 */

#include "dcmtk/config/osconfig.h"

// if defined, use createValueFromTempFile() for large binary data files
//#define EXPERIMENTAL_READ_FROM_FILE

#define INCLUDE_CSTDLIB
#define INCLUDE_CSTDIO
#define INCLUDE_CCTYPE
#include "dcmtk/ofstd/ofstdinc.h"

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_GUSI_H
#include <GUSI.h>
#endif

#include "dcmtk/ofstd/ofstd.h"
#include "dcmtk/ofstd/ofconapp.h"
#include "dcmtk/ofstd/ofstream.h"
#include "dcmtk/dcmdata/dctk.h"
#include "dcmtk/dcmdata/dcpxitem.h"
#include "dcmtk/dcmdata/cmdlnarg.h"
#include "dcmtk/dcmdata/dcuid.h"     /* for dcmtk version name */
#include "dcmtk/dcmdata/dcostrmz.h"  /* for dcmZlibCompressionLevel */

#ifdef EXPERIMENTAL_READ_FROM_FILE
#include "dcmtk/dcmdata/dcistrmf.h"  /* for class DcmInputFileStream */
#endif

#ifdef WITH_ZLIB
#include <zlib.h>                    /* for zlibVersion() */
#endif

#define OFFIS_CONSOLE_APPLICATION "dump2dcm"

static OFLogger dump2dcmLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION);

static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v"
  OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $";

#define SHORTCOL 3
#define LONGCOL 21

// Maximum Line Size (default)

const unsigned int DCM_DumpMaxLineSize = 4096;

// Global variables

static E_ByteOrder opt_fileContentsByteOrdering = EBO_LittleEndian;

// Field definition separators

#define DCM_DumpCommentChar '#'
#define DCM_DumpTagDelim ')'
#define DCM_DumpOpenString '['
#define DCM_DumpCloseString ']'
#define DCM_DumpOpenDescription '('
#define DCM_DumpOpenFile '<'
#define DCM_DumpCloseFile '>'

#define TO_UCHAR(s) OFstatic_cast(unsigned char, (s))
static void
stripWhitespace(char *s)
{
    char *p;

    if (s == NULL) return;

    p = s;
    while (*s != '\0') {
        if (isspace(TO_UCHAR(*s)) == OFFalse) {
            *p++ = *s;
        }
        s++;
    }
    *p = '\0';
}

static char *
stripTrailingWhitespace(char *s)
{
    if (s == NULL) return s;
    for (size_t i = strlen(s); i > 0 && isspace(TO_UCHAR(s[--i])); s[i] = '\0');
    return s;
}

static char *
stripPrecedingWhitespace(char *s)
{
    char *p;
    if (s == NULL) return s;

    for(p = s; *p && isspace(TO_UCHAR(*p)); p++)
        ;

    return p;
}

static OFBool
onlyWhitespace(const char *s)
{
    while(*s) if (!isspace(TO_UCHAR(*s++)))
        return OFFalse;
    return OFTrue;
}

static char *
getLine(char *line, int maxLineLen, FILE *f, const unsigned long lineNumber)
{
    char *s;

    s = fgets(line, maxLineLen, f);

    // if line is too long, throw rest of it away
    if (s && strlen(s) == size_t(maxLineLen - 1) && s[maxLineLen - 2] != '\n')
    {
        int c = fgetc(f);
        while(c != '\n' && c != EOF)
            c = fgetc(f);
        OFLOG_ERROR(dump2dcmLogger, "line " << lineNumber << " too long");
    }

    /* strip any trailing white space */
    stripTrailingWhitespace(s);

    return s;
}

static OFBool
isaCommentLine(const char *s)
{
    // skip leading spaces
    while(isspace(TO_UCHAR(*s))) ++s;
    return *s == DCM_DumpCommentChar;
}

static OFBool
parseTag(char *&s, DcmTagKey &key)
{
    OFBool ok = OFTrue;
    char *p;
    unsigned int g, e;

    // find tag begin
    p = strchr(s, DCM_DumpTagDelim);
    if (p)
    {
        // string all white spaces and read tag
        size_t len = p - s + 1;
        p = new char[len + 1];
        OFStandard::strlcpy(p, s, len + 1);
        stripWhitespace(p);
        s += len;

        if (sscanf(p, "(%x,%x)", &g, &e) == 2)
            key.set(OFstatic_cast(Uint16, g), OFstatic_cast(Uint16, e));
        else
            ok = OFFalse;
        delete[] p;
    }
        else ok = OFFalse;

    return ok;
}

static OFBool
parseVR(char *&s, DcmEVR &vr)
{
    OFBool ok = OFTrue;

    s = stripPrecedingWhitespace(s);

    // Are there two upper characters?
    if (isupper(TO_UCHAR(*s)) && isupper(TO_UCHAR(*(s + 1))))
    {
        char c_vr[3];
        OFStandard::strlcpy(c_vr, s, 3);
        // Convert to VR
        DcmVR dcmVR(c_vr);
        vr = dcmVR.getEVR();
        s += 2;
    }
    else if ((*s == 'p') && (*(s + 1) == 'i'))
    {
        vr = EVR_pixelItem;
        s += 2;
    }
    else if (((*s == 'o') && (*(s + 1) == 'x')) ||
        ((*s == 'x') && (*(s + 1) == 's')) ||
        ((*s == 'n') && (*(s + 1) == 'a')) ||
        ((*s == 'u') && (*(s + 1) == 'p')))
    {
        // swallow internal VRs
        vr = EVR_UNKNOWN;
        s += 2;
    }
    else ok = OFFalse;

    return ok;
}
#undef TO_UCHAR

static size_t
searchLastClose(char *s, const char closeChar)
{
    // search last close bracket in a line
    // no bracket structure will be considered

    char *found = NULL;
    char *p = s;

    while(p && *p)
    {
        p = strchr(p, closeChar);
        if (p)
        {
            found = p;
            p++;
        }
    }

    if (found)
        return (found - s) + 1;
    else
        return 0;
}

static size_t
searchCommentOrEol(char *s)
{
    char *comment = strchr(s, DCM_DumpCommentChar);
    if (comment)
        return comment - s;
    else if (s)
        return strlen(s);
    else
        return 0;
}

static void
convertNewlineCharacters(char *s)
{
    // convert the string "\n" into the \r\n combination required by DICOM
    if (s) for (; *s; ++s) if (*s == '\\' && *(s+1) == 'n')
    {
        *s = '\r';
        *++s = '\n';
    }
}

static OFBool
parseValue(char *&s, char *&value, DcmEVR &vr, const DcmTagKey &tagkey)
{
    OFBool ok = OFTrue;
    size_t len;
    value = NULL;

    s = stripPrecedingWhitespace(s);

    switch (*s)
    {
        case DCM_DumpOpenString:
            len = searchLastClose(s, DCM_DumpCloseString);
            if (len == 0)
                ok = OFFalse;
            else if (len > 2)
            {
                value = new char[len - 1];
                OFStandard::strlcpy(value, s + 1, len - 1);
                convertNewlineCharacters(value);
            }
            else
                value = NULL;
            break;

        case DCM_DumpOpenDescription:
            /* need to distinguish VR=AT from description field */
            /* NB: if the VR is unknown this workaround will not succeed */
            if (vr == EVR_AT)
            {
                len = searchLastClose(s, DCM_DumpTagDelim);
                if (len >= 11)  // (gggg,eeee) allow non-significant spaces
                {
                    char *pv = s;
                    DcmTagKey tag;
                    if (parseTag(pv, tag))   // check for valid tag format
                    {
                        value = new char[len + 1];
                        OFStandard::strlcpy(value, s, len + 1);
                        stripWhitespace(value);
                    } else
                        ok = OFFalse;   // skip description
                }
                else
                    ok = OFFalse;   // skip description
            }
            /* need to distinguish pixel sequence */
            else if ((tagkey == DCM_PixelData) && (vr == EVR_OB))
            {
                if (strncmp(s + 1, "PixelSequence", 13) == 0)
                    vr = EVR_pixelSQ;
            }
            break;

        case DCM_DumpOpenFile:
            ok = OFFalse;  // currently not supported
            break;

        case DCM_DumpCommentChar:
            break;

        default:
            len = searchCommentOrEol(s);
            if (len)
            {
                value = new char[len + 1];
                OFStandard::strlcpy(value, s, len + 1);
                stripTrailingWhitespace(value);
            }
            break;
    }
    return ok;
}

static OFCondition
putFileContentsIntoElement(DcmElement *elem, const char *filename)
{
    OFCondition ec = EC_Normal;
#ifdef EXPERIMENTAL_READ_FROM_FILE
    /* create stream object for binary file */
    DcmInputFileStream fileStream(filename);
    ec = fileStream.status();
    if (ec.good())
    {
        /* NB: if size is odd file will be rejected */
        const size_t fileLen = OFStandard::getFileSize(filename);
        /* read element value from binary file (requires even length) */
        ec = elem->createValueFromTempFile(fileStream.newFactory(), fileLen, EBO_LittleEndian);
        if (ec.bad())
            OFLOG_ERROR(dump2dcmLogger, "cannot process binary data file: " << filename);
    } else {
        OFLOG_ERROR(dump2dcmLogger, "cannot open binary data file: " << filename);
        ec = EC_InvalidTag;
    }
#else
    FILE *f = NULL;
    if ((f = fopen(filename, "rb")) == NULL)
    {
        OFLOG_ERROR(dump2dcmLogger, "cannot open binary data file: " << filename);
        return EC_InvalidTag;
    }

    const size_t len = OFStandard::getFileSize(filename);
    size_t buflen = len;
    if (buflen & 1)
        buflen++; /* if odd then make even (DICOM requires even length values) */

    Uint8 *buf = NULL;
    const DcmEVR evr = elem->getVR();
    /* create buffer of OB or OW data */
    if (evr == EVR_OB || evr == EVR_pixelItem)
        ec = elem->createUint8Array(OFstatic_cast(Uint32, buflen), buf);
    else if (evr == EVR_OW)
    {
        Uint16 *buf16 = NULL;
        ec = elem->createUint16Array(OFstatic_cast(Uint32, buflen / 2), buf16);
        buf = OFreinterpret_cast(Uint8 *, buf16);
    } else
        ec = EC_IllegalCall;
    if (ec.good())
    {
        /* read binary file into the buffer */
        if (fread(buf, 1, len, f) != len)
        {
            char errBuf[256];
            OFLOG_ERROR(dump2dcmLogger, "error reading binary data file: " << filename
                << ": " << OFStandard::strerror(errno, errBuf, sizeof(errBuf)));
            ec = EC_CorruptedData;
        }
        else if (evr == EVR_OW)
        {
            /* swap 16 bit OW data (if necessary) */
            swapIfNecessary(gLocalByteOrder, opt_fileContentsByteOrdering, buf, OFstatic_cast(Uint32, buflen), sizeof(Uint16));
        }
    }
    else if (ec == EC_MemoryExhausted)
        OFLOG_ERROR(dump2dcmLogger, "out of memory reading binary data file: " << filename);
    else
        OFLOG_ERROR(dump2dcmLogger, "illegal call processing binary data file: " << filename);

    fclose(f);
#endif
    return ec;
}

static OFCondition
insertIntoSet(DcmStack &stack, const E_TransferSyntax xfer, const DcmTagKey &tagkey,
              const DcmEVR &vr, const char *value)
{
    // insert new element into dataset or metaheader

    OFCondition l_error = EC_Normal;
    OFCondition newElementError = EC_Normal;

    if (stack.empty())
        l_error = EC_CorruptedData;

    if (l_error == EC_Normal)
    {
        DcmElement *newElement = NULL;
        DcmObject *topOfStack = stack.top();

        // convert tagkey to tag including VR
        DcmTag tag(tagkey);
        DcmVR dcmvr(vr);

        const DcmEVR tagvr = tag.getEVR();
        /* check VR and consider various special cases */
        if (tagvr != vr && vr != EVR_UNKNOWN && tagvr != EVR_UNKNOWN &&
           (tagkey != DCM_LUTData || (vr != EVR_US && vr != EVR_SS && vr != EVR_OW)) &&
           (tagkey != DCM_PixelData || (vr != EVR_OB && vr != EVR_OW && vr != EVR_pixelSQ)) &&
           (tagvr != EVR_xs || (vr != EVR_US && vr != EVR_SS)) &&
           (tagvr != EVR_ox || (vr != EVR_OB && vr != EVR_OW)) &&
           (tagvr != EVR_na || vr != EVR_pixelItem))
        {
            OFLOG_WARN(dump2dcmLogger, "Tag " << tag << " with wrong VR '"
                << dcmvr.getVRName() << "' found, correct is '"
                << tag.getVR().getVRName() << "'");
        }
        else if ((tagvr == EVR_UNKNOWN) && (vr == EVR_UNKNOWN))
        {
            OFLOG_WARN(dump2dcmLogger, "VR of Tag " << tag << " is unknown, "
                << "using 'UN' for this data element");
        }

        if (vr != EVR_UNKNOWN)
            tag.setVR(dcmvr);
        const DcmEVR newTagVR = tag.getEVR();

        // create new element (special handling for pixel sequence and item)
        if (newTagVR == EVR_pixelSQ)
            newElement = new DcmPixelData(tag);
        else if (newTagVR == EVR_pixelItem)
            newElement = new DcmPixelItem(DCM_PixelItemTag);
        else
            newElementError = newDicomElement(newElement, tag);

        if (newElementError == EC_Normal)
        {
            // tag describes an element
            if (!newElement)
            {
                // Tag was ambiguous - should never happen according to the current implementation of newDicomElement()
                l_error = EC_InvalidVR;
            }
            else
            {
                // check for uncompressed pixel data (i.e. no pixel sequence present)
                if (tagkey == DCM_PixelData  && (newTagVR == EVR_OB || newTagVR == EVR_OW))
                    OFstatic_cast(DcmPixelData *, newElement)->setNonEncapsulationFlag(OFTrue /*alwaysUnencapsulated*/);
                // fill value
                if (value)
                {
                    if (value[0] == '=' && (newTagVR == EVR_OB || newTagVR == EVR_OW || newTagVR == EVR_pixelItem))
                    {
                        /*
                         * Special case handling for OB, OW and pixel item data.
                         * Allow a value beginning with a '=' character to represent
                         * a file containing data to be used as the attribute value.
                         * A '=' character is not a normal value since OB and OW values
                         * must be written as multivalued hexadecimal (e.g. "00\ff\0d\8f");
                         */
                        l_error = putFileContentsIntoElement(newElement, value + 1);
                    } else {
                        l_error = newElement->putString(value);
                    }
                }

                // insert element into hierarchy
                if (l_error == EC_Normal)
                {
                    switch(topOfStack->ident())
                    {
                      case EVR_item:
                      case EVR_dirRecord:
                      case EVR_dataset:
                      case EVR_metainfo:
                          {
                              DcmItem *item = OFstatic_cast(DcmItem *, topOfStack);
                              item->insert(newElement);
                              // special handling for pixel sequence
                              if (newTagVR == EVR_pixelSQ)
                              {
                                  DcmPixelSequence *pixelSeq = new DcmPixelSequence(DCM_PixelSequenceTag);
                                  if (pixelSeq != NULL)
                                  {
                                      OFstatic_cast(DcmPixelData *, newElement)->putOriginalRepresentation(xfer, NULL, pixelSeq);
                                      stack.push(pixelSeq);
                                  }
                              }
                              else if (newElement->ident() == EVR_SQ)
                                  stack.push(newElement);
                          }
                          break;
                      case EVR_pixelSQ:
                          if (newTagVR == EVR_pixelItem)
                          {
                              DcmPixelSequence *pixelSeq = OFstatic_cast(DcmPixelSequence *, topOfStack);
                              pixelSeq->insert(OFstatic_cast(DcmPixelItem *, newElement));
                          } else
                              l_error = EC_InvalidTag;
                          break;
                      default:
                          l_error = EC_InvalidTag;
                      break;
                    }
                }
            }
        }
        else if (newElementError == EC_SequEnd)
        {
            // pop stack if stack object was a sequence
            if (topOfStack->ident() == EVR_SQ || topOfStack->ident() == EVR_pixelSQ)
                stack.pop();
            else
                l_error = EC_InvalidTag;
        }
        else if (newElementError == EC_ItemEnd)
        {
            // pop stack if stack object was an item
            switch (topOfStack->ident())
            {
              case EVR_item:
              case EVR_dirRecord:
              case EVR_dataset:
              case EVR_metainfo:
                  stack.pop();
                  break;

              default:
                  l_error = EC_InvalidTag;
                  break;
            }
        }
        else if (newElementError == EC_InvalidTag)
        {
            if (tag.getXTag() == DCM_Item)
            {
                DcmItem *item = NULL;
                if (topOfStack->getTag().getXTag() == DCM_DirectoryRecordSequence)
                {
                    // an Item must be pushed to the stack
                    item = new DcmDirectoryRecord(tag, 0);
                    OFstatic_cast(DcmSequenceOfItems *, topOfStack)->insert(item);
                    stack.push(item);
                }
                else if (topOfStack->ident() == EVR_SQ)
                {
                    // an item must be pushed to the stack
                    item = new DcmItem(tag);
                    OFstatic_cast(DcmSequenceOfItems *, topOfStack)->insert(item);
                    stack.push(item);
                }
                else
                    l_error = EC_InvalidTag;
            }
            else
                l_error = EC_InvalidTag;
        }
        else
            l_error = EC_InvalidTag;
    }

    return l_error;
}

static OFBool
readDumpFile(DcmMetaInfo *metaheader, DcmDataset *dataset,
             FILE *infile, const char *ifname, E_TransferSyntax &xfer,
             const OFBool stopOnErrors, const unsigned long maxLineLength)
{
    char *lineBuf = new char[maxLineLength];
    int lineNumber = 0;
    OFBool errorOnThisLine = OFFalse;
    char *parse = NULL;
    char *value = NULL;
    DcmEVR vr = EVR_UNKNOWN;
    int errorsEncountered = 0;
    DcmTagKey tagkey;
    DcmStack metaheaderStack;
    DcmStack datasetStack;
    xfer = EXS_Unknown;

    if (metaheader)
        metaheaderStack.push(metaheader);

    datasetStack.push(dataset);

    while (getLine(lineBuf, OFstatic_cast(int, maxLineLength), infile, lineNumber + 1))
    {
        lineNumber++;

        OFLOG_TRACE(dump2dcmLogger, "processing line " << lineNumber << " of the input file");

        // ignore empty lines and comment lines
        if (onlyWhitespace(lineBuf))
            continue;
        if (isaCommentLine(lineBuf))
            continue;

        errorOnThisLine = OFFalse;

        parse = &lineBuf[0];

        // parse tag an the line
        if (!parseTag(parse, tagkey))
        {
            OFLOG_ERROR(dump2dcmLogger, OFFIS_CONSOLE_APPLICATION ": "<< ifname << ": "
                << "no Tag found (line " << lineNumber << ")");
            errorOnThisLine = OFTrue;
        }

        // parse optional VR
        if (!errorOnThisLine && !parseVR(parse, vr))
            vr = EVR_UNKNOWN;

        // parse optional value
        if (!errorOnThisLine && !parseValue(parse, value, vr, tagkey))
        {
            OFLOG_ERROR(dump2dcmLogger, OFFIS_CONSOLE_APPLICATION ": "<< ifname << ": "
                << "incorrect value specification (line " << lineNumber << ")");
            errorOnThisLine = OFTrue;
        }

        // insert new element that consists of tag, VR, and value
        if (!errorOnThisLine)
        {
            OFCondition l_error = EC_Normal;
            if (tagkey.getGroup() == 0x0002)
            {
                if (metaheader)
                {
                    l_error = insertIntoSet(metaheaderStack, xfer, tagkey, vr, value);
                    // check for transfer syntax in meta-header
                    if ((tagkey == DCM_TransferSyntaxUID) && (xfer == EXS_Unknown))
                    {
                        const char *xferUID;
                        // use resolved value (UID)
                        if (metaheader->findAndGetString(DCM_TransferSyntaxUID, xferUID).good())
                            xfer = DcmXfer(xferUID).getXfer();
                    }
                }
            }
            else
                l_error = insertIntoSet(datasetStack, xfer, tagkey, vr, value);

            if (value)
            {
                delete[] value;
                value = NULL;
            }
            if (l_error != EC_Normal)
            {
                errorOnThisLine = OFTrue;
                OFLOG_ERROR(dump2dcmLogger, OFFIS_CONSOLE_APPLICATION ": " << ifname << ": Error in creating Element: "
                    << l_error.text() << " (line " << lineNumber << ")");
            }

        }

        if (errorOnThisLine)
            errorsEncountered++;
    }

    // test blocking structure
    if (metaheader && metaheaderStack.card() != 1)
    {
        OFLOG_ERROR(dump2dcmLogger, OFFIS_CONSOLE_APPLICATION ": " << ifname << ": Block Error in metaheader");
        errorsEncountered++;
    }

    if (datasetStack.card() != 1)
    {
        OFLOG_ERROR(dump2dcmLogger, OFFIS_CONSOLE_APPLICATION ": " << ifname << ": Block Error in dataset");
        errorsEncountered++;
    }

    delete[] lineBuf;

    if (errorsEncountered)
    {
        OFLOG_ERROR(dump2dcmLogger, errorsEncountered << " Errors found in " <<  ifname);
        return !stopOnErrors;
    }
    else
        return OFTrue;
}

// ********************************************

int main(int argc, char *argv[])
{
#ifdef HAVE_GUSI_H
    GUSISetup(GUSIwithSIOUXSockets);
    GUSISetup(GUSIwithInternetSockets);
#endif

    OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION , "Convert ASCII dump to DICOM file", rcsid);
    OFCommandLine cmd;

    cmd.setOptionColumns(LONGCOL, SHORTCOL);
    cmd.setParamColumn(LONGCOL + SHORTCOL + 4);

    cmd.addParam("dumpfile-in", "dump input filename");
    cmd.addParam("dcmfile-out", "DICOM output filename");

    cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2);
     cmd.addOption("--help",                   "-h",     "print this help text and exit", OFCommandLine::AF_Exclusive);
     cmd.addOption("--version",                          "print version information and exit", OFCommandLine::AF_Exclusive);
     OFLog::addOptions(cmd);

    cmd.addGroup("input options:", LONGCOL, SHORTCOL + 2);
      cmd.addSubGroup("input file format:");
        cmd.addOption("--read-meta-info",      "+f",     "read meta information if present (default)");
        cmd.addOption("--ignore-meta-info",    "-f",     "ignore file meta information");
      cmd.addSubGroup("file contents byte ordering:");
        cmd.addOption("--read-file-little",    "+rl",    "read OW data with little endian (default)");
        cmd.addOption("--read-file-big",       "+rb",    "read OW data from file with big endian");
      cmd.addSubGroup("other input options:");
        cmd.addOption("--line",                "+l",  1, "[m]ax-length: integer",
                                                         "maximum line length m (default: 4096)");

    cmd.addGroup("processing options:");
      cmd.addSubGroup("unique identifiers:");
        cmd.addOption("--generate-new-uids",   "+Ug",    "generate new Study/Series/SOP Instance UID");
        cmd.addOption("--dont-overwrite-uids", "-Uo",    "do not overwrite existing UIDs (default)");
        cmd.addOption("--overwrite-uids",      "+Uo",    "overwrite existing UIDs");

    cmd.addGroup("output options:");
      cmd.addSubGroup("output file format:");
        cmd.addOption("--write-file",          "+F",     "write file format (default)");
        cmd.addOption("--write-dataset",       "-F",     "write data set without file meta information");
        cmd.addOption("--update-meta-info",    "+Fu",    "update particular file meta information");
      cmd.addSubGroup("output transfer syntax:");
        cmd.addOption("--write-xfer-same",     "+t=",    "write with same TS as input (default)");
        cmd.addOption("--write-xfer-little",   "+te",    "write with explicit VR little endian");
        cmd.addOption("--write-xfer-big",      "+tb",    "write with explicit VR big endian TS");
        cmd.addOption("--write-xfer-implicit", "+ti",    "write with implicit VR little endian TS");
#ifdef WITH_ZLIB
        cmd.addOption("--write-xfer-deflated", "+td",    "write with deflated expl. VR little endian TS");
#endif
      cmd.addSubGroup("error handling:");
        cmd.addOption("--stop-on-error",       "-E",     "do not write if dump is damaged (default)");
        cmd.addOption("--ignore-errors",       "+E",     "attempt to write even if dump is damaged");
      cmd.addSubGroup("post-1993 value representations:");
        cmd.addOption("--enable-new-vr",       "+u",     "enable support for new VRs (UN/UT) (default)");
        cmd.addOption("--disable-new-vr",      "-u",     "disable support for new VRs, convert to OB");
      cmd.addSubGroup("group length encoding:");
        cmd.addOption("--group-length-recalc", "+g=",    "recalculate group lengths if present (default)");
        cmd.addOption("--group-length-create", "+g",     "always write with group length elements");
        cmd.addOption("--group-length-remove", "-g",     "always write without group length elements");
      cmd.addSubGroup("length encoding in sequences and items:");
        cmd.addOption("--length-explicit",     "+e",     "write with explicit lengths (default)");
        cmd.addOption("--length-undefined",    "-e",     "write with undefined lengths");
      cmd.addSubGroup("data set trailing padding (not with --write-dataset):");
        cmd.addOption("--padding-retain",      "-p=",    "do not change padding (default)");
        cmd.addOption("--padding-off",         "-p",     "no padding (implicit if --write-dataset)");
        cmd.addOption("--padding-create",      "+p",  2, "[f]ile-pad [i]tem-pad: integer",
                                                         "align file on multiple of f bytes\nand items on multiple of i bytes");
#ifdef WITH_ZLIB
      cmd.addSubGroup("deflate compression level (only with --write-xfer-deflated):");
        cmd.addOption("--compression-level",   "+cl", 1, "[l]evel: integer (default: 6)",
                                                         "0=uncompressed, 1=fastest, 9=best compression");
#endif

    const char *opt_ifname = NULL;
    const char *opt_ofname = NULL;
    E_TransferSyntax opt_xfer = EXS_Unknown;
    E_EncodingType opt_enctype = EET_ExplicitLength;
    E_GrpLenEncoding opt_glenc = EGL_recalcGL;
    E_PaddingEncoding opt_padenc = EPD_withoutPadding;
    E_FileWriteMode opt_writeMode = EWM_fileformat;
    OFCmdUnsignedInt opt_filepad = 0;
    OFCmdUnsignedInt opt_itempad = 0;
    OFCmdUnsignedInt opt_linelength = DCM_DumpMaxLineSize;
    OFBool opt_stopOnErrors = OFTrue;
    OFBool opt_metaInfo = OFTrue;
    OFBool opt_generateUIDs = OFFalse;
    OFBool opt_overwriteUIDs = OFFalse;

    /* evaluate command line */
    prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION);
    if (app.parseCommandLine(cmd, argc, argv))
    {
      /* check exclusive options first */
      if (cmd.hasExclusiveOption())
      {
          if (cmd.findOption("--version"))
          {
              app.printHeader(OFTrue /*print host identifier*/);
              COUT << OFendl << "External libraries used:";
#ifdef WITH_ZLIB
              COUT << OFendl << "- ZLIB, Version " << zlibVersion() << OFendl;
#else
              COUT << " none" << OFendl;
#endif
              return 0;
          }
      }

      /* command line parameters */

      cmd.getParam(1, opt_ifname);
      cmd.getParam(2, opt_ofname);

      OFLog::configureFromCommandLine(cmd, app);

      /* input options */

      cmd.beginOptionBlock();
      if (cmd.findOption("--read-meta-info")) opt_metaInfo = OFTrue;
      if (cmd.findOption("--ignore-meta-info")) opt_metaInfo = OFFalse;
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--read-file-little")) opt_fileContentsByteOrdering = EBO_LittleEndian;
      if (cmd.findOption("--read-file-big")) opt_fileContentsByteOrdering = EBO_BigEndian;
      cmd.endOptionBlock();

      if (cmd.findOption("--line"))
          app.checkValue(cmd.getValueAndCheckMin(opt_linelength, 80));

      /* processing options */

      if (cmd.findOption("--generate-new-uids")) opt_generateUIDs = OFTrue;

      cmd.beginOptionBlock();
      if (cmd.findOption("--dont-overwrite-uids")) opt_overwriteUIDs = OFFalse;
      if (cmd.findOption("--overwrite-uids")) opt_overwriteUIDs = OFTrue;
      cmd.endOptionBlock();

      /* output options */

      cmd.beginOptionBlock();
      if (cmd.findOption("--write-file")) opt_writeMode = EWM_fileformat;
      if (cmd.findOption("--write-dataset")) opt_writeMode = EWM_dataset;
      cmd.endOptionBlock();

      if (cmd.findOption("--update-meta-info"))
      {
          app.checkConflict("--update-meta-info", "--write-dataset", opt_writeMode == EWM_dataset);
          opt_writeMode = EWM_updateMeta;
      }

      cmd.beginOptionBlock();
      if (cmd.findOption("--write-xfer-same")) opt_xfer = EXS_Unknown;;
      if (cmd.findOption("--write-xfer-little")) opt_xfer = EXS_LittleEndianExplicit;
      if (cmd.findOption("--write-xfer-big")) opt_xfer = EXS_BigEndianExplicit;
      if (cmd.findOption("--write-xfer-implicit")) opt_xfer = EXS_LittleEndianImplicit;
#ifdef WITH_ZLIB
      if (cmd.findOption("--write-xfer-deflated")) opt_xfer = EXS_DeflatedLittleEndianExplicit;
#endif
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--stop-on-error")) opt_stopOnErrors = OFTrue;
      if (cmd.findOption("--ignore-errors")) opt_stopOnErrors = OFFalse;
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--enable-new-vr")) dcmEnableGenerationOfNewVRs();
      if (cmd.findOption("--disable-new-vr")) dcmDisableGenerationOfNewVRs();
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--group-length-recalc")) opt_glenc = EGL_recalcGL;
      if (cmd.findOption("--group-length-create")) opt_glenc = EGL_withGL;
      if (cmd.findOption("--group-length-remove")) opt_glenc = EGL_withoutGL;
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--length-explicit")) opt_enctype = EET_ExplicitLength;
      if (cmd.findOption("--length-undefined")) opt_enctype = EET_UndefinedLength;
      cmd.endOptionBlock();

      cmd.beginOptionBlock();
      if (cmd.findOption("--padding-retain"))
      {
          app.checkConflict("--padding-retain", "--write-dataset", opt_writeMode == EWM_dataset);
          opt_padenc = EPD_noChange;
      }
      if (cmd.findOption("--padding-off")) opt_padenc = EPD_withoutPadding;
      if (cmd.findOption("--padding-create"))
      {
          app.checkConflict("--padding-create", "--write-dataset", opt_writeMode == EWM_dataset);
          app.checkValue(cmd.getValueAndCheckMin(opt_filepad, 0));
          app.checkValue(cmd.getValueAndCheckMin(opt_itempad, 0));
          opt_padenc = EPD_withPadding;
      }
      cmd.endOptionBlock();

#ifdef WITH_ZLIB
      if (cmd.findOption("--compression-level"))
      {
          OFCmdUnsignedInt comprLevel = 0;
          app.checkDependence("--compression-level", "--write-xfer-deflated", opt_xfer == EXS_DeflatedLittleEndianExplicit);
          app.checkValue(cmd.getValueAndCheckMinMax(comprLevel, 0, 9));
          dcmZlibCompressionLevel.set(OFstatic_cast(int, comprLevel));
      }
#endif
    }

    /* print resource identifier */
    OFLOG_DEBUG(dump2dcmLogger, rcsid << OFendl);

    DcmFileFormat fileformat;
    DcmMetaInfo *metaheader = (opt_metaInfo) ? fileformat.getMetaInfo() : NULL;
    DcmDataset *dataset = fileformat.getDataset();

    /* make sure data dictionary is loaded */
    if (!dcmDataDict.isDictionaryLoaded())
    {
        OFLOG_WARN(dump2dcmLogger, "no data dictionary loaded, check environment variable: "
            << DCM_DICT_ENVIRONMENT_VARIABLE);
    }

    // open input dump file
    if ((opt_ifname == NULL) || (strlen(opt_ifname) == 0))
    {
        OFLOG_FATAL(dump2dcmLogger, "invalid input filename: <empty string>");
        return 1;
    }
    OFLOG_INFO(dump2dcmLogger, "reading dump file: " << opt_ifname);

    FILE *dumpfile = fopen(opt_ifname, "r");
    if (!dumpfile)
    {
        OFLOG_FATAL(dump2dcmLogger, "input file does not exist: " << opt_ifname);
        return 1;
    }

    int status = 0;
    E_TransferSyntax xfer;
    // read dump file into metaheader and dataset
    if (readDumpFile(metaheader, dataset, dumpfile, opt_ifname, xfer, opt_stopOnErrors,
        OFstatic_cast(unsigned long, opt_linelength)))
    {
        /* generate new UIDs (if required) */
        if (opt_generateUIDs)
        {
            char uid[100];
            if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_StudyInstanceUID))
            {
                OFLOG_INFO(dump2dcmLogger, "generating new Study Instance UID");
                dataset->putAndInsertString(DCM_StudyInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_STUDY_UID_ROOT));
            }
            if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_SeriesInstanceUID))
            {
                OFLOG_INFO(dump2dcmLogger, "generating new Series Instance UID");
                dataset->putAndInsertString(DCM_SeriesInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_SERIES_UID_ROOT));
            }
            if (opt_overwriteUIDs || !dataset->tagExistsWithValue(DCM_SOPInstanceUID))
            {
                OFLOG_INFO(dump2dcmLogger, "generating new SOP Instance UID");
                dataset->putAndInsertString(DCM_SOPInstanceUID, dcmGenerateUniqueIdentifier(uid, SITE_INSTANCE_UID_ROOT));
                /* make sure that the file meta information is updated correspondingly */
                if (opt_writeMode == EWM_fileformat)
                    opt_writeMode = EWM_updateMeta;
            }
        }

        // write into file format or dataset
        OFLOG_INFO(dump2dcmLogger, "writing DICOM file");

        /* determine transfer syntax to write the file */
        if (opt_xfer == EXS_Unknown)
        {
            opt_xfer = xfer;
            /* check whether output xfer is still unknown */
            if (opt_xfer == EXS_Unknown)
            {
                OFLOG_WARN(dump2dcmLogger, "output transfer syntax unknown, assuming --write-xfer-little");
                opt_xfer = EXS_LittleEndianExplicit;
            }
        }
        /* check whether it is possible to write the file */
        if (fileformat.canWriteXfer(opt_xfer))
        {
            /* check whether pixel data is compressed */
            if ((opt_writeMode == EWM_dataset) && DcmXfer(xfer).isEncapsulated())
            {
                OFLOG_WARN(dump2dcmLogger, "encapsulated pixel data require file format, ignoring --write-dataset");
                opt_writeMode = EWM_fileformat;
            }
            OFCondition l_error = fileformat.saveFile(opt_ofname, opt_xfer, opt_enctype, opt_glenc, opt_padenc,
                OFstatic_cast(Uint32, opt_filepad), OFstatic_cast(Uint32, opt_itempad), opt_writeMode);

            if (l_error == EC_Normal)
            {
                OFLOG_INFO(dump2dcmLogger, "dump successfully converted");
            } else {
                OFLOG_ERROR(dump2dcmLogger, l_error.text() << ": writing file: "  << opt_ofname);
                status = 1;
            }
        } else {
            OFLOG_ERROR(dump2dcmLogger, "no conversion to transfer syntax " << DcmXfer(opt_xfer).getXferName() << " possible!");
            status = 2;
        }
    }
    fclose(dumpfile);

    return status;
}


text:
  #fill in the outline here

# Check the called column for the number called.
  #fill in the outline here

# If the number is in the column, replace with an 'x'
  #fill in the outline here

# Display a column to the console
  #fill in the outline here

# Display the board to the console (prettily)
  #fill in the outline here

# Initial Solution

class BingoBoard

  def initialize(board)
    @bingo_board = board
    @bingo = ['B', 'I', 'N', 'G', 'O']
    @num = rand(1..100)
  end

  def call
    @bingo_index = @bingo[rand(@bingo.length-1)]
       return "#{@bingo_index}#{@num}"
    # return @bingo_index
    # return @num

  end

  def check

      if @bingo_board[@bingo_index].include?(@num)
    @bingo_board[@bingo_index].map! {|row| row == @num? "X" : row}
  else
    puts @bingo_board
#     @bingo_board.each do |row|
#       row.map do |num|
#         if (@bingo_index == 'B') && (num == @num)

    #     end
    #   end
    end
  end
end

#DRIVER CODE (I.E. METHOD CALLS) GO BELOW THIS LINE
board = [[47, 44, 71, 8, 88],
        [22, 69, 75, 65, 73],
        [83, 85, 97, 89, 57],
        [25, 31, 96, 68, 51],
        [75, 70, 54, 80, 83]]

new_game = BingoBoard.new(board)

p new_game.call

p new_game.check

#Reflection
How difficult was pseudocoding this challenge? What do you think of your pseudocoding style?

# I found the outline a bit hard to follow this time around to PC. The notes of create vs define confused me a bit, but think it came together eventually.

# What are the benefits of using a class for this challenge?

# There many variables involved in this program and using class is an efficient way of creating methods and outlining the behavior of this game.

# How can you access coordinates in a nested array?

# Indices are the way to access coordinates in nested arrays.

# What methods did you use to access and modify the array?

# The include? and replace methods are good to utilize to accessa and modify array.

# Give an example of a new method you learned while reviewing the Ruby docs. Based on what you see in the docs, what purpose does it serve, and how is it called?

# I've learned about the map method and it's benefits to iterate  throughout the array to create a new array.

# How did you determine what should be an instance variable versus a local variable?

# Instance variables are those that should be used throughout the program.


text:
package sonata.kernel.vimadaptor.commons.vnfd;

import com.fasterxml.jackson.annotation.JsonProperty;

import sonata.kernel.vimadaptor.commons.nsd.VirtualLink.ConnectivityType;

import java.util.ArrayList;

public class VnfVirtualLink {

  private boolean access;
  @JsonProperty("connection_points_reference")
  private ArrayList<String> connectionPointsReference;
  @JsonProperty("connectivity_type")
  private ConnectivityType connectivityType;
  private boolean dhcp;
  @JsonProperty("external_access")
  private boolean externalAccess;
  private String id;
  @JsonProperty("leaf_requirement")
  private String leafRequirement;
  private String qos;
  @JsonProperty("root_requirement")
  private String rootRequirement;

  public ArrayList<String> getConnectionPointsReference() {
    return connectionPointsReference;
  }

  public ConnectivityType getConnectivityType() {
    return connectivityType;
  }

  public String getId() {
    return id;
  }

  public String getLeafRequirement() {
    return leafRequirement;
  }

  public String getQos() {
    return qos;
  }

  public String getRootRequirement() {
    return rootRequirement;
  }

  public boolean isAccess() {
    return access;
  }

  public boolean isDhcp() {
    return dhcp;
  }

  public boolean isExternalAccess() {
    return externalAccess;
  }

  public void setAccess(boolean access) {
    this.access = access;
  }

  public void setConnectionPointsReference(ArrayList<String> connectionPointsReference) {
    this.connectionPointsReference = connectionPointsReference;
  }

  public void setConnectivityType(ConnectivityType connectivityType) {
    this.connectivityType = connectivityType;
  }

  public void setDhcp(boolean dhcp) {
    this.dhcp = dhcp;
  }

  public void setExternalAccess(boolean externalAccess) {
    this.externalAccess = externalAccess;
  }

  public void setId(String id) {
    this.id = id;
  }

  public void setLeafRequirement(String leafRequirement) {
    this.leafRequirement = leafRequirement;
  }

  public void setQos(String qos) {
    this.qos = qos;
  }

  public void setRootRequirement(String rootRequirement) {
    this.rootRequirement = rootRequirement;
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>freemarker 源码分析</title>

    <meta name="author" content="盒子">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="all">

  韭菜盒子
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        归档

        标签

        分类

        分页

        关于我

freemarker 源码分析

正在研究freemarker源码

← Previous

Archive

Next →

Published

2010-09-14

Share to Weixin

Categories

  default 108

Tags

© 盒子 2016
          with help from Gor
          and Twitter Bootstrap
		  and Idea from ruhoh
            京ICP备17040577号-1


text:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import AuthPlugin from './auth'
import VueMaterial from 'vue-material'
import 'vue-material/dist/vue-material.min.css'
import 'vue-material/dist/theme/default.css'
import VeeValidate from 'vee-validate'
import axios from 'axios'
import VueSweetalert2 from 'vue-sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css';

Vue.config.productionTip = false
Vue.use(VueMaterial)
Vue.use(VueSweetalert2)
Vue.use(VeeValidate)

import i18n from './lang'

VeeValidate.Validator.extend('password', {
  getMessage: field => 'Invalid password! It must contain 1 uppercase, 1 lowercase, 1 number, and one punctation.', // eslint-disable-line no-unused-vars
  validate: value => {
    var strongRegex = new RegExp('^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!\\?@#\\$%\\^&\\*_\\.,:;\\[\\]\\(\\){}<>\'"\\+\\-=~`])[0-9a-zA-Z!\\?@#\\$%\\^&\\*_\\.,:;\\[\\]\\(\\){}<>\'"\\+\\-=~`]{8,}$')
    return strongRegex.test(value)
  }
})

Vue.prototype.$http = axios;
Vue.prototype.$apiPrefix = '/cxf';
Vue.prototype.$production = (process.env.NODE_ENV === 'production')

Vue.use(AuthPlugin, {
  router: router,
  http: axios,
  apiPrefix: Vue.prototype.$apiPrefix,
  production: Vue.prototype.$production
})

new Vue({
  router,
  i18n,
  render: h => h(App)
}).$mount('#app')


text:
package io.tehuti.metrics.stats;

import io.tehuti.metrics.MeasurableStat;
import io.tehuti.metrics.MetricConfig;
/**
 * An un-windowed cumulative total maintained over all time.
 */
public class Total implements MeasurableStat {

    private double total;

    public Total() {
        this.total = 0.0;
    }

    public Total(double value) {
        this.total = value;
    }

    @Override
    public void record(MetricConfig config, double value, long now) {
        this.total += value;
    }

    @Override
    public double measure(MetricConfig config, long now) {
        return this.total;
    }

}


text:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { LocalizationService, Translation } from './LocalizationService';

@Injectable()
export class LocalizationResolver implements Resolve<any> {
    constructor(private localizationService: LocalizationService) {

    }

    public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Translation> {
        return Observable.fromPromise(this.localizationService.getLocalization());
    }
}


text:
/* $Id: tiff2bw.c,v 1.15 2010-07-02 12:02:56 dron Exp $ */

/*
 * Copyright (c) 1988-1997 Sam Leffler
 * Copyright (c) 1991-1997 Silicon Graphics, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software and
 * its documentation for any purpose is hereby granted without fee, provided
 * that (i) the above copyright notices and this permission notice appear in
 * all copies of the software and related documentation, and (ii) the names of
 * Sam Leffler and Silicon Graphics may not be used in any advertising or
 * publicity relating to the software without the specific, prior written
 * permission of Sam Leffler and Silicon Graphics.
 *
 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
 *
 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
 * OF THIS SOFTWARE.
 */

#include "tif_config.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif

#ifdef NEED_LIBPORT
# include "libport.h"
#endif

#include "tiffio.h"

#define	streq(a,b)	(strcmp((a),(b)) == 0)
#define	strneq(a,b,n)	(strncmp(a,b,n) == 0)

/* x% weighting -> fraction of full color */
#define	PCT(x)	(((x)*255+127)/100)
int	RED = PCT(30);		/* 30% */
int	GREEN = PCT(59);	/* 59% */
int	BLUE = PCT(11);		/* 11% */

static	void usage(void);
static	int processCompressOptions(char*);

static void
compresscontig(unsigned char* out, unsigned char* rgb, uint32 n)
{
	register int v, red = RED, green = GREEN, blue = BLUE;

	while (n-- > 0) {
		v = red*(*rgb++);
		v += green*(*rgb++);
		v += blue*(*rgb++);
		*out++ = v>>8;
	}
}

static void
compresssep(unsigned char* out,
	    unsigned char* r, unsigned char* g, unsigned char* b, uint32 n)
{
	register uint32 red = RED, green = GREEN, blue = BLUE;

	while (n-- > 0)
		*out++ = (unsigned char)
			((red*(*r++) + green*(*g++) + blue*(*b++)) >> 8);
}

static int
checkcmap(TIFF* tif, int n, uint16* r, uint16* g, uint16* b)
{
	while (n-- > 0)
		if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256)
			return (16);
	TIFFWarning(TIFFFileName(tif), "Assuming 8-bit colormap");
	return (8);
}

static void
compresspalette(unsigned char* out, unsigned char* data, uint32 n, uint16* rmap, uint16* gmap, uint16* bmap)
{
	register int v, red = RED, green = GREEN, blue = BLUE;

	while (n-- > 0) {
		unsigned int ix = *data++;
		v = red*rmap[ix];
		v += green*gmap[ix];
		v += blue*bmap[ix];
		*out++ = v>>8;
	}
}

static	uint16 compression = (uint16) -1;
static	uint16 predictor = 0;
static	int jpegcolormode = JPEGCOLORMODE_RGB;
static	int quality = 75;		/* JPEG quality */

static	void cpTags(TIFF* in, TIFF* out);

int
main(int argc, char* argv[])
{
	uint32 rowsperstrip = (uint32) -1;
	TIFF *in, *out;
	uint32 w, h;
	uint16 samplesperpixel;
	uint16 bitspersample;
	uint16 config;
	uint16 photometric;
	uint16* red;
	uint16* green;
	uint16* blue;
	tsize_t rowsize;
	register uint32 row;
	register tsample_t s;
	unsigned char *inbuf, *outbuf;
	char thing[1024];
	int c;
	extern int optind;
	extern char *optarg;

	while ((c = getopt(argc, argv, "c:r:R:G:B:")) != -1)
		switch (c) {
		case 'c':		/* compression scheme */
			if (!processCompressOptions(optarg))
				usage();
			break;
		case 'r':		/* rows/strip */
			rowsperstrip = atoi(optarg);
			break;
		case 'R':
			RED = PCT(atoi(optarg));
			break;
		case 'G':
			GREEN = PCT(atoi(optarg));
			break;
		case 'B':
			BLUE = PCT(atoi(optarg));
			break;
		case '?':
			usage();
			/*NOTREACHED*/
		}
	if (argc - optind < 2)
		usage();
	in = TIFFOpen(argv[optind], "r");
	if (in == NULL)
		return (-1);
	photometric = 0;
	TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric);
	if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE ) {
		fprintf(stderr,
	    "%s: Bad photometric; can only handle RGB and Palette images.\n",
		    argv[optind]);
		return (-1);
	}
	TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel);
	if (samplesperpixel != 1 && samplesperpixel != 3) {
		fprintf(stderr, "%s: Bad samples/pixel %u.\n",
		    argv[optind], samplesperpixel);
		return (-1);
	}
	TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample);
	if (bitspersample != 8) {
		fprintf(stderr,
		    " %s: Sorry, only handle 8-bit samples.\n", argv[optind]);
		return (-1);
	}
	TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w);
	TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h);
	TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config);

	out = TIFFOpen(argv[optind+1], "w");
	if (out == NULL)
		return (-1);
	TIFFSetField(out, TIFFTAG_IMAGEWIDTH, w);
	TIFFSetField(out, TIFFTAG_IMAGELENGTH, h);
	TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, 8);
	TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 1);
	TIFFSetField(out, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
	cpTags(in, out);
	if (compression != (uint16) -1) {
		TIFFSetField(out, TIFFTAG_COMPRESSION, compression);
		switch (compression) {
		case COMPRESSION_JPEG:
			TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality);
			TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode);
			break;
		case COMPRESSION_LZW:
		case COMPRESSION_DEFLATE:
			if (predictor != 0)
				TIFFSetField(out, TIFFTAG_PREDICTOR, predictor);
			break;
		}
	}
	TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
	sprintf(thing, "B&W version of %s", argv[optind]);
	TIFFSetField(out, TIFFTAG_IMAGEDESCRIPTION, thing);
	TIFFSetField(out, TIFFTAG_SOFTWARE, "tiff2bw");
	outbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(out));
	TIFFSetField(out, TIFFTAG_ROWSPERSTRIP,
	    TIFFDefaultStripSize(out, rowsperstrip));

#define	pack(a,b)	((a)<<8 | (b))
	switch (pack(photometric, config)) {
	case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG):
	case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE):
		TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue);
		/*
		 * Convert 16-bit colormap to 8-bit (unless it looks
		 * like an old-style 8-bit colormap).
		 */
		if (checkcmap(in, 1<<bitspersample, red, green, blue) == 16) {
			int i;
#define	CVT(x)		(((x) * 255L) / ((1L<<16)-1))
			for (i = (1<<bitspersample)-1; i >= 0; i--) {
				red[i] = CVT(red[i]);
				green[i] = CVT(green[i]);
				blue[i] = CVT(blue[i]);
			}
#undef CVT
		}
		inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
		for (row = 0; row < h; row++) {
			if (TIFFReadScanline(in, inbuf, row, 0) < 0)
				break;
			compresspalette(outbuf, inbuf, w, red, green, blue);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG):
		inbuf = (unsigned char *)_TIFFmalloc(TIFFScanlineSize(in));
		for (row = 0; row < h; row++) {
			if (TIFFReadScanline(in, inbuf, row, 0) < 0)
				break;
			compresscontig(outbuf, inbuf, w);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE):
		rowsize = TIFFScanlineSize(in);
		inbuf = (unsigned char *)_TIFFmalloc(3*rowsize);
		for (row = 0; row < h; row++) {
			for (s = 0; s < 3; s++)
				if (TIFFReadScanline(in,
				    inbuf+s*rowsize, row, s) < 0)
					 return (-1);
			compresssep(outbuf,
			    inbuf, inbuf+rowsize, inbuf+2*rowsize, w);
			if (TIFFWriteScanline(out, outbuf, row, 0) < 0)
				break;
		}
		break;
	}
#undef pack
	TIFFClose(out);
	return (0);
}

static int
processCompressOptions(char* opt)
{
	if (streq(opt, "none"))
		compression = COMPRESSION_NONE;
	else if (streq(opt, "packbits"))
		compression = COMPRESSION_PACKBITS;
	else if (strneq(opt, "jpeg", 4)) {
		char* cp = strchr(opt, ':');

                compression = COMPRESSION_JPEG;
                while( cp )
                {
                    if (isdigit((int)cp[1]))
			quality = atoi(cp+1);
                    else if (cp[1] == 'r' )
			jpegcolormode = JPEGCOLORMODE_RAW;
                    else
                        usage();

                    cp = strchr(cp+1,':');
                }
	} else if (strneq(opt, "lzw", 3)) {
		char* cp = strchr(opt, ':');
		if (cp)
			predictor = atoi(cp+1);
		compression = COMPRESSION_LZW;
	} else if (strneq(opt, "zip", 3)) {
		char* cp = strchr(opt, ':');
		if (cp)
			predictor = atoi(cp+1);
		compression = COMPRESSION_DEFLATE;
	} else
		return (0);
	return (1);
}

#define	CopyField(tag, v) \
    if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v)
#define	CopyField2(tag, v1, v2) \
    if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2)
#define	CopyField3(tag, v1, v2, v3) \
    if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3)
#define	CopyField4(tag, v1, v2, v3, v4) \
    if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4)

static void
cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type)
{
	switch (type) {
	case TIFF_SHORT:
		if (count == 1) {
			uint16 shortv;
			CopyField(tag, shortv);
		} else if (count == 2) {
			uint16 shortv1, shortv2;
			CopyField2(tag, shortv1, shortv2);
		} else if (count == 4) {
			uint16 *tr, *tg, *tb, *ta;
			CopyField4(tag, tr, tg, tb, ta);
		} else if (count == (uint16) -1) {
			uint16 shortv1;
			uint16* shortav;
			CopyField2(tag, shortv1, shortav);
		}
		break;
	case TIFF_LONG:
		{ uint32 longv;
		  CopyField(tag, longv);
		}
		break;
	case TIFF_RATIONAL:
		if (count == 1) {
			float floatv;
			CopyField(tag, floatv);
		} else if (count == (uint16) -1) {
			float* floatav;
			CopyField(tag, floatav);
		}
		break;
	case TIFF_ASCII:
		{ char* stringv;
		  CopyField(tag, stringv);
		}
		break;
	case TIFF_DOUBLE:
		if (count == 1) {
			double doublev;
			CopyField(tag, doublev);
		} else if (count == (uint16) -1) {
			double* doubleav;
			CopyField(tag, doubleav);
		}
		break;
          default:
                TIFFError(TIFFFileName(in),
                          "Data type %d is not supported, tag %d skipped.",
                          tag, type);
	}
}

#undef CopyField4
#undef CopyField3
#undef CopyField2
#undef CopyField

static struct cpTag {
	uint16	tag;
	uint16	count;
	TIFFDataType type;
} tags[] = {
	{ TIFFTAG_SUBFILETYPE,		1, TIFF_LONG },
	{ TIFFTAG_THRESHHOLDING,	1, TIFF_SHORT },
	{ TIFFTAG_DOCUMENTNAME,		1, TIFF_ASCII },
	{ TIFFTAG_IMAGEDESCRIPTION,	1, TIFF_ASCII },
	{ TIFFTAG_MAKE,			1, TIFF_ASCII },
	{ TIFFTAG_MODEL,		1, TIFF_ASCII },
	{ TIFFTAG_MINSAMPLEVALUE,	1, TIFF_SHORT },
	{ TIFFTAG_MAXSAMPLEVALUE,	1, TIFF_SHORT },
	{ TIFFTAG_XRESOLUTION,		1, TIFF_RATIONAL },
	{ TIFFTAG_YRESOLUTION,		1, TIFF_RATIONAL },
	{ TIFFTAG_PAGENAME,		1, TIFF_ASCII },
	{ TIFFTAG_XPOSITION,		1, TIFF_RATIONAL },
	{ TIFFTAG_YPOSITION,		1, TIFF_RATIONAL },
	{ TIFFTAG_RESOLUTIONUNIT,	1, TIFF_SHORT },
	{ TIFFTAG_SOFTWARE,		1, TIFF_ASCII },
	{ TIFFTAG_DATETIME,		1, TIFF_ASCII },
	{ TIFFTAG_ARTIST,		1, TIFF_ASCII },
	{ TIFFTAG_HOSTCOMPUTER,		1, TIFF_ASCII },
	{ TIFFTAG_WHITEPOINT,		2, TIFF_RATIONAL },
	{ TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL },
	{ TIFFTAG_HALFTONEHINTS,	2, TIFF_SHORT },
	{ TIFFTAG_INKSET,		1, TIFF_SHORT },
	{ TIFFTAG_DOTRANGE,		2, TIFF_SHORT },
	{ TIFFTAG_TARGETPRINTER,	1, TIFF_ASCII },
	{ TIFFTAG_SAMPLEFORMAT,		1, TIFF_SHORT },
	{ TIFFTAG_YCBCRCOEFFICIENTS,	(uint16) -1,TIFF_RATIONAL },
	{ TIFFTAG_YCBCRSUBSAMPLING,	2, TIFF_SHORT },
	{ TIFFTAG_YCBCRPOSITIONING,	1, TIFF_SHORT },
	{ TIFFTAG_REFERENCEBLACKWHITE,	(uint16) -1,TIFF_RATIONAL },
	{ TIFFTAG_EXTRASAMPLES,		(uint16) -1, TIFF_SHORT },
	{ TIFFTAG_SMINSAMPLEVALUE,	1, TIFF_DOUBLE },
	{ TIFFTAG_SMAXSAMPLEVALUE,	1, TIFF_DOUBLE },
	{ TIFFTAG_STONITS,		1, TIFF_DOUBLE },
};
#define	NTAGS	(sizeof (tags) / sizeof (tags[0]))

static void
cpTags(TIFF* in, TIFF* out)
{
    struct cpTag *p;
    for (p = tags; p < &tags[NTAGS]; p++)
	cpTag(in, out, p->tag, p->count, p->type);
}
#undef NTAGS

char* stuff[] = {
"usage: tiff2bw [options] input.tif output.tif",
"where options are:",
" -R %		use #% from red channel",
" -G %		use #% from green channel",
" -B %		use #% from blue channel",
"",
" -r #		make each strip have no more than # rows",
"",
" -c lzw[:opts]	compress output with Lempel-Ziv & Welch encoding",
" -c zip[:opts]	compress output with deflate encoding",
" -c packbits	compress output with packbits encoding",
" -c g3[:opts]	compress output with CCITT Group 3 encoding",
" -c g4		compress output with CCITT Group 4 encoding",
" -c none	use no compression algorithm on output",
"",
"LZW and deflate options:",
" #		set predictor value",
"For example, -c lzw:2 to get LZW-encoded data with horizontal differencing",
NULL
};

static void
usage(void)
{
	char buf[BUFSIZ];
	int i;

	setbuf(stderr, buf);
        fprintf(stderr, "%s\n\n", TIFFGetVersion());
	for (i = 0; stuff[i] != NULL; i++)
		fprintf(stderr, "%s\n", stuff[i]);
	exit(-1);
}

/* vim: set ts=8 sts=8 sw=8 noet: */
/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 8
 * fill-column: 78
 * End:
 */


text:
define(["exports", "module", "react", "classnames", "./utils/ValidComponentChildren", "./utils/createChainedFunction"], function (exports, module, _react, _classnames, _utilsValidComponentChildren, _utilsCreateChainedFunction) {
  "use strict";

  var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

  var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

  var React = _interopRequire(_react);

  var cloneElement = _react.cloneElement;

  var classSet = _interopRequire(_classnames);

  var ValidComponentChildren = _interopRequire(_utilsValidComponentChildren);

  var createChainedFunction = _interopRequire(_utilsCreateChainedFunction);

  var Pager = React.createClass({
    displayName: "Pager",

    propTypes: {
      onSelect: React.PropTypes.func
    },

    render: function render() {
      return React.createElement(
        "ul",
        _extends({}, this.props, {
          className: classSet(this.props.className, "pager") }),
        ValidComponentChildren.map(this.props.children, this.renderPageItem)
      );
    },

    renderPageItem: function renderPageItem(child, index) {
      return cloneElement(child, {
        onSelect: createChainedFunction(child.props.onSelect, this.props.onSelect),
        key: child.key ? child.key : index
      });
    }
  });

  module.exports = Pager;
});


text:
package org.atf.core.eventbus;

import org.atf.core.eventbus.event.Event;

/**
 * @author Michal Bocek
 * @since 1.0.0
 */
public interface EventBus {

	void fire(Event event);

	void register(Handler<Event> handler);
}


text:
module Tapjoy
  module LDAP
    module CLI
      module Group
        # Delete LDAP group
        class Delete
          def delete
            confirm unless opts[:force]
            puts Tapjoy::LDAP::API::Group.destroy(opts[:name])
          end

          private

          def opts
            @opts ||= Optimist.options do
              # Set help message
              usage 'group delete [options]'
              synopsis "\nThis command is for deleting LDAP groups"

              opt :name, 'Specify group', type: :string, required: true
              opt :force, 'Force delete'
            end
          end

          def confirm
            puts "Confirm that you want to delete group #{opts[:name]} (yes/no)"
            print '>'
            confirm = STDIN.gets.chomp.downcase
            abort("Deletion of #{opts[:name]} aborted") unless confirm.start_with?('y')
          end
        end
      end
    end
  end
end


text:
![alt mobile checker by the World Wide Web Consortium](https://github.com/w3c/Mobile-Checker/blob/master/public/img/mobilechecker-logo-w3c.png)

[![Build Status](https://travis-ci.org/w3c/Mobile-Checker.svg?branch=master)](https://travis-ci.org/w3c/Mobile-Checker)
[![Coverage Status](https://coveralls.io/repos/w3c/Mobile-Checker/badge.svg)](https://coveralls.io/r/w3c/Mobile-Checker)
[![Dependency Status](https://david-dm.org/w3c/Mobile-Checker.svg)](https://david-dm.org/w3c/Mobile-Checker)
[![devDependency Status](https://david-dm.org/w3c/Mobile-Checker/dev-status.svg)](https://david-dm.org/w3c/Mobile-Checker#info=devDependencies)
[![Join the chat at https://gitter.im/w3c/Mobile-Checker](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/w3c/Mobile-Checker)

The Mobile Checker is a tool for Web developers who want to make their Web page or Web app work better on mobile devices.

The Mobile Checker was built to provide all of us web developers with a new and helpful experience of mobile Web developement.
We built the base. Now join us, and make it grant your wishes. We hope you will make it awesome.

## How does it work?
This tool is a full JavaScript Web application built with [Node.js](http://nodejs.org/) and [Selenium WebDriver](http://docs.seleniumhq.org/projects/webdriver/). Based on the [mobile Web browser emulator API](https://github.com/w3c/mobile-web-browser-emulator), the Mobile Checker combines powerful technologies to simulate a Web browser on a mobile device.
That's why, contrary to most of the current online mobile emulators, the Mobile Checker can provide an emulation close to what your Web app looks like on different kinds of mobile devices, including tablets and smartphones.

## Installation
Mobile Checker is a Node application. It will eventually be distributed through npm, but in the meantime
you can simply clone this repository:

    git clone https://github.com/w3c/Mobile-Checker.git

1. Install [Node.js](http://nodejs.org/)

2. Install npm dependencies:

    ```
    npm install -d
    ```

3. In addition to the npm dependencies, install:

* [Google Chrome](https://www.google.com/chrome/)
* [browsermob-proxy](https://github.com/lightbody/browsermob-proxy/) running on port 8080
* [ImageMagick](http://www.imagemagick.org/)
* [XVFB](http://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml)

## Running
In your terminal, run:

    node app.js

Then, connect on the localhost:3000 port.

## Testing
Testing is done using mocha. Simply run:

    mocha --timeout 30000

from the root and you will be running the test suite. Mocha can be installed with:

    npm install -g mocha

## Feedback and contributions

* **Send feedback** about the tool and join us on the [mailing list](public-qa-dev@w3.org).
* **Discuss** about the Mobile Checker in our [Gitter room](https://gitter.im/w3c/Mobile-Checker).
* **Report a bug** and open an issue on [Github](https://github.com/w3c/Mobile-Checker/issues).
* **Send a feature request** on [Github](https://github.com/w3c/Mobile-Checker/issues).
* **Contribute** to the Mobile Checker by first reading the [contribution guidelines](https://github.com/w3c/Mobile-Checker/blob/master/CONTRIBUTING.md).


text:
shellHelper.count = function (what) {
    assert(typeof what == "string");

    var args = what.split( /\s+/ );
    what = args[0]
    args = args.splice(1)

    if (what == "collections" || what == "tables") {
        databaseNames = db.getMongo().getDatabaseNames();
        collectionCounts = databaseNames.map(function (databaseName) {
            var count = db.getMongo().getDB(databaseName).getCollectionNames().length;
            return (count.commify() + " collection(s)");
        });
        printPaddedColumns(databaseNames, collectionCounts, mongo_hacker_config['colors']['databaseNames']);
        return "";
    }

    if (what == "documents" || what == "docs") {
        collectionNames = db.getCollectionNames().filter(function (collectionName) {
            // exclude "system" collections from "count" operation
            return !collectionName.startsWith('system.');
        });
        documentCounts = collectionNames.map(function (collectionName) {
            var count = db.getCollection(collectionName).count();
            return (count.commify() + " document(s)");
        });
        printPaddedColumns(collectionNames, documentCounts, mongo_hacker_config['colors']['collectionNames']);
        return "";
    }

    if (what == "index" || what == "indexes") {
        db.indexStats("", 1);
        return ""
    }

    throw "don't know how to count [" + what + "]";

}


text:
from __future__ import absolute_import, unicode_literals

def project_stream(project):
    """
    Filters the activity stream to return any item for the specified project.
    """
    return []

def user_project_stream(user, project):
    """
    Filters the activity stream to return items the user has done
    for the specified project.
    """
    return []

def investigation_stream(investigation):
    """
    Filters the activity stream to return any item for the specified
    investigation.
    """
    return []

def user_investigation_stream(user, investigation):
    """
    Filters the activity stream to return items the user has done
    for the specified investigation.
    """
    return []


text:
"""Tests for clif.testing.python.implicit_conversion."""

from absl.testing import absltest

from clif.testing.python import implicit_conversion

class ImplicitConversionTest(absltest.TestCase):

  def testImplicitConversion(self):
    b = implicit_conversion.B(123)
    self.assertEqual(implicit_conversion.Func(b), 123)

if __name__ == '__main__':
  absltest.main()


text:
namespace TimeUtil {

  // check if current time is in the specified time-domain,
  // If inside: return true;
  //            set prev_boundary to the domain's start time
  //              (if it does not exist, set it to LocalTime::InfinitePast())
  //            set next_boundary to the domain's end time
  //              (if it does not exist, set it to LocalTime::InfiniteFuture())
  // If outside: return false;
  //           set prev_boundary to the last domain's end time
  //              (if it does not exist, set it to LocalTime::InfinitePast())
  //           set next_boundary to the next domain's start time
  //              (if it does not exist, set it to LocalTime::InfiniteFuture())
  //
  // In all cases, prev_boundary is guaranteed to be <= current
  //               next_boundary is guaranteed to be > current
  bool CheckDomain(const TimeDomain<SharpPoint>& domain,
                   Time t, Timezone tz,
                   Time *prev_boundary, Time *next_boundary);
  bool CheckDomain(const TimeDomain<GenericPoint>& domain,
                   Time t, const Place& place,
                   Time *prev_boundary, Time *next_boundary);

}

#endif  // _PUBLIC_UTIL_TIME_TIMEUTIL_H_


text:
package uk.ac.ebi.gxa.dao;

import org.hibernate.SessionFactory;
import uk.ac.ebi.gxa.dao.exceptions.RecordNotFoundException;
import uk.ac.ebi.microarray.atlas.model.Organism;

public class OrganismDAO extends AbstractDAO<Organism> {

    public OrganismDAO(SessionFactory sessionFactory) {
        super(sessionFactory, Organism.class);
    }

    @Override
    protected String getNameColumn() {
        return "name";
    }

    /**
     * @return lower case matching required in getByName() queries
     */
    @Override
    protected boolean lowerCaseNameMatch() {
        return true;
    }

    public Organism getOrCreateOrganism(String name) {
        try {
            return getByName(name);
        } catch (RecordNotFoundException e) {
            // organism not found - create a new one
            Organism organism = new Organism(null, lowerCaseNameMatch() ? name.toLowerCase() : name);
            save(organism);
            template.flush();
            return organism;
        }
    }
}


text:
package org.apache.toree.magic.builtin

import java.io.PrintStream

import com.google.common.base.Strings
import org.apache.toree.kernel.protocol.v5.MIMEType
import org.apache.toree.magic._
import org.apache.toree.magic.dependencies.IncludeOutputStream
import org.apache.toree.utils.ArgumentParsingSupport
import org.slf4j.LoggerFactory

class JavaScript extends CellMagic with ArgumentParsingSupport
  with IncludeOutputStream {

  // Lazy because the outputStream is not provided at construction
  private lazy val printStream = new PrintStream(outputStream)

  override def execute(code: String): CellMagicOutput = {
    def printHelpAndReturn: CellMagicOutput = {
      printHelp(printStream, """%JavaScript <string_code>""")
      CellMagicOutput()
    }

    Strings.isNullOrEmpty(code) match {
      case true => printHelpAndReturn
      case false => CellMagicOutput(MIMEType.ApplicationJavaScript -> code)
    }
  }
}


text:
const path = require('path');
const webpack = require('webpack');

const DEBUG = process.env.NODE_ENV !== 'production';

module.exports = {
    entry: {
        app : ['./src/main/js/main.tsx'],
        init : ['./src/main/js/init.ts']
    },
    output: {
        path: __dirname + '/target/classes/assets',
        filename: '[name].bundle.js',
        devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]',
        globalObject: "this" // https://github.com/webpack/webpack/issues/6642
    },
    devtool: 'source-map',
    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".jsx"]
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: ["awesome-typescript-loader"]
            },
            {
                test: /\.js$/,
                enforce: "pre",
                use: "source-map-loader"
            }

        ]
    },
    optimization: {
        splitChunks: {
            cacheGroups: {
                commons: { test: /[\\/]node_modules[\\/]/, name: "vendor", chunks: "all" }
            }
        }
    },
    plugins: [
        /*new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),*/
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
            }
        })
    ],
    node: {
        console: true,
        fs: 'empty',
        net: 'empty',
        tls: 'empty'
    },
    mode: DEBUG ? "development" : "production"
};