text:
CREATE TABLE [dbo].[Tasks]
(
    [Id] BIGINT NOT NULL IDENTITY(1,1),
    [TestsFolder] NVARCHAR(512) NOT NULL,
    [TimeLimitMilliseconds] INT NOT NULL,
    [MemoryLimitBytes] INT NOT NULL,
    [Name] NVARCHAR(256) NOT NULL,
    [CreationDateUtc] DATETIME NOT NULL DEFAULT(GETUTCDATE()),
    [Statement] NVARCHAR(MAX) NOT NULL,
    [IsOpened] BIT NOT NULL DEFAULT(0),
    CONSTRAINT [PK_Tasks] PRIMARY KEY CLUSTERED ([Id] ASC)
)

GO
CREATE UNIQUE NONCLUSTERED INDEX [UIX_Tasks_Name] ON [dbo].[Tasks] ([Name])

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/xampp/htdocs/symfony/daemons/SmsDaemon_Win/daemon.php</file>
            <file>file:/C:/xampp/htdocs/symfony/src/MManager/MControlBundle/Controller/ModemController.php</file>
        </group>
    </open-files>
</project-private>


text:
module Icofont
	class Paths
		class << self
			def templates_path
				@@templates_path ||= File.expand_path("../templates", __FILE__)
			end

			def output_fonts_path
				@@output_fonts_path ||= expand_root("app/assets/#{FONT_NAME}")
			end

			def output_css_path
				@@output_css_path ||= expand_root("app/assets/stylesheets")
			end

			def output_css_file_path
				@@output_css_path ||= File.join(output_css_path, "#{FONT_NAME}.css.erb")
			end

			def manifest_path
				@@manifest_path ||= expand_root(".#{FONT_NAME}/fontcustom-manifest.yml")
			end

			def glyphs_path
				@@glyphs_path ||= expand_root(".#{FONT_NAME}/#{FONT_NAME}.txt")
			end

			def svg_path
				@@svg_path ||= File.join(svg_root, svg_folder)
			end

			def svg_root
				@@svg_root ||= File.expand_path(".#{FONT_NAME}", '~')
			end

			def svg_folder
				@@svg_folder ||= 'glyphs'
			end

			private

			def expand_root(path)
				File.join Rails.root, path
			end
		end
	end
end


text:
//
//  JDFTextView.m
//  JDFToolkit
//
//  Created by Joe Fryer on 03/09/2013.
//  Copyright (c) 2013 JDF. All rights reserved.
//

#import "JDFTextView.h"

@interface JDFTextView()

@property (nonatomic) BOOL placeholderIsVisible;
@property (nonatomic, strong) UIColor *standardTextColor;

@end

@implementation JDFTextView

#pragma mark - Setters

/*
 We do not use this setter internally - we call [super setTextColor:] when we want to change the text color. This setter is to intersect the user setting a text color externally, in which case we store their desired color in self.standardTextColor (however, we only set this via super here if the placeholder is not visible, as if it is visible we don't want to change it as we want the text to have the placeholderColor!).
 */
- (void)setTextColor:(UIColor *)textColor
{
    self.standardTextColor = textColor;
    if (!self.placeholderIsVisible) {
        [super setTextColor:textColor];
    }
}

- (void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    if ([super.text isEqualToString:@""]) {
        super.text = self.placeholder;
        self.placeholderIsVisible = YES;
    }
}

- (void)setPlaceholderIsVisible:(BOOL)placeholderIsVisible
{
    // Here, when we set our text color, we set it on super, as we have overriden setTextColor: to intersect a text color change that the user makes and store it in self.standardTextColor (but we don't want to do use that internally as we will end up making self.standardTextColor the same as our placeholderColor).
    _placeholderIsVisible = placeholderIsVisible;
    if (_placeholderIsVisible) {
        [super setTextColor:self.placeholderColor];
    } else {
        [super setTextColor:self.standardTextColor];
    }
}

- (void)setText:(NSString *)text
{
    if ([text isEqualToString:@""]) {
        [super setText:self.placeholder];
        self.placeholderIsVisible = YES;
    } else {
        [super setText:text];
    }
}

#pragma mark - Getters

/*
 If the user requests the text from us, we don't want to return the placeholder string, if that is what is displaying!
 */
- (NSString *)text
{
    if (self.placeholderIsVisible) {
        return @"";
    } else {
        return [super text];
    }
}

#pragma mark - Notification Receivers

- (void)textDidBeginEditing:(NSNotification *)notification
{
    if (self.placeholderIsVisible) {
        super.text = @"";
        self.placeholderIsVisible = NO;
    }
}

- (void)textDidEndEditing:(NSNotification *)notification
{
    if ([super.text isEqualToString:@""]) {
        super.text = self.placeholder;
        self.placeholderIsVisible = YES;
    }
}

#pragma mark - Lifecycle

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self customInit];
    }
    return self;
}

- (void)awakeFromNib
{
    [self customInit];
}

- (void)customInit
{
    self.standardTextColor = [UIColor colorWithCGColor:self.textColor.CGColor];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidEndEditing:) name:UITextViewTextDidEndEditingNotification object:nil];

    if (!self.placeholder) {
        self.placeholder = @"";
    }
    if (!self.placeholderColor) {
        self.placeholderColor = [UIColor grayColor];
    }

    if ([super.text isEqualToString:@""]) {
        super.text = self.placeholder;
        self.placeholderIsVisible = YES;
    } else {
        self.placeholderIsVisible = NO;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end


text:
Tilt switch control led light off

Experimental device
1. Ball switch: 1 Led light:
2. 1 220Ω resistor: 1 pcs
3. Colorful breadboard experiment jumper: several
4. 2, Experimental connection

 Follow the Arduino tutorial to connect the control board, expansion board, breadboard, and the download cable. Then connect the led lights to the digital 8-pin, ball switch to the analog 5-pin.
3.The principle of the experiment when the switch is lower than the horizontal position of the tilt, switch through, analog port voltage of about 5V (digital binary for 1023), light led lights. When the other end is below the horizontal position tilt, the switch stops, the analog port voltage value is about 0V (digital binary is expressed as 0), extinguishes the led light. In the program, whether the analog port voltage value is greater than about 2.5V (digital hexadecimal representation of 512), you can know whether the tilt switch to find out.4、
code

The program code is as follows:

```c
 void setup()
{
pinMode(8,OUTPUT);// Set the number 8 pin to the output mode
}
void loop()
{
int i;// Define hair volume i
while(1)
{
i=analogRead(5);// Read the analog 5-port voltage value
if(i>200)// If greater than 512 (2.5V)
{
digitalWrite(8,HIGH);// Lighting led lights
}
else// otherwise
{
digitalWrite(8,LOW);// Off the led lights
}
}
}
```

After the program is downloaded to the experimental board, we can tilt the board to observe the status of the led lights. When the gold side is lower than the horizontal position of the tilt, switch find through, light led lights; when the silver end is lower than the horizontal position tilt, switch off, simulation
The mouth voltage is about 0V (digital binary is expressed as 0), off the led lights.
Master the program, we can follow their own ideas experiment, you can control other devices such as buzzers, etc.


text:
package com.localytics.android;

import org.json.JSONException;
import org.json.JSONObject;

import com.localytics.android.LocalyticsProvider.InfoDbColumns;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

public class PushReceiver extends BroadcastReceiver
{
	public void onReceive(Context context, Intent intent)
	{
		// Registration complete
		if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
		{
			handleRegistration(context, intent);
		}
		// Notification received
		else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
		{
			handleNotificationReceived(context, intent);
		}
	}

	private void handleRegistration(Context context, Intent intent)
	{
		String registrationId = intent.getStringExtra("registration_id");

		// Failed?
		if (intent.getStringExtra("error") != null)
		{
            if (Constants.IS_LOGGABLE)
            {
                Log.v(Constants.LOG_TAG, "GCM registration failed"); //$NON-NLS-1$
            }
	    }
		// Unregistered?
	    else if (intent.getStringExtra("unregistered") != null)
	    {
            if (Constants.IS_LOGGABLE)
            {
                Log.v(Constants.LOG_TAG, "GCM unregistered: removing id"); //$NON-NLS-1$
            }

	    	setRegistrationId(context, null);
	    }
		// Success
	    else if (registrationId != null)
	    {
            if (Constants.IS_LOGGABLE)
            {
                Log.v(Constants.LOG_TAG, String.format("GCM registered, new id: %s", registrationId)); //$NON-NLS-1$
            }

	    	setRegistrationId(context, registrationId);
	    }
	}

	@SuppressWarnings("deprecation")
	private void handleNotificationReceived(Context context, Intent intent)
	{
		// Get the notification message
		String message = intent.getExtras().getString("message");

		// Get the app name, icon, and launch intent
		CharSequence appName = "";
		int appIcon = android.R.drawable.sym_def_app_icon;
		Intent launchIntent = null;
		try
		{
			ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
			appIcon = applicationInfo.icon;
			appName = context.getPackageManager().getApplicationLabel(applicationInfo);
			launchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
	    }
		catch (NameNotFoundException e)
		{
            if (Constants.IS_LOGGABLE)
            {
                Log.w(Constants.LOG_TAG, "Failed to get application name, icon, or launch intent"); //$NON-NLS-1$
            }
	    }

		// Create the notification
		Notification notification = new Notification(appIcon, message, System.currentTimeMillis());

		// Set the intent to perform when tapped
		if (launchIntent != null)
		{
			launchIntent.putExtras(intent);
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			notification.setLatestEventInfo(context, appName, message, contentIntent);
		}

		// Auto dismiss when tapped
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        int notificationId = 0;

        // Use the campaign id as the notification id to prevents duplicates
        String llString = intent.getExtras().getString("ll");
        if (llString != null)
        {
        	try
        	{
        		JSONObject llObject = new JSONObject(llString);
        		notificationId = llObject.getInt("ca");
        	}
        	catch (JSONException e)
        	{
        		if (Constants.IS_LOGGABLE)
        		{
        			Log.w(Constants.LOG_TAG, "Failed to get campaign id from payload"); //$NON-NLS-1$
        		}
        	}
        }

        // Show the notification
		NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(notificationId, notification);
	}

	private void setRegistrationId(final Context context, final String registrationId)
	{
		// Get the app key
    	String appKey = DatapointHelper.getLocalyticsAppKeyOrNull(context);

		// Return if there's no app key in the manifest
		if (appKey == null || appKey.length() == 0) {
			return;
		}

		// Persist the registration id and current app version
        final LocalyticsProvider provider = LocalyticsProvider.getInstance(context, appKey);
        provider.runBatchTransaction(new Runnable()
        {
        	public void run()
        	{
                final ContentValues values = new ContentValues();
                values.put(InfoDbColumns.REGISTRATION_ID, registrationId == null ? "" : registrationId);
                values.put(InfoDbColumns.REGISTRATION_VERSION, DatapointHelper.getAppVersion(context));
                provider.update(InfoDbColumns.TABLE_NAME, values, null, null);
        	}
    	});
	}
}


text:
package org.apache.spark.unsafe.memory;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import javax.annotation.concurrent.GuardedBy;

/**
 * Manages memory for an executor. Individual operators / tasks allocate memory through
 * {@link TaskMemoryManager} objects, which obtain their memory from ExecutorMemoryManager.
 *
 * 负责具体实现,它管理on-heap和off-heap内存,并实现了一个weak reference pool支持跨tasks的空闲页复用。
 * 一个JVM里仅有一个实例
 */
public class ExecutorMemoryManager {

  /**
   * Allocator, exposed for enabling untracked allocations of temporary data structures.
   * 分配器,用于启用临时数据结构的未跟踪分配
   */
  public final MemoryAllocator allocator;

  /**
   * Tracks whether memory will be allocated on the JVM heap or off-heap using sun.misc.Unsafe.
   * 跟踪内存是否将使用sun.misc.Unsafe在JVM堆或非堆上分配
   */
  final boolean inHeap;

  @GuardedBy("this")
  private final Map<Long, LinkedList<WeakReference<MemoryBlock>>> bufferPoolsBySize =
    new HashMap<Long, LinkedList<WeakReference<MemoryBlock>>>();

  private static final int POOLING_THRESHOLD_BYTES = 1024 * 1024;

  /**
   * Construct a new ExecutorMemoryManager.
   * 构造一个新的ExecutorMemoryManager
   *
   * @param allocator the allocator that will be used
   */
  public ExecutorMemoryManager(MemoryAllocator allocator) {
    this.inHeap = allocator instanceof HeapMemoryAllocator;
    this.allocator = allocator;
  }

  /**
   * Returns true if allocations of the given size should go through the pooling mechanism and
   * false otherwise.
   * 如果给定大小的分配应通过池化机制,则返回true,否则返回false
   */
  private boolean shouldPool(long size) {
    // Very small allocations are less likely to benefit from pooling.
      //非常小的分配不太可能从池中获益
    // At some point, we should explore supporting pooling for off-heap memory, but for now we'll
    // ignore that case in the interest of simplicity.
      //在某些时候,我们应该探索支持堆栈内存的方式,但是现在我们就为了简单起见而忽视这种情况
    return size >= POOLING_THRESHOLD_BYTES && allocator instanceof HeapMemoryAllocator;
  }

  /**
   * Allocates a contiguous block of memory. Note that the allocated memory is not guaranteed
   * to be zeroed out (call `zero()` on the result if this is necessary).
   * 分配一个连续的内存块。请注意,分配的内存不能保证被清零(如果需要,则在结果上调用`zero()`)
   */
  MemoryBlock allocate(long size) throws OutOfMemoryError {
    if (shouldPool(size)) {
      synchronized (this) {
        final LinkedList<WeakReference<MemoryBlock>> pool = bufferPoolsBySize.get(size);
        if (pool != null) {
          while (!pool.isEmpty()) {
            final WeakReference<MemoryBlock> blockReference = pool.pop();
            final MemoryBlock memory = blockReference.get();
            if (memory != null) {
              assert (memory.size() == size);
              return memory;
            }
          }
          bufferPoolsBySize.remove(size);
        }
      }
      return allocator.allocate(size);
    } else {
      return allocator.allocate(size);
    }
  }

  void free(MemoryBlock memory) {
    final long size = memory.size();
    if (shouldPool(size)) {
      synchronized (this) {
        LinkedList<WeakReference<MemoryBlock>> pool = bufferPoolsBySize.get(size);
        if (pool == null) {
          pool = new LinkedList<WeakReference<MemoryBlock>>();
          bufferPoolsBySize.put(size, pool);
        }
        pool.add(new WeakReference<MemoryBlock>(memory));
      }
    } else {
      allocator.free(memory);
    }
  }

}


text:
/*************************************************************************/
/*                                                                       */
/*                  Language Technologies Institute                      */
/*                     Carnegie Mellon University                        */
/*                        Copyright (c) 1999                             */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK         */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE      */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*             Author:  Alan W Black (awb@cs.cmu.edu)                    */
/*               Date:  December 1999                                    */
/*************************************************************************/
/*                                                                       */
/*    String manipulation functions                                      */
/*                                                                       */
/*************************************************************************/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "cst_alloc.h"
#include "cst_string.h"
#include "cst_file.h"

#ifdef UNDER_CE /* WinCE does not fully implement ANSI C */

cst_string *cst_strrchr(const cst_string *str, int c)
{
    cst_string *p = (const cst_string *)str + cst_strlen(str);
    while (p >= str) {
	if (*p == c)
	    return p;
	--p;
    }
    return NULL;
}

double cst_atof(const char *str)
{
    /* double f = 0.0; */

    /* sscanf(str, "%f", &f); */
    return atof(str);
}

#else /* Sane operating system */

cst_string *cst_strrchr(const cst_string *str, int c)
{
    return (cst_string *)strrchr((const char *)str, c);
}

double cst_atof(const char *str)
{
    return atof(str);
}
#endif /* WinCE */

cst_string *cst_strdup(const cst_string *str)
{
    cst_string *nstr = NULL;

    if (str)
    {
	nstr = cst_alloc(cst_string,cst_strlen((const char *)str)+1);
	memmove(nstr,str,cst_strlen((const char *)str)+1);
    }
    return nstr;
}

cst_string *cst_strchr(const cst_string *s, int c)
{
    return (cst_string *)strchr((const char *)s,c);
}

char *cst_substr(const char *str,int start, int length)
{
    char *nstr = NULL;

    if (str)
    {
	nstr = cst_alloc(char,length+1);
	strncpy(nstr,str+start,length);
	nstr[length] = '\0';
    }
    return nstr;
}

char *cst_string_before(const char *s,const char *c)
{
    char *p;
    char *q;

    p = (char *)cst_strstr(s,c);
    if (p == NULL)
	return NULL;
    q = (char *)cst_strdup((cst_string *)s);
    q[cst_strlen(s)-cst_strlen(p)] = '\0';
    return q;
}

cst_string *cst_downcase(const cst_string *str)
{
    cst_string *dc;
    int i;

    dc = cst_strdup(str);
    for (i=0; str[i] != '\0'; i++)
    {
	if (isupper((int)str[i]))
	    dc[i] = tolower((int)str[i]);
    }
    return dc;
}

cst_string *cst_upcase(const cst_string *str)
{
    cst_string *uc;
    int i;

    uc = cst_strdup(str);
    for (i=0; str[i] != '\0'; i++)
    {
	if (islower((int)str[i]))
	    uc[i] = toupper((int)str[i]);
    }
    return uc;
}

int cst_member_string(const char *str, const char * const *slist)
{
    const char * const *p;

    for (p = slist; *p; ++p)
	if (cst_streq(*p, str))
	    break;

    return *p != NULL;
}

char *cst_strcat(const char *a, const char *b)
{
    char *r;

    r = cst_alloc(char,cst_strlen(a)+cst_strlen(b)+1);
    cst_sprintf(r,"%s%s",a,b);
    return r;
}

char *cst_strcat3(const char *a, const char *b, const char *c)
{
    char *r;

    r = cst_alloc(char,cst_strlen(a)+cst_strlen(b)+cst_strlen(c)+1);
    cst_sprintf(r,"%s%s%s",a,b,c);
    return r;
}


text:
class CUISpinNum : public CUICustomSpin
{
public:
					CUISpinNum			();

	virtual void	Init				(float x, float y, float width, float height);

	// CUIOptionsItem
	virtual void	SetCurrentValue		();
	virtual void	SaveValue			();
	virtual bool	IsChanged			();

    virtual void	OnBtnUpClick		();
	virtual void	OnBtnDownClick		();

			void	SetMax				(int max)	{m_iMax=max;};
			void	SetMin				(int min)	{m_iMin=min;};
			int		Value				() const {return m_iVal;}
protected:
			void	SetValue			();
	virtual bool	CanPressUp			();
	virtual bool	CanPressDown		();
	virtual void		IncVal			();
	virtual void		DecVal			();

	int		m_iMax;
	int		m_iMin;
	int		m_iStep;
	int		m_iVal;
};

class CUISpinFlt : public CUICustomSpin
{
public:
	CUISpinFlt();

	virtual void	Init				(float x, float y, float width, float height);

	// CUIOptionsItem
	virtual void	SetCurrentValue		();
	virtual void	SaveValue			();
	virtual bool	IsChanged			();

    virtual void	OnBtnUpClick		();
	virtual void	OnBtnDownClick		();

			void	SetMax				(float max);
			void	SetMin				(float min);
protected:
			void	SetValue			();
	virtual bool	CanPressUp			();
	virtual bool	CanPressDown		();
	virtual void	IncVal				();
	virtual void	DecVal				();

	float		m_fMax;
	float		m_fMin;
	float		m_fStep;
	float		m_fVal;
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2014 The LolDevs team (https://github.com/loldevs)
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>riotapi</artifactId>
        <groupId>net.boreeas</groupId>
        <version>2.0.6</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>riotapi.loginqueue</artifactId>
    <name>net.boreeas:riotapi.loginqueue</name>
    <description>Login to a server.</description>

    <dependencies>
        <dependency>
            <groupId>net.boreeas</groupId>
            <artifactId>riotapi.domain</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>
</project>


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # This module can be used to add/remove a resource pool to/from vCenter
      class Vmware_resource_pool < Base
        # @return [String] Name of the datacenter to add the host.
        attribute :datacenter
        validates :datacenter, presence: true, type: String

        # @return [String] Name of the cluster to add the host.
        attribute :cluster
        validates :cluster, presence: true, type: String

        # @return [String] Resource pool name to manage.
        attribute :resource_pool
        validates :resource_pool, presence: true, type: String

        # @return [Boolean, nil] In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.
        attribute :cpu_expandable_reservations
        validates :cpu_expandable_reservations, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Integer, nil] Amount of resource that is guaranteed available to the virtual machine or resource pool.
        attribute :cpu_reservation
        validates :cpu_reservation, type: Integer

        # @return [Integer, nil] The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.,The default value -1 indicates no limit.
        attribute :cpu_limit
        validates :cpu_limit, type: Integer

        # @return [:high, :custom, :low, :normal, nil] Memory shares are used in case of resource contention.
        attribute :cpu_shares
        validates :cpu_shares, expression_inclusion: {:in=>[:high, :custom, :low, :normal], :message=>"%{value} needs to be :high, :custom, :low, :normal"}, allow_nil: true

        # @return [Boolean, nil] In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.
        attribute :mem_expandable_reservations
        validates :mem_expandable_reservations, expression_inclusion: {:in=>[true, false], :message=>"%{value} needs to be true, false"}, allow_nil: true

        # @return [Integer, nil] Amount of resource that is guaranteed available to the virtual machine or resource pool.
        attribute :mem_reservation
        validates :mem_reservation, type: Integer

        # @return [Integer, nil] The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.,The default value -1 indicates no limit.
        attribute :mem_limit
        validates :mem_limit, type: Integer

        # @return [:high, :custom, :low, :normal, nil] Memory shares are used in case of resource contention.
        attribute :mem_shares
        validates :mem_shares, expression_inclusion: {:in=>[:high, :custom, :low, :normal], :message=>"%{value} needs to be :high, :custom, :low, :normal"}, allow_nil: true

        # @return [:present, :absent, nil] Add or remove the resource pool
        attribute :state
        validates :state, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}, allow_nil: true
      end
    end
  end
end


text:
<?php

namespace Illuminate\Mail;

use Swift_Image;
use Swift_Attachment;

class Message
{
    /**
     * The Swift Message instance.
     *
     * @var \Swift_Message
     */
    protected $swift;

    /**
     * Create a new message instance.
     *
     * @param  \Swift_Message  $swift
     * @return void
     */
    public function __construct($swift)
    {
        $this->swift = $swift;
    }

    /**
     * Add a "from" address to the message.
     *
     * @param  string  $address
     * @param  string|null  $name
     * @return $this
     */
    public function from($address, $name = null)
    {
        $this->swift->setFrom($address, $name);

        return $this;
    }

    /**
     * Set the "sender" of the message.
     *
     * @param  string  $address
     * @param  string|null  $name
     * @return $this
     */
    public function sender($address, $name = null)
    {
        $this->swift->setSender($address, $name);

        return $this;
    }

    /**
     * Set the "return path" of the message.
     *
     * @param  string  $address
     * @return $this
     */
    public function returnPath($address)
    {
        $this->swift->setReturnPath($address);

        return $this;
    }

    /**
     * Add a recipient to the message.
     *
     * @param  string|array  $address
     * @param  string|null  $name
     * @param  bool  $override
     * @return $this
     */
    public function to($address, $name = null, $override = false)
    {
        if ($override) {
            $this->swift->setTo($address, $name);

            return $this;
        }

        return $this->addAddresses($address, $name, 'To');
    }

    /**
     * Add a carbon copy to the message.
     *
     * @param  string  $address
     * @param  string|null  $name
     * @return $this
     */
    public function cc($address, $name = null)
    {
        return $this->addAddresses($address, $name, 'Cc');
    }

    /**
     * Add a blind carbon copy to the message.
     *
     * @param  string  $address
     * @param  string|null  $name
     * @return $this
     */
    public function bcc($address, $name = null)
    {
        return $this->addAddresses($address, $name, 'Bcc');
    }

    /**
     * Add a reply to address to the message.
     *
     * @param  string  $address
     * @param  string|null  $name
     * @return $this
     */
    public function replyTo($address, $name = null)
    {
        return $this->addAddresses($address, $name, 'ReplyTo');
    }

    /**
     * Add a recipient to the message.
     *
     * @param  string|array  $address
     * @param  string  $name
     * @param  string  $type
     * @return $this
     */
    protected function addAddresses($address, $name, $type)
    {
        if (is_array($address)) {
            $this->swift->{"set{$type}"}($address, $name);
        } else {
            $this->swift->{"add{$type}"}($address, $name);
        }

        return $this;
    }

    /**
     * Set the subject of the message.
     *
     * @param  string  $subject
     * @return $this
     */
    public function subject($subject)
    {
        $this->swift->setSubject($subject);

        return $this;
    }

    /**
     * Set the message priority level.
     *
     * @param  int  $level
     * @return $this
     */
    public function priority($level)
    {
        $this->swift->setPriority($level);

        return $this;
    }

    /**
     * Attach a file to the message.
     *
     * @param  string  $file
     * @param  array  $options
     * @return $this
     */
    public function attach($file, array $options = [])
    {
        $attachment = $this->createAttachmentFromPath($file);

        return $this->prepAttachment($attachment, $options);
    }

    /**
     * Create a Swift Attachment instance.
     *
     * @param  string  $file
     * @return \Swift_Attachment
     */
    protected function createAttachmentFromPath($file)
    {
        return Swift_Attachment::fromPath($file);
    }

    /**
     * Attach in-memory data as an attachment.
     *
     * @param  string  $data
     * @param  string  $name
     * @param  array  $options
     * @return $this
     */
    public function attachData($data, $name, array $options = [])
    {
        $attachment = $this->createAttachmentFromData($data, $name);

        return $this->prepAttachment($attachment, $options);
    }

    /**
     * Create a Swift Attachment instance from data.
     *
     * @param  string  $data
     * @param  string  $name
     * @return \Swift_Attachment
     */
    protected function createAttachmentFromData($data, $name)
    {
        return Swift_Attachment::newInstance($data, $name);
    }

    /**
     * Embed a file in the message and get the CID.
     *
     * @param  string  $file
     * @return string
     */
    public function embed($file)
    {
        return $this->swift->embed(Swift_Image::fromPath($file));
    }

    /**
     * Embed in-memory data in the message and get the CID.
     *
     * @param  string  $data
     * @param  string  $name
     * @param  string|null  $contentType
     * @return string
     */
    public function embedData($data, $name, $contentType = null)
    {
        $image = Swift_Image::newInstance($data, $name, $contentType);

        return $this->swift->embed($image);
    }

    /**
     * Prepare and attach the given attachment.
     *
     * @param  \Swift_Attachment  $attachment
     * @param  array  $options
     * @return $this
     */
    protected function prepAttachment($attachment, $options = [])
    {
        // First we will check for a MIME type on the message, which instructs the
        // mail client on what type of attachment the file is so that it may be
        // downloaded correctly by the user. The MIME option is not required.
        if (isset($options['mime'])) {
            $attachment->setContentType($options['mime']);
        }

        // If an alternative name was given as an option, we will set that on this
        // attachment so that it will be downloaded with the desired names from
        // the developer, otherwise the default file names will get assigned.
        if (isset($options['as'])) {
            $attachment->setFilename($options['as']);
        }

        $this->swift->attach($attachment);

        return $this;
    }

    /**
     * Get the underlying Swift Message instance.
     *
     * @return \Swift_Message
     */
    public function getSwiftMessage()
    {
        return $this->swift;
    }

    /**
     * Dynamically pass missing methods to the Swift instance.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        $callable = [$this->swift, $method];

        return call_user_func_array($callable, $parameters);
    }
}


text:
using Xunit.Abstractions;
using Orleans.LeaseProviders;
using TestExtensions.Runners;
using Orleans.Configuration;
using Microsoft.Extensions.Options;

namespace Tester.AzureUtils.Lease
{
    [TestCategory("Functional"), TestCategory("AzureStorage"), TestCategory("Lease")]
    public class AzureBlobLeaseProviderTests : GoldenPathLeaseProviderTestRunner
    {
        public AzureBlobLeaseProviderTests(ITestOutputHelper output)
            :base(CreateLeaseProvider(), output)
        {
        }

        private static ILeaseProvider CreateLeaseProvider()
        {
            TestUtils.CheckForAzureStorage();
            return new AzureBlobLeaseProvider(Options.Create(new AzureBlobLeaseProviderOptions()
            {
                BlobContainerName = "test-blob-container-name"
            }.ConfigureTestDefaults()));
        }
    }
}


text:
using System;
using System.Runtime.Caching;

namespace Oldmansoft.Identity
{
    /// <summary>
    /// 密码守卫
    /// </summary>
    public class PasswordGuard
    {
        /// <summary>
        /// 唯一实例
        /// </summary>
        public static readonly PasswordGuard Instance = new PasswordGuard();

        private readonly MemoryCache Memory = new MemoryCache("Identity");

        /// <summary>
        /// 重试次数
        /// </summary>
        public int CanTryCount { get; set; }

        /// <summary>
        /// 锁定秒数
        /// </summary>
        public int LockSecond { get; set; }

        private PasswordGuard()
        {
            CanTryCount = 3;
            LockSecond = 10;
        }

        /// <summary>
        /// 是否锁定
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool IsLockedOut(string name)
        {
            var cacheItem = Memory.GetCacheItem(name);
            if (cacheItem != null)
            {
                var tryWrongCount = (int)cacheItem.Value;
                if (tryWrongCount >= CanTryCount)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 设置计数
        /// </summary>
        /// <param name="name"></param>
        public void SetCount(string name)
        {
            var oldValue = Memory.AddOrGetExisting(name, 1, DateTime.Now.AddSeconds(LockSecond));
            if (oldValue != null)
            {
                Memory.Set(name, (int)oldValue + 1, DateTime.Now.AddSeconds(LockSecond));
            }
        }
    }
}


text:
package org.apache.bookkeeper.conf;

import java.net.URL;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.SystemConfiguration;

import org.apache.bookkeeper.feature.Feature;
import org.apache.bookkeeper.meta.LedgerManagerFactory;
import org.apache.bookkeeper.util.ReflectionUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Abstract configuration
 */
public abstract class AbstractConfiguration extends CompositeConfiguration {

    static final Logger LOG = LoggerFactory.getLogger(AbstractConfiguration.class);
    public static final String READ_SYSTEM_PROPERTIES_PROPERTY
                            = "org.apache.bookkeeper.conf.readsystemproperties";
    /**
     * Enable the use of System Properties, which was the default behaviour till 4.4.0
     */
    private static final boolean READ_SYSTEM_PROPERTIES
                                    = Boolean.getBoolean(READ_SYSTEM_PROPERTIES_PROPERTY);

    protected static final ClassLoader defaultLoader;
    static {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (null == loader) {
            loader = AbstractConfiguration.class.getClassLoader();
        }
        defaultLoader = loader;
    }

    // Ledger Manager
    protected final static String LEDGER_MANAGER_TYPE = "ledgerManagerType";
    protected final static String LEDGER_MANAGER_FACTORY_CLASS = "ledgerManagerFactoryClass";
    protected final static String ZK_LEDGERS_ROOT_PATH = "zkLedgersRootPath";
    protected final static String AVAILABLE_NODE = "available";
    protected final static String REREPLICATION_ENTRY_BATCH_SIZE = "rereplicationEntryBatchSize";

    // Metastore settings, only being used when LEDGER_MANAGER_FACTORY_CLASS is MSLedgerManagerFactory
    protected final static String METASTORE_IMPL_CLASS = "metastoreImplClass";
    protected final static String METASTORE_MAX_ENTRIES_PER_SCAN = "metastoreMaxEntriesPerScan";

    protected AbstractConfiguration() {
        super();
        if (READ_SYSTEM_PROPERTIES) {
            // add configuration for system properties
            addConfiguration(new SystemConfiguration());
        }
    }

    /**
     * You can load configurations in precedence order. The first one takes
     * precedence over any loaded later.
     *
     * @param confURL
     *          Configuration URL
     */
    public void loadConf(URL confURL) throws ConfigurationException {
        Configuration loadedConf = new PropertiesConfiguration(confURL);
        addConfiguration(loadedConf);
    }

    /**
     * You can load configuration from other configuration
     *
     * @param baseConf
     *          Other Configuration
     */
    public void loadConf(AbstractConfiguration baseConf) {
        addConfiguration(baseConf);
    }

    /**
     * Load configuration from other configuration object
     *
     * @param otherConf
     *          Other configuration object
     */
    public void loadConf(Configuration otherConf) {
        addConfiguration(otherConf);
    }

    /**
     * Set Ledger Manager Type.
     *
     * @param lmType
     *          Ledger Manager Type
     * @deprecated replaced by {@link #setLedgerManagerFactoryClass}
     */
    @Deprecated
    public void setLedgerManagerType(String lmType) {
        setProperty(LEDGER_MANAGER_TYPE, lmType);
    }

    /**
     * Get Ledger Manager Type.
     *
     * @return ledger manager type
     * @throws ConfigurationException
     * @deprecated replaced by {@link #getLedgerManagerFactoryClass()}
     */
    @Deprecated
    public String getLedgerManagerType() {
        return getString(LEDGER_MANAGER_TYPE);
    }

    /**
     * Set Ledger Manager Factory Class Name.
     *
     * @param factoryClassName
     *          Ledger Manager Factory Class Name
     */
    public void setLedgerManagerFactoryClassName(String factoryClassName) {
        setProperty(LEDGER_MANAGER_FACTORY_CLASS, factoryClassName);
    }

    /**
     * Set Ledger Manager Factory Class.
     *
     * @param factoryClass
     *          Ledger Manager Factory Class
     */
    public void setLedgerManagerFactoryClass(Class<? extends LedgerManagerFactory> factoryClass) {
        setProperty(LEDGER_MANAGER_FACTORY_CLASS, factoryClass.getName());
    }

    /**
     * Get ledger manager factory class.
     *
     * @return ledger manager factory class
     */
    public Class<? extends LedgerManagerFactory> getLedgerManagerFactoryClass()
        throws ConfigurationException {
        return ReflectionUtils.getClass(this, LEDGER_MANAGER_FACTORY_CLASS,
                                        null, LedgerManagerFactory.class,
                                        defaultLoader);
    }

    /**
     * Set Zk Ledgers Root Path.
     *
     * @param zkLedgersPath zk ledgers root path
     */
    public void setZkLedgersRootPath(String zkLedgersPath) {
        setProperty(ZK_LEDGERS_ROOT_PATH, zkLedgersPath);
    }

    /**
     * Get Zk Ledgers Root Path.
     *
     * @return zk ledgers root path
     */
    public String getZkLedgersRootPath() {
        return getString(ZK_LEDGERS_ROOT_PATH, "/ledgers");
    }

    /**
     * Get the node under which available bookies are stored
     *
     * @return Node under which available bookies are stored.
     */
    public String getZkAvailableBookiesPath() {
        return getZkLedgersRootPath() + "/" + AVAILABLE_NODE;
    }

    /**
     * Set the max entries to keep in fragment for re-replication. If fragment
     * has more entries than this count, then the original fragment will be
     * split into multiple small logical fragments by keeping max entries count
     * to rereplicationEntryBatchSize. So, re-replication will happen in batches
     * wise.
     */
    public void setRereplicationEntryBatchSize(long rereplicationEntryBatchSize) {
        setProperty(REREPLICATION_ENTRY_BATCH_SIZE, rereplicationEntryBatchSize);
    }

    /**
     * Get the re-replication entry batch size
     */
    public long getRereplicationEntryBatchSize() {
        return getLong(REREPLICATION_ENTRY_BATCH_SIZE, 10);
    }

    /**
     * Get metastore implementation class.
     *
     * @return metastore implementation class name.
     */
    public String getMetastoreImplClass() {
        return getString(METASTORE_IMPL_CLASS);
    }

    /**
     * Set metastore implementation class.
     *
     * @param metastoreImplClass
     *          Metastore implementation Class name.
     */
    public void setMetastoreImplClass(String metastoreImplClass) {
        setProperty(METASTORE_IMPL_CLASS, metastoreImplClass);
    }

    /**
     * Get max entries per scan in metastore.
     *
     * @return max entries per scan in metastore.
     */
    public int getMetastoreMaxEntriesPerScan() {
        return getInt(METASTORE_MAX_ENTRIES_PER_SCAN, 50);
    }

    /**
     * Set max entries per scan in metastore.
     *
     * @param maxEntries
     *          Max entries per scan in metastore.
     */
    public void setMetastoreMaxEntriesPerScan(int maxEntries) {
        setProperty(METASTORE_MAX_ENTRIES_PER_SCAN, maxEntries);
    }

    public void setFeature(String configProperty, Feature feature) {
        setProperty(configProperty, feature);
    }

    public Feature getFeature(String configProperty, Feature defaultValue) {
        if (null == getProperty(configProperty)) {
            return defaultValue;
        } else {
            return (Feature)getProperty(configProperty);
        }
    }
}


text:
<Customer CustomerID="OLDWO">
	<CompanyName>Old World Delicatessen</CompanyName>
	<ContactName>Rene Phillips</ContactName>
	<ContactTitle>Sales Representative</ContactTitle>
	<Address>2743 Bering St.</Address>
	<City>Anchorage</City>
	<Region>AK</Region>
	<PostalCode>99508</PostalCode>
	<Country>USA</Country>
	<Phone>(907) 555-7584</Phone>
	<Fax>(907) 555-2880</Fax>
</Customer>


text:
from __future__ import absolute_import

from django.db import models

from sentry.db.models import FlexibleForeignKey

from . import AvatarBase

class OrganizationAvatar(AvatarBase):
    """
    An OrganizationAvatar associates an Organization with their avatar photo File
    and contains their preferences for avatar type.
    """

    AVATAR_TYPES = ((0, "letter_avatar"), (1, "upload"))

    FILE_TYPE = "avatar.file"

    organization = FlexibleForeignKey("sentry.Organization", unique=True, related_name="avatar")
    avatar_type = models.PositiveSmallIntegerField(default=0, choices=AVATAR_TYPES)

    class Meta:
        app_label = "sentry"
        db_table = "sentry_organizationavatar"

    def get_cache_key(self, size):
        return "org_avatar:%s:%s" % (self.organization_id, size)


text:
<manifest package="com.anysoftkeyboard.jnidictionaryv1">

</manifest>


text:
WatchersNET.SiteMap - A Modern SiteMap / TreeView Module and Skin Object for DNN®

![prview](http://www.watchersnet.de/Portals/0/SiteMapSkinsCollage.png)

[DEMO](http://www.watchersnet.de/DotNetNuke/Module/SiteMap.aspx)

Back in the old days, almost every web site had a sitemap where they listed out all the pages. The purpose of the sitemap is to help visitors and search engine spiders to find information on the site.

Now, a lot of modern websites have dropped the sitemap page, instead they place the sitemap in the footer area.

This Module/Skin Object Creates a SiteMap that looks like such footer SiteMap, but of course it can be placed anywhere on your Website. There a many pre-installed Skins, which changes the look of the SiteMap.

The Module/Skin Object also can Render the SiteMap as a TreeView (With Skin Support & Animations)

# Features

* SiteMap available as Module and Skin Object
* Very Light Weight
* Skin Support (Contains 9 Normal Skins, and 10 TreeView Skins)
* There are two Render Modes : Normal and as TreeView*
* Option to Show only Sub Links from Current Tab
* Simply excluding of Tabs
* Show / Hide Tab Hidden Tabs
* Show / Hide Tab Icons
* Define a Default Tab Icon
* Shows links based on visitor's authorized permission level
* Full Language Localization
* Generates Human Friendly URLs
* IPortable Support (Easy Import/Export of Settings)
* Option to Set Maximum Sublevels
* Demo Modus (Shows Skin Selector above the SiteMap)
* Filter Tabs By Taxonomy Tags (Terms from Current Page, All Terms from All Vacabularies, From Selected Vocabularies and from Selected Terms)

## Extra TreeView Options

* Animation: Sets the animation speed for Expanding/Collapsing of Child Tabs.
* Valid values are one of the strings "slow", "normal", "fast".
* Collapse: Sets whether all nodes should be collapsed by default
* Unique: Sets whether only one tree node can be open at any time, collapsing any previous open nodes.
* Persist: Persists the tree's expand/collapse state in one of two ways:
** "location" - looks within all tree nodes with link anchors that match the document's current URL (location.href), and if found, expands that node (including its parent nodes). Great for href-based state saving.
** "cookie" - Saves the current state of the tree on each click to a cookie and restores that state on page load.

## Option to Set Start Level

* Root : Shows All Tabs
* Parent : Shows All Tabs From the Current Tabs Level Parent - If No Parent Tabs available it Renders from Root
* Current: Shows All Tabs In the Current Level
* Children: Shows All Child Tabs From The Current Tab - If No Child Tabs available it Renders from Root)
* Custom: Shows all Tabs in The Current level based on the selected Tab


text:
package org.apache.flink.table.api

import _root_.java.util.concurrent.atomic.AtomicInteger

import org.apache.calcite.plan.RelOptUtil
import org.apache.calcite.plan.hep.HepMatchOrder
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.sql2rel.RelDecorrelator
import org.apache.calcite.tools.RuleSet
import org.apache.flink.api.common.functions.MapFunction
import org.apache.flink.api.common.typeinfo.TypeInformation
import org.apache.flink.api.java.io.DiscardingOutputFormat
import org.apache.flink.api.java.typeutils.GenericTypeInfo
import org.apache.flink.api.java.{DataSet, ExecutionEnvironment}
import org.apache.flink.table.descriptors.{BatchTableDescriptor, ConnectorDescriptor}
import org.apache.flink.table.explain.PlanJsonParser
import org.apache.flink.table.expressions.{Expression, TimeAttribute}
import org.apache.flink.table.plan.nodes.FlinkConventions
import org.apache.flink.table.plan.nodes.dataset.DataSetRel
import org.apache.flink.table.plan.rules.FlinkRuleSets
import org.apache.flink.table.plan.schema._
import org.apache.flink.table.runtime.MapRunner
import org.apache.flink.table.sinks._
import org.apache.flink.table.sources.{BatchTableSource, TableSource}
import org.apache.flink.types.Row

/**
  * The abstract base class for batch TableEnvironments.
  *
  * A TableEnvironment can be used to:
  * - convert a [[DataSet]] to a [[Table]]
  * - register a [[DataSet]] in the [[TableEnvironment]]'s catalog
  * - register a [[Table]] in the [[TableEnvironment]]'s catalog
  * - scan a registered table to obtain a [[Table]]
  * - specify a SQL query on registered tables to obtain a [[Table]]
  * - convert a [[Table]] into a [[DataSet]]
  * - explain the AST and execution plan of a [[Table]]
  *
  * @param execEnv The [[ExecutionEnvironment]] which is wrapped in this [[BatchTableEnvironment]].
  * @param config The [[TableConfig]] of this [[BatchTableEnvironment]].
  */
abstract class BatchTableEnvironment(
    private[flink] val execEnv: ExecutionEnvironment,
    config: TableConfig)
  extends TableEnvironment(config) {

  // a counter for unique table names.
  private val nameCntr: AtomicInteger = new AtomicInteger(0)

  // the naming pattern for internally registered tables.
  private val internalNamePattern = "^_DataSetTable_[0-9]+$".r

  override def queryConfig: BatchQueryConfig = new BatchQueryConfig

  /**
    * Checks if the chosen table name is valid.
    *
    * @param name The table name to check.
    */
  override protected def checkValidTableName(name: String): Unit = {
    val m = internalNamePattern.findFirstIn(name)
    m match {
      case Some(_) =>
        throw new TableException(s"Illegal Table name. " +
          s"Please choose a name that does not contain the pattern $internalNamePattern")
      case None =>
    }
  }

  /** Returns a unique table name according to the internal naming pattern. */
  override protected def createUniqueTableName(): String =
    "_DataSetTable_" + nameCntr.getAndIncrement()

  /**
    * Registers an internal [[BatchTableSource]] in this [[TableEnvironment]]'s catalog without
    * name checking. Registered tables can be referenced in SQL queries.
    *
    * @param name        The name under which the [[TableSource]] is registered.
    * @param tableSource The [[TableSource]] to register.
    */
  override protected def registerTableSourceInternal(
      name: String,
      tableSource: TableSource[_])
    : Unit = {

    tableSource match {

      // check for proper batch table source
      case batchTableSource: BatchTableSource[_] =>
        // check if a table (source or sink) is registered
        Option(getTable(name)) match {

          // table source and/or sink is registered
          case Some(table: TableSourceSinkTable[_, _]) => table.tableSourceTable match {

            // wrapper contains source
            case Some(_: TableSourceTable[_]) =>
              throw new TableException(s"Table '$name' already exists. " +
                s"Please choose a different name.")

            // wrapper contains only sink (not source)
            case _ =>
              val enrichedTable = new TableSourceSinkTable(
                Some(new BatchTableSourceTable(batchTableSource)),
                table.tableSinkTable)
              replaceRegisteredTable(name, enrichedTable)
          }

          // no table is registered
          case _ =>
            val newTable = new TableSourceSinkTable(
              Some(new BatchTableSourceTable(batchTableSource)),
              None)
            registerTableInternal(name, newTable)
        }

      // not a batch table source
      case _ =>
        throw new TableException("Only BatchTableSource can be registered in " +
            "BatchTableEnvironment.")
    }
  }

  /**
    * Creates a table source and/or table sink from a descriptor.
    *
    * Descriptors allow for declaring the communication to external systems in an
    * implementation-agnostic way. The classpath is scanned for suitable table factories that match
    * the desired configuration.
    *
    * The following example shows how to read from a connector using a JSON format and
    * registering a table source as "MyTable":
    *
    * {{{
    *
    * tableEnv
    *   .connect(
    *     new ExternalSystemXYZ()
    *       .version("0.11"))
    *   .withFormat(
    *     new Json()
    *       .jsonSchema("{...}")
    *       .failOnMissingField(false))
    *   .withSchema(
    *     new Schema()
    *       .field("user-name", "VARCHAR").from("u_name")
    *       .field("count", "DECIMAL")
    *   .registerSource("MyTable")
    * }}}
    *
    * @param connectorDescriptor connector descriptor describing the external system
    */
  def connect(connectorDescriptor: ConnectorDescriptor): BatchTableDescriptor = {
    new BatchTableDescriptor(this, connectorDescriptor)
  }

  /**
    * Registers an external [[TableSink]] with given field names and types in this
    * [[TableEnvironment]]'s catalog.
    * Registered sink tables can be referenced in SQL DML statements.
    *
    * Example:
    *
    * {{{
    *   // create a table sink and its field names and types
    *   val fieldNames: Array[String] = Array("a", "b", "c")
    *   val fieldTypes: Array[TypeInformation[_]] = Array(Types.STRING, Types.INT, Types.LONG)
    *   val tableSink: BatchTableSink = new YourTableSinkImpl(...)
    *
    *   // register the table sink in the catalog
    *   tableEnv.registerTableSink("output_table", fieldNames, fieldsTypes, tableSink)
    *
    *   // use the registered sink
    *   tableEnv.sqlUpdate("INSERT INTO output_table SELECT a, b, c FROM sourceTable")
    * }}}
    *
    * @param name       The name under which the [[TableSink]] is registered.
    * @param fieldNames The field names to register with the [[TableSink]].
    * @param fieldTypes The field types to register with the [[TableSink]].
    * @param tableSink  The [[TableSink]] to register.
    */
  def registerTableSink(
      name: String,
      fieldNames: Array[String],
      fieldTypes: Array[TypeInformation[_]],
      tableSink: TableSink[_]): Unit = {
    // validate
    checkValidTableName(name)
    if (fieldNames == null) throw TableException("fieldNames must not be null.")
    if (fieldTypes == null) throw TableException("fieldTypes must not be null.")
    if (fieldNames.length == 0) throw new TableException("fieldNames must not be empty.")
    if (fieldNames.length != fieldTypes.length) {
      throw new TableException("Same number of field names and types required.")
    }

    // configure and register
    val configuredSink = tableSink.configure(fieldNames, fieldTypes)
    registerTableSinkInternal(name, configuredSink)
  }

  /**
    * Registers an external [[TableSink]] with already configured field names and field types in
    * this [[TableEnvironment]]'s catalog.
    * Registered sink tables can be referenced in SQL DML statements.
    *
    * @param name The name under which the [[TableSink]] is registered.
    * @param configuredSink The configured [[TableSink]] to register.
    */
  def registerTableSink(name: String, configuredSink: TableSink[_]): Unit = {
    registerTableSinkInternal(name, configuredSink)
  }

  private def registerTableSinkInternal(name: String, configuredSink: TableSink[_]): Unit = {
    // validate
    checkValidTableName(name)
    if (configuredSink.getFieldNames == null || configuredSink.getFieldTypes == null) {
      throw new TableException("Table sink is not configured.")
    }
    if (configuredSink.getFieldNames.length == 0) {
      throw new TableException("Field names must not be empty.")
    }
    if (configuredSink.getFieldNames.length != configuredSink.getFieldTypes.length) {
      throw new TableException("Same number of field names and types required.")
    }

    // register
    configuredSink match {

      // check for proper batch table sink
      case _: BatchTableSink[_] =>

        // check if a table (source or sink) is registered
        Option(getTable(name)) match {

          // table source and/or sink is registered
          case Some(table: TableSourceSinkTable[_, _]) => table.tableSinkTable match {

            // wrapper contains sink
            case Some(_: TableSinkTable[_]) =>
              throw new TableException(s"Table '$name' already exists. " +
                s"Please choose a different name.")

            // wrapper contains only source (not sink)
            case _ =>
              val enrichedTable = new TableSourceSinkTable(
                table.tableSourceTable,
                Some(new TableSinkTable(configuredSink)))
              replaceRegisteredTable(name, enrichedTable)
          }

          // no table is registered
          case _ =>
            val newTable = new TableSourceSinkTable(
              None,
              Some(new TableSinkTable(configuredSink)))
            registerTableInternal(name, newTable)
        }

      // not a batch table sink
      case _ =>
        throw new TableException("Only BatchTableSink can be registered in BatchTableEnvironment.")
    }
  }

  /**
    * Writes a [[Table]] to a [[TableSink]].
    *
    * Internally, the [[Table]] is translated into a [[DataSet]] and handed over to the
    * [[TableSink]] to write it.
    *
    * @param table The [[Table]] to write.
    * @param sink The [[TableSink]] to write the [[Table]] to.
    * @param queryConfig The configuration for the query to generate.
    * @tparam T The expected type of the [[DataSet]] which represents the [[Table]].
    */
  override private[flink] def writeToSink[T](
      table: Table,
      sink: TableSink[T],
      queryConfig: QueryConfig): Unit = {

    // Check the query configuration to be a batch one.
    val batchQueryConfig = queryConfig match {
      case batchConfig: BatchQueryConfig => batchConfig
      case _ =>
        throw new TableException("BatchQueryConfig required to configure batch query.")
    }

    sink match {
      case batchSink: BatchTableSink[T] =>
        val outputType = sink.getOutputType
        // translate the Table into a DataSet and provide the type that the TableSink expects.
        val result: DataSet[T] = translate(table, batchQueryConfig)(outputType)
        // Give the DataSet to the TableSink to emit it.
        batchSink.emitDataSet(result)
      case _ =>
        throw new TableException("BatchTableSink required to emit batch Table.")
    }
  }

  /**
    * Creates a final converter that maps the internal row type to external type.
    *
    * @param physicalTypeInfo the input of the sink
    * @param schema the input schema with correct field names (esp. for POJO field mapping)
    * @param requestedTypeInfo the output type of the sink
    * @param functionName name of the map function. Must not be unique but has to be a
    *                     valid Java class identifier.
    */
  protected def getConversionMapper[IN, OUT](
      physicalTypeInfo: TypeInformation[IN],
      schema: RowSchema,
      requestedTypeInfo: TypeInformation[OUT],
      functionName: String)
    : Option[MapFunction[IN, OUT]] = {

    val converterFunction = generateRowConverterFunction[OUT](
      physicalTypeInfo.asInstanceOf[TypeInformation[Row]],
      schema,
      requestedTypeInfo,
      functionName
    )

    // add a runner if we need conversion
    converterFunction.map { func =>
      new MapRunner[IN, OUT](
          func.name,
          func.code,
          func.returnType)
    }
  }

  /**
    * Returns the AST of the specified Table API and SQL queries and the execution plan to compute
    * the result of the given [[Table]].
    *
    * @param table The table for which the AST and execution plan will be returned.
    * @param extended Flag to include detailed optimizer estimates.
    */
  private[flink] def explain(table: Table, extended: Boolean): String = {
    val ast = table.getRelNode
    val optimizedPlan = optimize(ast)
    val dataSet = translate[Row](optimizedPlan, ast.getRowType, queryConfig) (
      new GenericTypeInfo (classOf[Row]))
    dataSet.output(new DiscardingOutputFormat[Row])
    val env = dataSet.getExecutionEnvironment
    val jasonSqlPlan = env.getExecutionPlan
    val sqlPlan = PlanJsonParser.getSqlExecutionPlan(jasonSqlPlan, extended)

    s"== Abstract Syntax Tree ==" +
        System.lineSeparator +
        s"${RelOptUtil.toString(ast)}" +
        System.lineSeparator +
        s"== Optimized Logical Plan ==" +
        System.lineSeparator +
        s"${RelOptUtil.toString(optimizedPlan)}" +
        System.lineSeparator +
        s"== Physical Execution Plan ==" +
        System.lineSeparator +
        s"$sqlPlan"
  }

  /**
    * Returns the AST of the specified Table API and SQL queries and the execution plan to compute
    * the result of the given [[Table]].
    *
    * @param table The table for which the AST and execution plan will be returned.
    */
  def explain(table: Table): String = explain(table: Table, extended = false)

  /**
    * Registers a [[DataSet]] as a table under a given name in the [[TableEnvironment]]'s catalog.
    *
    * @param name The name under which the table is registered in the catalog.
    * @param dataSet The [[DataSet]] to register as table in the catalog.
    * @tparam T the type of the [[DataSet]].
    */
  protected def registerDataSetInternal[T](name: String, dataSet: DataSet[T]): Unit = {

    val (fieldNames, fieldIndexes) = getFieldInfo[T](dataSet.getType)
    val dataSetTable = new DataSetTable[T](
      dataSet,
      fieldIndexes,
      fieldNames
    )
    registerTableInternal(name, dataSetTable)
  }

  /**
    * Registers a [[DataSet]] as a table under a given name with field names as specified by
    * field expressions in the [[TableEnvironment]]'s catalog.
    *
    * @param name The name under which the table is registered in the catalog.
    * @param dataSet The [[DataSet]] to register as table in the catalog.
    * @param fields The field expressions to define the field names of the table.
    * @tparam T The type of the [[DataSet]].
    */
  protected def registerDataSetInternal[T](
      name: String, dataSet: DataSet[T], fields: Array[Expression]): Unit = {

    val inputType = dataSet.getType

    val (fieldNames, fieldIndexes) = getFieldInfo[T](
      inputType,
      fields)

    if (fields.exists(_.isInstanceOf[TimeAttribute])) {
      throw new ValidationException(
        ".rowtime and .proctime time indicators are not allowed in a batch environment.")
    }

    val dataSetTable = new DataSetTable[T](dataSet, fieldIndexes, fieldNames)
    registerTableInternal(name, dataSetTable)
  }

  /**
    * Returns the built-in normalization rules that are defined by the environment.
    */
  protected def getBuiltInNormRuleSet: RuleSet = FlinkRuleSets.DATASET_NORM_RULES

  /**
    * Returns the built-in optimization rules that are defined by the environment.
    */
  protected def getBuiltInPhysicalOptRuleSet: RuleSet = FlinkRuleSets.DATASET_OPT_RULES

  /**
    * Generates the optimized [[RelNode]] tree from the original relational node tree.
    *
    * @param relNode The original [[RelNode]] tree
    * @return The optimized [[RelNode]] tree
    */
  private[flink] def optimize(relNode: RelNode): RelNode = {

    // 0. convert sub-queries before query decorrelation
    val convSubQueryPlan = runHepPlanner(
      HepMatchOrder.BOTTOM_UP, FlinkRuleSets.TABLE_SUBQUERY_RULES, relNode, relNode.getTraitSet)

    // 0. convert table references
    val fullRelNode = runHepPlanner(
      HepMatchOrder.BOTTOM_UP,
      FlinkRuleSets.TABLE_REF_RULES,
      convSubQueryPlan,
      relNode.getTraitSet)

    // 1. decorrelate
    val decorPlan = RelDecorrelator.decorrelateQuery(fullRelNode)

    // 2. normalize the logical plan
    val normRuleSet = getNormRuleSet
    val normalizedPlan = if (normRuleSet.iterator().hasNext) {
      runHepPlanner(HepMatchOrder.BOTTOM_UP, normRuleSet, decorPlan, decorPlan.getTraitSet)
    } else {
      decorPlan
    }

    // 3. optimize the logical Flink plan
    val logicalOptRuleSet = getLogicalOptRuleSet
    val logicalOutputProps = relNode.getTraitSet.replace(FlinkConventions.LOGICAL).simplify()
    val logicalPlan = if (logicalOptRuleSet.iterator().hasNext) {
      runVolcanoPlanner(logicalOptRuleSet, normalizedPlan, logicalOutputProps)
    } else {
      normalizedPlan
    }

    // 4. optimize the physical Flink plan
    val physicalOptRuleSet = getPhysicalOptRuleSet
    val physicalOutputProps = relNode.getTraitSet.replace(FlinkConventions.DATASET).simplify()
    val physicalPlan = if (physicalOptRuleSet.iterator().hasNext) {
      runVolcanoPlanner(physicalOptRuleSet, logicalPlan, physicalOutputProps)
    } else {
      logicalPlan
    }

    physicalPlan
  }

  /**
    * Translates a [[Table]] into a [[DataSet]].
    *
    * The transformation involves optimizing the relational expression tree as defined by
    * Table API calls and / or SQL queries and generating corresponding [[DataSet]] operators.
    *
    * @param table The root node of the relational expression tree.
    * @param queryConfig The configuration for the query to generate.
    * @param tpe   The [[TypeInformation]] of the resulting [[DataSet]].
    * @tparam A The type of the resulting [[DataSet]].
    * @return The [[DataSet]] that corresponds to the translated [[Table]].
    */
  protected def translate[A](
      table: Table,
      queryConfig: BatchQueryConfig)(implicit tpe: TypeInformation[A]): DataSet[A] = {
    val relNode = table.getRelNode
    val dataSetPlan = optimize(relNode)
    translate(dataSetPlan, relNode.getRowType, queryConfig)
  }

  /**
    * Translates a logical [[RelNode]] into a [[DataSet]]. Converts to target type if necessary.
    *
    * @param logicalPlan The root node of the relational expression tree.
    * @param logicalType The row type of the result. Since the logicalPlan can lose the
    *                    field naming during optimization we pass the row type separately.
    * @param queryConfig The configuration for the query to generate.
    * @param tpe         The [[TypeInformation]] of the resulting [[DataSet]].
    * @tparam A The type of the resulting [[DataSet]].
    * @return The [[DataSet]] that corresponds to the translated [[Table]].
    */
  protected def translate[A](
      logicalPlan: RelNode,
      logicalType: RelDataType,
      queryConfig: BatchQueryConfig)(implicit tpe: TypeInformation[A]): DataSet[A] = {
    TableEnvironment.validateType(tpe)

    logicalPlan match {
      case node: DataSetRel =>
        val plan = node.translateToPlan(this, queryConfig)
        val conversion =
          getConversionMapper(
            plan.getType,
            new RowSchema(logicalType),
            tpe,
            "DataSetSinkConversion")
        conversion match {
          case None => plan.asInstanceOf[DataSet[A]] // no conversion necessary
          case Some(mapFunction: MapFunction[Row, A]) =>
            plan.map(mapFunction)
              .returns(tpe)
              .name(s"to: ${tpe.getTypeClass.getSimpleName}")
              .asInstanceOf[DataSet[A]]
        }

      case _ =>
        throw TableException("Cannot generate DataSet due to an invalid logical plan. " +
          "This is a bug and should not happen. Please file an issue.")
    }
  }
}


text:
import { goRight, keydown, state } from "../../src/base/internal.js";
import KeyboardDirectionMixin from "../../src/base/KeyboardDirectionMixin.js";
import { assert, sinon } from "../testHelpers.js";

class KeyboardDirectionMixinTest extends KeyboardDirectionMixin(HTMLElement) {
  constructor() {
    super();
    this[state] = { orientation: "" };
  }

  [goRight]() {
    if (super[goRight]) {
      super[goRight]();
    }
    return true;
  }
}
customElements.define("keyboard-direction-test", KeyboardDirectionMixinTest);

describe("KeyboardDirectionMixin", () => {
  it("maps a Right arrow key to a goRight action", () => {
    const fixture = new KeyboardDirectionMixinTest();
    const spy = sinon.spy(fixture, goRight);
    const result = fixture[keydown]({
      key: "ArrowRight",
      target: fixture,
    });
    assert(spy.calledOnce);
    assert(result);
  });

  it("ignores a Right arrow key when orientation is vertical", () => {
    const fixture = new KeyboardDirectionMixinTest();
    Object.assign(fixture[state], {
      orientation: "vertical",
    });
    const spy = sinon.spy(fixture, goRight);
    const result = fixture[keydown]({
      key: "ArrowRight",
    });
    assert(!spy.calledOnce);
    assert(!result);
  });

  it("ignores a Right arrow key if the meta (command) key was pressed", () => {
    const fixture = new KeyboardDirectionMixinTest();
    const spy = sinon.spy(fixture, goRight);
    const result = fixture[keydown]({
      altKey: true,
      key: "ArrowRight",
    });
    assert(!spy.calledOnce);
    assert(!result);
  });
});


text:
#include <Carna/dicom/DicomManager.h>
#include <Carna/dicom/Patient.h>
#include <Carna/dicom/Study.h>
#include <Carna/dicom/Series.h>
#include <Carna/dicom/SeriesElement.h>
#include <Carna/dicom/DicomExtractionSettings.h>
#include <Carna/dicom/QtDicomSeriesOpeningController.h>
#include <Carna/base/CarnaException.h>
#include <dicom-interface/dicomSeries.h>
#include <QDirIterator>
#include <QXmlStreamWriter>
#include <QXmlSimpleReader>
#include <QEventLoop>
#include <sstream>

namespace Carna
{

namespace dicom
{

// ----------------------------------------------------------------------------------
// XML Node Definitions
// ----------------------------------------------------------------------------------

const static QString XML_DICOM_INDEX = "DicomIndex";
const static QString XML_PATIENT = "Patient";
const static QString XML_PATIENT_NAME = "name";
const static QString XML_SERIES = "Series";
const static QString XML_SERIES_NAME = "name";
const static QString XML_STUDY = "Study";
const static QString XML_STUDY_NAME = "name";
const static QString XML_DICOM_IMAGE = "DicomImage";
const static QString XML_DICOM_IMAGE_FILE = "file";
const static QString XML_DICOM_IMAGE_ZPOSITION = "zPosition";

// ----------------------------------------------------------------------------------
// QtDicomSeriesFileIterator
// ----------------------------------------------------------------------------------

/** \brief  Qt based implementation of abstract \c DicomSeriesFileIterator class
  *
  * \see    SelectSeries
  * \author Leonid Kostrykin
  * \date   2010-2011
  */
class QtDicomSeriesFileIterator : public DicomSeriesFileIterator
{

public:

    /** \brief  Instantiates.
      */
    QtDicomSeriesFileIterator( const QString& sFolderName )
        : it( sFolderName, QDir::Files, QDirIterator::Subdirectories )
    {
    }

    /** \brief  Returns the next file.
      */
    virtual std::string getNextFile()
    {
        const std::string next = it.next().toStdString();
        return next;
    }

    /** \brief  Returns whether there is a next file.
      */
    virtual bool hasNextFile()
    {
        return it.hasNext();
    }

private:

    QDirIterator it;

}; // QtDicomSeriesFileIterator

// ----------------------------------------------------------------------------------
// DicomManager
// ----------------------------------------------------------------------------------

DicomManager::DicomManager( QObject* parent )
    : QObject( parent )
{
}

DicomManager::~DicomManager()
{
    releasePatients();
}

void DicomManager::releasePatients()
{
    for( auto it = patients.begin(); it != patients.end(); ++it )
    {
        delete it->second;
    }
    patients.clear();
}

void DicomManager::openDirectory( const QString& path )
{
    releasePatients();

    failedFiles.clear();
    loadingController.reset( new QtDicomSeriesOpeningController() );

    QtDicomSeriesFileIterator fileIterator( path );
    DicomSeries ds;

    connect( loadingController.get(), SIGNAL( onDirOpened( unsigned int ) ), this, SLOT( setTotalFilesCount( unsigned int ) ) );
    connect( loadingController.get(), SIGNAL( onDirIterationProgress( unsigned int ) ), this, SLOT( setProgressedFilesCount( unsigned int ) ) );
    connect( loadingController.get(), SIGNAL( onNewImage( const Carna::dicom::ImageData& ) ), this, SLOT( processNewImage( const Carna::dicom::ImageData& ) ) );
    connect( loadingController.get(), SIGNAL( onFailed( const QString& ) ), this, SLOT( fail( const QString& ) ) );

    ds.openDicomDir( fileIterator, *loadingController );

    loadingController.reset();
}

void DicomManager::cancel()
{
    if( loadingController.get() )
    {
        loadingController->abort();
    }
}

void DicomManager::setTotalFilesCount( unsigned int totalFilesCount )
{
    this->totalFilesCount = totalFilesCount;
    emit totalFilesCountChanged( totalFilesCount );
}

void DicomManager::setProgressedFilesCount( unsigned int progressedFilesCount )
{
    if( progressedFilesCount == totalFilesCount )
    {
        failedFiles = loadingController->getFailedFiles();
    }

    emit processedFilesCountChanged( progressedFilesCount );

    QEventLoop eventLoop;
    eventLoop.processEvents();

    if( progressedFilesCount == totalFilesCount )
    {
        emit finished();
    }
}

void DicomManager::processNewImage( const ImageData& imageData )
{
    if( patients.find( imageData.patientID ) == patients.end() )
    {
        patients[ imageData.patientID ] = new Patient( imageData.patientID );
    }

    Patient& updated_patient = *patients[ imageData.patientID ];

 // ----------------------------------------------------------------------------------

    Study* updated_study = nullptr;
    const auto& studies = updated_patient.getStudies();
    for( auto study_itr = studies.begin(); study_itr != studies.end(); ++study_itr )
    {
        if( ( **study_itr ).name == imageData.studyID )
        {
            updated_study = *study_itr;
            break;
        }
    }

    if( updated_study == nullptr )
    {
        updated_study = new Study( imageData.studyID );
        updated_patient.put( updated_study );
    }

 // ----------------------------------------------------------------------------------

    Series* updated_series = nullptr;
    const auto& series = updated_study->getSeries();
    for( auto series_itr = series.begin(); series_itr != series.end(); ++series_itr )
    {
        if( ( **series_itr ).name == imageData.seriesID )
        {
            updated_series = *series_itr;
            break;
        }
    }

    if( updated_series == nullptr )
    {
        updated_series = new Series( imageData.seriesID );
        updated_study->put( updated_series );
    }

 // ----------------------------------------------------------------------------------

    updated_series->put( new SeriesElement( imageData.fileName, imageData.zPosition ) );
}

const std::map< std::string, Patient* >& DicomManager::getPatients() const
{
    return patients;
}

const std::deque< std::string >& DicomManager::getFailedFiles() const
{
    return failedFiles;
}

void DicomManager::saveIndex( const QString& fileName )
{
    QFile file( fileName );
    if( !file.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
    {
        this->fail( "Failed opening '" + fileName + "' for writing." );
        return;
    }

    QXmlStreamWriter xml( &file );
    xml.setAutoFormatting( true );
    xml.writeStartDocument();

    xml.writeStartElement( XML_DICOM_INDEX );

    for( auto patient_itr = patients.begin(); patient_itr != patients.end(); ++patient_itr )
    {
        const Patient& patient = *( patient_itr->second );
        xml.writeStartElement( XML_PATIENT );
        xml.writeAttribute( XML_PATIENT_NAME, QString::fromStdString( patient.name ) );

        for( auto study_itr = patient.getStudies().begin(); study_itr != patient.getStudies().end(); ++study_itr )
        {
            const Study& study = **study_itr;
            xml.writeStartElement( XML_STUDY );
            xml.writeAttribute( XML_STUDY_NAME, QString::fromStdString( study.name ) );

            for( auto series_itr = study.getSeries().begin(); series_itr != study.getSeries().end(); ++series_itr )
            {
                const Series& series = **series_itr;
                xml.writeStartElement( XML_SERIES );
                xml.writeAttribute( XML_SERIES_NAME, QString::fromStdString( series.name ) );

                for( auto file_itr = series.getElements().begin(); file_itr != series.getElements().end(); ++file_itr )
                {
                    const SeriesElement& element = **file_itr;
                    xml.writeStartElement( XML_DICOM_IMAGE );
                    xml.writeAttribute( XML_DICOM_IMAGE_FILE, QString::fromStdString( element.fileName ) );
                    xml.writeAttribute( XML_DICOM_IMAGE_ZPOSITION, QString::number( element.zPosition ) );
                    xml.writeEndElement();
                }

                xml.writeEndElement();
            }

            xml.writeEndElement();
        }

        xml.writeEndElement();
    }

    xml.writeEndElement();
    xml.writeEndDocument();

    file.close();

    if( file.exists() )
    {
        emit finished();
    }
    else
    {
        this->fail( "Failed writing '" + fileName + "' for unknown reason." );
    }
}

void DicomManager::openIndex( const QString& fileName )
{
    releasePatients();

    QFile file( fileName );
    if( !file.exists() )
    {
        std::stringstream ss;
        ss << "Failed opening '" << fileName.toStdString() << "' for reading.";
        this->fail( QString::fromStdString( ss.str() ) );
        return;
    }

    QXmlSimpleReader xmlReader;
    QXmlInputSource xmlSource( &file );

    class SaxParser : public QXmlDefaultHandler
    {

    public:

        SaxParser( std::map< std::string, Patient* >& patients )
            : patients( patients )
            , currentScope( INDICES )
            , currentPatient( nullptr )
            , currentStudy( nullptr )
            , currentSeries( nullptr )
        {
        }

        virtual bool startElement( const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& attributes )
        {
            switch( currentScope )
            {

                case INDICES:
                {
                    if( localName == XML_DICOM_INDEX )
                    {
                        currentScope = PATIENTS;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case PATIENTS:
                {
                    if( localName == XML_PATIENT )
                    {
                        currentPatient = new Patient( attributes.value( XML_PATIENT_NAME ).toStdString() );
                        patients[ currentPatient->name ] = currentPatient;

                        currentScope = STUDIES;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case STUDIES:
                {
                    if( localName == XML_STUDY )
                    {
                        CARNA_ASSERT( currentPatient != nullptr );

                        currentStudy = new Study( attributes.value( XML_STUDY_NAME ).toStdString() );
                        currentPatient->put( currentStudy );

                        currentScope = SERIES;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case SERIES:
                {
                    if( localName == XML_SERIES )
                    {
                        CARNA_ASSERT( currentPatient != nullptr );
                        CARNA_ASSERT( currentStudy != nullptr );

                        currentSeries = new Series( attributes.value( XML_SERIES_NAME ).toStdString() );
                        currentStudy->put( currentSeries );

                        currentScope = ELEMENTS;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case ELEMENTS:
                {
                    if( localName == XML_DICOM_IMAGE )
                    {
                        CARNA_ASSERT( currentPatient != nullptr );
                        CARNA_ASSERT( currentStudy != nullptr );
                        CARNA_ASSERT( currentSeries != nullptr );

                        bool ok = false;
                        const std::string fileName = attributes.value( XML_DICOM_IMAGE_FILE ).toStdString();
                        const double zPosition = attributes.value( XML_DICOM_IMAGE_ZPOSITION ).toDouble( &ok );

                        if( !ok )
                        {
                            return false;
                        }

                        SeriesElement* const element = new SeriesElement( fileName, zPosition );
                        currentSeries->put( element );

                        currentScope = ELEMENT;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

            }
            return true;
        }

        virtual bool endElement( const QString& namespaceURI, const QString& localName, const QString& qName )
        {
            switch( currentScope )
            {

                case PATIENTS:
                {
                    if( localName == XML_DICOM_INDEX )
                    {
                        currentScope = INDICES;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case STUDIES:
                {
                    if( localName == XML_PATIENT )
                    {
                        currentScope = PATIENTS;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case SERIES:
                {
                    if( localName == XML_STUDY )
                    {
                        currentScope = STUDIES;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case ELEMENTS:
                {
                    if( localName == XML_SERIES )
                    {
                        currentScope = SERIES;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

                case ELEMENT:
                {
                    if( localName == XML_DICOM_IMAGE )
                    {
                        currentScope = ELEMENTS;
                        break;
                    }
                    else
                    {
                        return false;
                    }
                }

            }
            return true;
        }

    private:

        std::map< std::string, Patient* >& patients;

        enum Scope
        {
            INDICES, PATIENTS, STUDIES, SERIES, ELEMENTS, ELEMENT
        }
        currentScope;

        Patient* currentPatient;
        Study* currentStudy;
        Series* currentSeries;

    }; // SaxParser

    SaxParser parser( patients );
    xmlReader.setContentHandler( &parser );
    xmlReader.setErrorHandler( &parser );

    if( !xmlReader.parse( xmlSource ) )
    {
        std::stringstream ss;
        ss << "Failed reading '" << fileName.toStdString() << "' due to unexpected format.";
        this->fail( QString::fromStdString( ss.str() ) );
        return;
    }

    emit finished();
}

void DicomManager::extractSeries( const DicomExtractionSettings& settings )
{
    unsigned long file_index = 0;
    QDir dst_dir( settings.destination );

 // compute files count

    std::deque< const SeriesElement* > elements;
    unsigned int files_count = 0;
    for( auto series_itr = settings.series.begin(); series_itr != settings.series.end(); ++series_itr )
    {
        const Series* const series = *series_itr;
        files_count += series->getElements().size();
        for( auto element_itr = series->getElements().begin(); element_itr != series->getElements().end(); ++element_itr )
        {
            const SeriesElement* const element = *element_itr;
            elements.push_back( element );
        }
    }

    emit totalFilesCountChanged( files_count );

 // copy files

    unsigned int processed_files = 0;
    for( auto element_itr = elements.begin(); element_itr != elements.end(); ++element_itr )
    {
        while( dst_dir.exists( QString::number( file_index ) ) )
        {
            ++file_index;
        }

        QString dst_filename = dst_dir.filePath( QString::number( file_index ) );

        const SeriesElement& element = **element_itr;
        QFile src( QString::fromStdString( element.fileName ) );
        if( !src.copy( dst_filename ) )
        {
            std::stringstream ss;
            ss << "Failed copying '" << element.fileName << "' to '" << dst_filename.toStdString() << "'";
            fail( QString::fromStdString( ss.str() ) );
            return;
        }

        emit processedFilesCountChanged( ++processed_files );
    }

 // finish

    emit finished();
}

void DicomManager::fail( const QString& message )
{
    releasePatients();

    emit failed( message );
    emit failed();
}

}  // namespace Carna :: dicom

}  // namespace Carna


text:
typedef Eigen::SparseMatrix<double> SpMat;
typedef std::vector<std::tuple<double,double,int> > Index;
typedef std::vector<Eigen::Triplet<double> > Triplet;


text:
fn underscore_test(r#_: u32) {
    //~^ ERROR `r#_` is not currently supported.
}


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
  <meta name="viewport" content="width=device-width" />
  <title>Rocket Pitches</title>

  <link rel="stylesheet" href="css/style.css" />

  <link href='http://fonts.googleapis.com/css?family=Bevan' rel='stylesheet' type='text/css'>
  <link href='http://fonts.googleapis.com/css?family=Muli' rel='stylesheet' type='text/css'>

Wipperzeit large

					log-in

Wipperzeitmenulog-in

				View Ideas
				The Process
				Join
				About WZ

								High Concepts
								30Sec Pitches
								Rocket Pitches

Rocket Pitches

Highlight the major concepts of an idea in a easily digestable format.

Learn how to develop a great pitch

Submit a project

Got a great idea for a game? Why not share it.

Submit a new project

								sort:
								new
								activity
								a-z

Origami Hyabusa!

											submitted by:
KenFarris
											<time pubdate time="17:39:5717:39:57" title="17:39">3h ago</time>

Brought to life by an enchanted bolt of lightning paper peregrines hunt for survivial and to continue their quest for the Ancient Aerie that will make them real raptors once more.

											view
											follow
											comments
											share
											spam?

												view
												follow
												comments
												share

Atlatl

											submitted by:
KenFarris
											<time pubdate time="17:39:5717:39:57" title="17:39">3h ago</time>

Brave the Bering Straits as a Paleo traveler with your intrepid clan as you seek the fabled fertile Plains of Folsom where Modern American humanity begins.

											view
											follow
											comments
											share
											spam?

												view
												follow
												comments
												share

								see more projects

Link

Link

Link

Link

Link

Link

Link

Link

© Wipperzite 2013 - All Rights Reserved - Wipperzeit LLC - 1234 Anyoad, Ann Arbor, MI 48197


text:
because I discovered [http://libraries.io/](http://libraries.io/) haha.

## Motivation
- I like to be notified when some legacy projects finally release a new version
- I like to stay on top of some frequently updating projects
- I like to update ASAP when there are security fixes for my favorite frameworks

## Contribution
All PRs welcome!

### How to setup
- install [docker](https://docs.docker.com/v1.8/installation/)
    - [docker-toolbox](https://github.com/docker/toolbox/releases) if not linux
- install [docker-compose](https://github.com/docker/compose/releases)
    - try [myboot2docker](https://github.com/wharsojo/myboot2docker) if using `docker-toolbox`, `boot2docker` essentially
- fork and clone the repo
- `cd` into the repo dir
- `git submodule update --init`
- `bin/bootstrap` (wait for all the downloads...)
- `docker-compose up`

### Problems
Please do not hesitate to file an issue if encountering any problem, either when using the app or contributing to the app.


text:
<Record>
<Term>Paranasal Sinus Diseases</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Nose Diseases</ParentTerm>
<ClassificationPath>Respiratory Tract Diseases/Nose Diseases/Paranasal Sinus Diseases</ClassificationPath>
<ClassificationPath>Otorhinolaryngologic Diseases/Nose Diseases/Paranasal Sinus Diseases</ClassificationPath>
<BroaderTerm>Respiratory Tract Diseases</BroaderTerm>
<BroaderTerm>Nose Diseases</BroaderTerm>
<BroaderTerm>Otorhinolaryngologic Diseases</BroaderTerm>
<BroaderTerm>Paranasal Sinus Diseases</BroaderTerm>
<ChildTerm>Paranasal Sinus Neoplasms</ChildTerm>
<ChildTerm>Sinusitis</ChildTerm>
<Synonym>Paranasal Sinus Disease</Synonym>
<Synonym>Paranasal Sinus Diseases</Synonym>
<Description>Diseases affecting or involving the PARANASAL SINUSES and generally manifesting as inflammation, abscesses, cysts, or tumors.</Description>
<Source>MeSH</Source>
</Record>


text:
package nl.esciencecenter.xenon.adaptors.shared.ssh;

import org.junit.Test;

public class SSHUtilFixedClientTest {

    @Test
    public void test_() {
    }
}


text:
package controllers

import play.api._
import play.api.mvc._
import play.api.db.slick._
import models._
import play.api.Play.current

case class HomeViewModel(randomSpecimen: Option[Loaded[SpecimenWithImages]], latestArticles: List[Loaded[Article]])

trait ApplicationController extends Controller { this: ModelServicesComponent =>
  def home = DBAction { implicit rs =>
    val model = HomeViewModel(
      Services.SpecimenService.randomSpecimen,
      Services.ArticleService.latestArticles(3))

    Ok(views.html.app.home(model))
  }

  def contacts = DBAction { implicit rs =>
    Ok(views.html.app.contacts())
  }

  def testimonials = DBAction { implicit rs =>
    Ok(views.html.app.testimonials(Services.TestimonialService.allTestimonials))
  }

  def todo = Action {
    NotFound(views.html.app.todo())
  }
}

object ApplicationController extends ApplicationController with ModelServicesComponent


text:
#ifndef _SDL_uikitwindow_h
#define _SDL_uikitwindow_h

#include "../SDL_sysvideo.h"
#import "SDL_uikitvideo.h"
#import "SDL_uikitopenglview.h"
#import "SDL_uikitviewcontroller.h"

typedef struct SDL_WindowData SDL_WindowData;

extern int UIKit_CreateWindow(_THIS, SDL_Window * window);
extern void UIKit_ShowWindow(_THIS, SDL_Window * window);
extern void UIKit_HideWindow(_THIS, SDL_Window * window);
extern void UIKit_RaiseWindow(_THIS, SDL_Window * window);
extern void UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen);
extern void UIKit_DestroyWindow(_THIS, SDL_Window * window);
extern SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window,
                                      struct SDL_SysWMinfo * info);

@class UIWindow;

struct SDL_WindowData
{
    UIWindow *uiwindow;
    SDL_uikitopenglview *view;
    SDL_uikitviewcontroller *viewcontroller;
};

#endif /* _SDL_uikitwindow_h */

/* vi: set ts=4 sw=4 expandtab: */


text:
@interface Person : SPModel
@property (nonatomic) NSString *name;
@property (nonatomic) NSString *surname;
@property (nonatomic) NSString *number;
@property (nonatomic) NSInteger age;
@property (nonatomic) long long money;

@property (nonatomic) Car *car;
@end


text:
module Napa
  class Logger
    class Output
      class Stdout
        def initialize
          if enable?
            Logging.appenders.stdout('stdout', options)
            Napa::Logger.logger.add_appenders 'stdout'
          end
        end

        def options
          {}.tap do |o|
            o[:layout] = Logging.layouts.json if Napa::Logger.config.format == :json
            o[:layout] = Logging.layouts.yaml if Napa::Logger.config.format == :yaml
          end
        end

        def enable?
          Napa::Logger.config.output.include?(:stdout)
        end
      end
    end
  end
end


text:
var program = require('commander');
var fs = require('fs');
var request = require('request');

// Get version from package.json.
var version = require('./package.json').version;

program
  .command('install [type]')
  .description('Use this command to install a .gitignore file.')
  .action(function(type, options) {

    // Show error message if type is not specified.
    if (!type) {
      console.log('Error: type missing');
      program.help();
    }

    var url = 'https://raw.githubusercontent.com/github/gitignore/master/' + type + '.gitignore';

    var options = {
      url: url,
      headers: {
        'User-Agent': 'request'
      }
    }

    // Make the request.
    request(options, function (error, response, body) {
      // Handle error.
      if (response.statusCode == 404) {
        return console.log('File not found. Remember that type is case sensitive.');
      }

      if (!error && response.statusCode == 200) {
        fs.writeFile('.gitignore', body, 'utf8', function (err) {
           if (err) return console.log(err);

           // Show a success message.
           console.log('Successfully added .gitignore for ' + type + '.');
        });
      }
    });
  });

program.parse(process.argv);

if (!program.args.length) program.help();


text:
"use strict";

Aural.Utils.Scala.File = function(content) {
	this.description = '';
	this.numberIntervals = 0;
	this.intervals = [];

	if(content) {
		this.parse(content);
	}
};

/**
 * Description of the scala file
 * @type {String}
 */
Aural.Utils.Scala.File.prototype.description = null;

/**
 * Number of intervals as defined in the file
 * @type {Number}
 */
Aural.Utils.Scala.File.prototype.numberIntervals = null;

/**
 * Array of intervals
 * @type {Array}
 */
Aural.Utils.Scala.File.prototype.intervals = null;

/**
 * Parse the content of a scala file and populate the object
 * @param {String} contentFile - Content of the scala file
 * @private
 */
Aural.Utils.Scala.File.prototype.parse = function(contentFile) {
	var lines = (contentFile + "\r\n").match(/^.*[\n\r]+|$/gm),
		countLines = 0,
		line,
		interval,
		parsedInterval;

	this.intervals = [];

	for(var x = 0; x < lines.length; x++) {
		line = lines[x];

		if(line.indexOf('!') !== 0) { //exclude comment lines
			switch(countLines) {
				case 0: //first non-commented line is description
					this.description = line.trim();
					break;
				case 1: //second non-commented line is the number of intervals
					this.numberIntervals = parseInt(line, 10);
					break;
				default: //every other non-commented lines are interval values
					interval = line.trim();

					if(interval !== '') {
						parsedInterval = this.treatInterval(interval);

						if(!isNaN(parsedInterval)) {
							this.intervals.push(parsedInterval);
						}
					}
					break;
			}

			countLines++;
		}
	}

	if(this.intervals.length !== this.numberIntervals) {
		throw 'Error in file format : incorrect number of valid intervals';
	}
};

/**
 * Parse a scala interval value and return it as cents
 * @param {String} interval - Interval in any of the valid interval scala format
 * @returns {Number} Interval in cents
 * @private
 */
Aural.Utils.Scala.File.prototype.treatInterval = function(interval) {
	var isCent = false,
		convertedInterval;

	interval = interval.split(' ')[0];

	if(interval.indexOf('/') > 0) { //ratio notation
		var division = interval.split('/');
		convertedInterval = parseFloat(division[0]) / parseFloat(division[1]);
	} else {
		if(interval.indexOf('.') > 0) { //cent notation
			convertedInterval = parseFloat(interval);
			isCent = true;
		} else { //integer ratio notation
			convertedInterval = parseFloat(interval);
		}
	}

	if(!isCent) {
		if(convertedInterval < 0) {
			throw 'Error in file format : negative ratio as interval';
		}

		convertedInterval = 1200 * Math.log(convertedInterval) / Math.log(2);
	}

	return convertedInterval;
};