text:
require 'requirejs/error'

module RequirejsHelper
  # EXPERIMENTAL: Additional priority settings appended to
  # any user-specified priority setting by requirejs_include_tag.
  # Used for JS test suite integration.
  mattr_accessor :_priority
  @@_priority = []

  def _requirejs_data(name, &block)
    {}.tap do |data|
      if name
        name += ".js" unless name =~ /\.js$/
        data['main'] = _javascript_path(name).sub(/\.js$/,'')
      end

      data.merge!(yield controller) if block_given?
    end.map do |k, v|
      %Q{data-#{k}="#{v}"}
    end.join(" ")
  end

  def requirejs_include_tag(name=nil, &block)
    requirejs = Rails.application.config.requirejs

    if requirejs.loader == :almond
      name = requirejs.module_name_for(requirejs.build_config['modules'][0])
      return _almond_include_tag(name, &block)
    end

    html = ""

    _once_guard do
      unless requirejs.run_config.empty?
        run_config = requirejs.run_config.dup
        unless _priority.empty?
          run_config = run_config.dup
          run_config[:priority] ||= []
          run_config[:priority].concat _priority
        end
        if Rails.application.config.assets.digest
          modules = requirejs.build_config['modules'].map { |m| requirejs.module_name_for m }

          # Generate digestified paths from the modules spec
          paths = {}
          modules.each { |m| paths[m] = _javascript_path(m).sub /\.js$/,'' }

          if run_config.has_key? 'paths'
            # Add paths for assets specified by full URL (on a CDN)
            run_config['paths'].each { |k,v| paths[k] = v if v =~ /^https?:/ }
          end

          # Override user paths, whose mappings are only relevant in dev mode
          # and in the build_config.
          run_config['paths'] = paths
        end
        html.concat <<-HTML
        <script>var require = #{run_config.to_json};</script>
        HTML
      end

      html.concat <<-HTML
      <script #{_requirejs_data(name, &block)} src="#{_javascript_path 'require.js'}"></script>
      HTML

      html.html_safe
    end
  end

  def _once_guard
    if defined?(controller) && controller.requirejs_included
      raise Requirejs::MultipleIncludeError, "Only one requirejs_include_tag allowed per page."
    end

    retval = yield

    controller.requirejs_included = true if defined?(controller)
    retval
  end

  def _almond_include_tag(name, &block)
    "<script src='#{_javascript_path name}'></script>\n".html_safe
  end

  def _javascript_path(name)
    if defined?(javascript_path)
      javascript_path(name)
    else
      "/assets/#{name}"
    end
  end
end


text:
<?php
/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 2020-01-22
 * Time: 14:30
 */

namespace Enhavo\Bundle\BlockBundle\Tests\Block\Type;

use Enhavo\Bundle\BlockBundle\Block\Type\VideoBlockType;
use PHPUnit\Framework\TestCase;
use Enhavo\Bundle\BlockBundle\Block\BlockTypeInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class VideoBlockTypeTest extends TestCase
{
    public function testGetType()
    {
        $this->assertEquals('video', VideoBlockType::getName());
    }

    public function testConfigureOption()
    {
        $serviceMock = $this->getMockBuilder(ContainerInterface::class)->getMock();

        $type = new VideoBlockType($serviceMock);
        $options = $this->createOptions($type);
        $this->assertIsArray($options);
    }

    protected function createOptions(BlockTypeInterface $type, $options = [])
    {
        $resolver = new OptionsResolver();
        $type->configureOptions($resolver);
        return $resolver->resolve($options);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package cfvbaibai.cardfantasy.engine.skill;

import java.util.List;

import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.SkillUseInfo;
import cfvbaibai.cardfantasy.engine.SkillResolver;
import cfvbaibai.cardfantasy.engine.HeroDieSignal;
import cfvbaibai.cardfantasy.engine.Player;

public final class AllDelay {
    public static void apply(SkillUseInfo skillUseInfo, SkillResolver resolver, CardInfo attacker, Player defender)
            throws HeroDieSignal {
        int summonDelayOffset = skillUseInfo.getSkill().getImpact();
        List<CardInfo> allHandCards = defender.getHand().toList();
        resolver.getStage().getUI().useSkill(attacker, allHandCards, skillUseInfo.getSkill(), true);
        if(resolver.resolveStopDelay(defender))
        {
            return;
        }
        for (CardInfo card : allHandCards) {
            if(resolver.resolveStopCardDelay(card))
            {
                continue;
            }
            int summonDelay = card.getSummonDelay();
            resolver.getStage().getUI().increaseSummonDelay(card, summonDelayOffset);
            card.setSummonDelay(summonDelay + summonDelayOffset);
        }
    }
}


text:
package art_concurrent_book.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * Created by yaojie.hou on 2017/6/19.
 */
public class TwinsLock implements Lock {

	private final Sync sync = new Sync(2);
	private static final class Sync extends AbstractQueuedSynchronizer {

		Sync(int count) {
			setState(count);
		}

		@Override
		protected int tryAcquireShared(int reduceCount) {
			for (;;) {
				int currentCount = getState();
				int newCount = currentCount - reduceCount;
				if(newCount < 0 || compareAndSetState(currentCount, newCount)) {
					return newCount;
				}
			}
		}

		@Override
		protected boolean tryReleaseShared(int returnCount) {
			for (;;) {
				int currentCount = getState();
				int	newCount = currentCount + returnCount;
				if(compareAndSetState(newCount, currentCount)) {
					return true;
				}
			}
		}

		final ConditionObject newCondition() {
			return new ConditionObject();
		}
	}

	@Override
	public void lock() {
		sync.acquireShared(1);
	}

	@Override
	public void unlock() {
		sync.releaseShared(1);
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {
		sync.acquireSharedInterruptibly(1);
	}

	@Override
	public boolean tryLock() {
		return sync.tryAcquireShared(1) >= 0;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
	}

	@Override
	public Condition newCondition() {
		return sync.newCondition();
	}
}


text:
class BSTNode {
    int key;
    BSTNode left;
    BSTNode right;

    public static void main(String[] args) {

    }
}


text:
package org.jetbrains.lang.manifest.psi.impl;

import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import org.jetbrains.lang.manifest.psi.Section;

/**
 * @author Robert F. Beeger (robert@beeger.net)
 */
public class SectionImpl extends ASTWrapperPsiElement implements Section {
  public SectionImpl(ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    return "Section";
  }
}


text:
import React from 'react'; // tslint:disable-line:no-unused-variable
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import classNames from 'classnames';

import AgentTypeIcon from 'common/components/AgentTypeIcon';
import { getContentType, getMediaTypeFromContentType } from 'common/util/ContentTypes';
import { getStatusCodeFilteredWebServiceExchanges, getSelectedExchange, getTimelineEventsOffsetBoundary } from '../ServiceSelectors';
import StackFrame from 'common/components/StackFrame';
import Icon from 'common/components/Icon';
import { IExchangeModel } from '../ServiceInterfaces';
import { IStoreState } from 'client/IStoreState';
import RouteButton from 'common/components/RouteButton';
import { serviceTabName } from '../ServiceConfig';
import StatusLabel from 'common/components/StatusLabel';
import { formatMilliseconds, TimeDuration } from 'common/components/TimeDuration';
import { toStringWithFixedPoints } from 'common/util/StringUtilities';
import TimelineActivity from 'common/components/timeline/TimelineActivity';
import { TimelineTable, ITimelineTableProps, ITimelineTableCallbacks, getActivityColumnPlaceholder } from 'common/components/timeline/TimelineTable';
import UrlText from 'common/components/UrlText';

import commonStyles from 'common/components/Common.scss';
import styles from './ServiceTable.scss';

// tslint:disable-next-line:variable-name
const ServiceActivityBar =
    (props: { activity: IExchangeModel, metadata, totalDuration: number }) => {
        const { activity, metadata } = props;

        const metadataContainer = metadata
            ? (

                    {metadata}

            )
            : undefined;

        let responseStart = 0;
        let responseEnd = 0;
        let hasResponseStart = true;

        if (activity.response && activity.response.payload && activity.response.payload.timing) {
            responseStart = activity.response.payload.timing.responseStart;
            responseEnd = activity.response.payload.timing.responseEnd;
        }
        if (responseStart === undefined) {
            responseStart = 0;
            hasResponseStart = false;
        }

        const { totalDuration } = props;

        const requestStyle: React.CSSProperties = {
            flexGrow: responseStart / responseEnd
        };

        const responseStyle: React.CSSProperties = {
            flexGrow: (responseEnd - responseStart) / responseEnd
        };

        let title = `From start: ${formatMilliseconds(activity.offset)}`;

        const contentType = getContentType(activity.response.payload.headers);
        const mediaType = contentType ? getMediaTypeFromContentType(contentType) : undefined;

        if (mediaType) {
            title += `\nContent type: ${mediaType}`;
        }

        const percentageDuration = (responseEnd / totalDuration) * 100;
        const percentageDurationString = toStringWithFixedPoints(percentageDuration, 1);

        if (hasResponseStart) {
            title += `\nSending: ${formatMilliseconds(responseStart)}`
                + `\nDownloading: ${formatMilliseconds(responseEnd - responseStart)}`;
        }
        title +=
            `\nTotal: ${formatMilliseconds(responseEnd)} (${percentageDurationString}%)`;

        return (

                {metadataContainer}

        );
    };

const activityBarFunc = (activity: IExchangeModel, params, metadata) => {
    const { totalDuration } = params;

    return <ServiceActivityBar activity={activity} metadata={metadata} totalDuration={totalDuration} />;
};

const activityFunc = (activity: IExchangeModel, minOffset: number, maxOffset: number, params) => {
    if (activity.response) {
        const metadata = (

                <TimeDuration duration={activity.duration} />

        );

        return <TimelineActivity activity={activity} activityBarFunc={activityBarFunc} minOffset={minOffset} maxOffset={maxOffset} metadata={metadata} params={params} />;
    }
    else {
        const noResponseDataText = 'No response data';

        const title
            = `From start: ${formatMilliseconds(activity.offset)}`
            + `\n${noResponseDataText}`;

        return (

                {noResponseDataText}

        );
    }
};

const indexColumn = {
    headerFunc: () => {
        return (

                <AgentTypeIcon />
                #

        );
    },
    valueFunc: (activity: IExchangeModel) => {
        return (

                <AgentTypeIcon agentType={activity.agent} />
                {activity.index}

        );
    },
    width: 8
};

const urlColumn = {
    headerFunc: () => {
        return Url;
    },
    valueFunc: (activity: IExchangeModel) => {
        const urlText = activity.request
            ? <UrlText alignHttpsIcon={true} url={activity.request.payload.url} protocol={activity.request.payload.protocol.identifier} />
            : <UrlText alignHttpsIcon={true} url="-" protocol="http" />;

        const link = activity.linkedContextId
            ? (
                <RouteButton
                    className={styles.serviceTableLinkButton}
                    label="This call is an application server request. Click to view more details."
                    to={`/requests/${activity.linkedContextId}/request`}>
                    <Icon
                        target={Icon.paths.Go}
                        className={styles.serviceTableLinkIcon}
                        pathClassName={styles.serviceTableLinkIconPath} />
                </RouteButton>
            )
            // To preserve alignment of URL text and links, return a placeholder
 with the margin and width of the button and icon...
            :
;

        return (

                {urlText}
                {link}

        );
    },
    width: 24
};

const methodColumn = {
    headerClassName: styles.serviceTableMethodColumn,
    headerFunc: () => 'Method',
    valueClassName: commonStyles.trimText,
    valueFunc: (activity: IExchangeModel) => {
        return activity.request
            ? {activity.request.payload.method}
            : '-';
    },
    width: 8
};

const statusColumn = {
    headerFunc: () => 'Status',
    valueFunc: (activity: IExchangeModel) => {
        return activity.response
            ? <StatusLabel statusCode={activity.response.payload.statusCode} statusMessage={activity.response.payload.statusMessage} />
            : undefined;
    },
    width: 9
};

const locationColumn = {
    headerFunc: () => 'Location',
    valueFunc: (activity: IExchangeModel) => {
        const payload = (activity.request && activity.request.payload) ? activity.request.payload : undefined;
        const topFrame = (payload && payload.frames) ? payload.frames[0] : undefined;

        return <StackFrame frame={topFrame} />;
    },
    width: 10
};

const columns = [
    indexColumn,
    urlColumn,
    methodColumn,
    statusColumn,
    locationColumn,
    getActivityColumnPlaceholder()
];

function mapStateToProps(state: IStoreState, props): Partial<ITimelineTableProps<{}>> {
    const { exchanges } = getStatusCodeFilteredWebServiceExchanges(state);
    let { minOffset, maxOffset } = getTimelineEventsOffsetBoundary(state);

    // timeline table enforces maxOffset > minOffset, so ensure that here.
    if (minOffset === maxOffset) {
        maxOffset += 1;
    }

    return {
        activityFunc,
        columns,
        maxOffset,
        minOffset,
        offsetTicks: 5,
        params: {
            totalDuration: maxOffset
        },
        rowClassName: commonStyles.tableSelectableRow,
        selectedActivity: getSelectedExchange(state),
        selectedRowClassName: commonStyles.tableSelectedRow,
        spans: exchanges,
        shouldAutoSelectFirstActivity: true
    };
}

function mapDispatchToProps(dispatch, props): ITimelineTableCallbacks {
    return {
        onSelectActivity: (activity: IExchangeModel) => {
            const requestId = activity.request ? activity.request.context.id : activity.response.context.id;
            const exchangeId = activity.eventId;

            dispatch(push(`/requests/${requestId}/${serviceTabName}/${exchangeId}`));
        }
    };
}

export const ServiceTable = connect(mapStateToProps, mapDispatchToProps)(TimelineTable); // tslint:disable-line:variable-name

export default ServiceTable;

// WEBPACK FOOTER //
// ./src/client/routes/requests/details/service/views/ServiceTable.tsx


text:
package org.dashbuilder.dataset.engine.group;

import org.dashbuilder.dataset.ColumnType;
import org.dashbuilder.dataset.group.GroupStrategy;

public interface IntervalBuilderLocator {

    IntervalBuilder lookup(ColumnType columnType, GroupStrategy strategy);
}


text:
/**
 * index
 *
 * @author: fengwang
 * @date: 2017-10-17 11:07
 * @version: 1.0
 */
$(function () {
    //搜索关键字
    var keyword = '';

    var table = $('#recordTable').DataTable({
        paging: true,
        lengthChange: false,
        searching: false,
        ordering: false,
        order: [[1, "desc"]],
        info: true,
        autoWidth: false,
        processing: true,
        serverSide: true,
        ajax: {
            url: gContextPath + "/api/m/signature/" + $('#signature').val() + "/record/list",
            type: "POST",
            data: function (d) {
                d.keyword = keyword;
            }
        },
        columnDefs: [
            {
                render: function (data, type, row) {
                    var html = '' + row.signatureCallRecord.signature + '';
                    return html;
                },
                targets: 0
            },
            {
                render: function (data, type, row) {
                    var html = '' + row.signatureCallRecord.appCode + '';
                    return html;
                },
                targets: 1
            },
            {
                render: function (data, type, row) {
                    var html = '' + row.signatureCallRecord.callIp + '';
                    return html;
                },
                targets: 2
            },
            {
                render: function (data, type, row) {
                    var html = '' + row.signatureCallRecord.callTime + '';
                    return html;
                },
                targets: 3
            }
        ]
    });

    table.on('draw', function () {
        //绑定事件
        bindEvent();
    });

    //搜索
    function search() {
        keyword = $('.search-keyword').val();
        table.search(keyword).draw();
    }

    //绑定事件
    function bindEvent() {

    }

    $(".table-search").click(function () {
        search();
    });
});


text:
<html>
<head>
<style type="text/css">
input {
  color: white;
  background-color: green;
}
input::-moz-selection {
  color: red;
  background-color: blue;
}
</style>
</head>
<body onload="document.getElementById('i').select();">
<input value="text" id="i">
</body>
</html>


text:
from __future__ import absolute_import
from mayavi.preferences.preference_manager import *


text:
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.PythonTools.Infrastructure {
    sealed class Program {
        public static int Main(string[] args) {
            int port;
            try {
                port = int.Parse(args[0]);
            } catch (IndexOutOfRangeException) {
                Console.WriteLine("Port number expected");
                return 1;
            }

            try {
                return Run(port).WaitAndUnwrapExceptions();
            } catch (OperationCanceledException) {
                return 2;
            } catch (IOException) {
                return 255;
            } catch (Exception ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(typeof(Program)));
                return 255;
            }
        }

        private static async Task<int> Run(int port) {
            using (var client = new TcpClient()) {
                await client.ConnectAsync(IPAddress.Loopback, port);

                var utf8 = new UTF8Encoding(false);
                using (var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true))
                using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                    var filename = await reader.ReadLineAsync();
                    var args = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => utf8.GetString(Convert.FromBase64String(s)))
                        .ToList();
                    var workingDir = await reader.ReadLineAsync();
                    var env = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => s.Split(new[] { '=' }, 2))
                        .Select(s => new KeyValuePair<string, string>(s[0], utf8.GetString(Convert.FromBase64String(s[1]))))
                        .ToList();
                    var outputEncoding = await reader.ReadLineAsync();
                    var errorEncoding = await reader.ReadLineAsync();

                    return await ProcessOutput.Run(
                        filename,
                        args,
                        workingDir,
                        env,
                        false,
                        new StreamRedirector(writer, outputPrefix: "OUT:", errorPrefix: "ERR:"),
                        quoteArgs: false,
                        elevate: false,
                        outputEncoding: string.IsNullOrEmpty(outputEncoding) ? null : Encoding.GetEncoding(outputEncoding),
                        errorEncoding: string.IsNullOrEmpty(errorEncoding) ? null : Encoding.GetEncoding(errorEncoding)
                    );
                }
            }
        }
    }
}


text:
{% extends 'base.html' %}

{% block title %} Group 2 Exerises {% endblock %}

{% block content %}

These exercises are meant to be done in conjunction with one another

<form action="/{{ user.username }}/update_workout/{{ workout_id }}/{{ group }}/" method="post">
{% csrf_token %}

Squats
<button type="button" class="btn btn-default btn-xs" onclick="$('#video1').toggle();">

    </button>

{{ form1.as_p }}

Lsits
<button type="button" class="btn btn-default btn-xs" onclick="$('#video2').toggle();">

    </button>

{{ form2.as_p }}
<input type="submit" value="Submit" />
</form>

{% endblock %}


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#ifndef Charts_Coordinates_hpp
#define Charts_Coordinates_hpp

#include <TRCharts/Common.hpp>

#include <ostream>

namespace Charts
{

	struct Coordinates;

	struct GeneratedCoordinates
	{
		double abscissa;
		double ordinate;

		GeneratedCoordinates(void);

		GeneratedCoordinates(double abscissa, double ordinate);

		bool operator==(const GeneratedCoordinates & other) const;

		bool operator!=(const GeneratedCoordinates & other) const;
	};

	std::ostream & operator<<(std::ostream & to, const GeneratedCoordinates & from);
}

#include <TRCharts/Impl/CoordinatesImpl.hpp>

#endif


text:
@extends('master')

@unless (empty($title))
    @section('title')
        <title>{{ $title }} – Dev Wiki</title>
    @stop
@endunless

@section('content')

        @include('wiki.breadcrumbs')

        @if (count($index))
            @include('wiki.category-list')
        @endif

            {!! $post !!}

@stop


text:
package org.locationtech.geogig.repository;

import java.util.concurrent.ExecutorService;

import org.locationtech.geogig.api.Platform;

public class FileNodeIndexTest extends AbstractNodeIndexTest {

    @Override
    protected NodeIndex createIndex(Platform platform, ExecutorService executorService) {
        return new FileNodeIndex(platform, executorService);
    }

}


text:
package design.patterns.singleton.test;

import design.patterns.singleton.EnumUniqueService;
import design.patterns.singleton.UniqueService;

public class Run {

	public static void main(String[] args) {
		System.out.println("[-] Using vanila singleton");
		singletonFirstUSe();
		singletonSecondUse();
		System.out.println("[-] Using enum singleton");
		enumSingletonFirstUSe();
		enumSingletonSecondUse();
	}

	private static void singletonFirstUSe() {
		System.out.println("[-] First function");
		UniqueService service = UniqueService.getInstance();
		service.printValue();
		service.increaseValue();
	}

	private static void singletonSecondUse() {
		System.out.println("[-] Second function");
		UniqueService service = UniqueService.getInstance();
		// Prints the updated value
		service.printValue();
	}

	private static void enumSingletonFirstUSe() {
		System.out.println("[-] First function");
		EnumUniqueService service = EnumUniqueService.INSTANCE;
		service.printValue();
		service.increaseValue();
	}

	private static void enumSingletonSecondUse() {
		System.out.println("[-] Second function");
		EnumUniqueService service = EnumUniqueService.INSTANCE;
		// Prints the updated value
		service.printValue();
	}

}


text:
namespace Diamond.Block
{
    public class BlockHugeBrownMushroom : Block
    {
    }
}


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.language.settings;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import org.chromium.chrome.browser.language.AppLocaleUtils;
import org.chromium.components.browser_ui.settings.ChromeBasePreference;

/**
 * Chrome Preference that enables selecting a single LanguageItem.
 */
public class LanguageItemPickerPreference extends ChromeBasePreference {
    private LanguageItem mLanguageItem;
    private boolean mUseLanguageItemForTitle;

    public LanguageItemPickerPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Get the LanguageItem value for this preference.
     * @return LanguageItem saved to this preference.
     */
    public LanguageItem getLanguageItem() {
        return mLanguageItem;
    }

    /**
     * Set the LanguageItem value.
     * @param LanguageItem The LanguageItem to use for this preference
     */
    public void setLanguageItem(LanguageItem languageItem) {
        mLanguageItem = languageItem;
        updateDisplay();
    }

    /**
     * Set the LanguageItem value based on the string locale code. If null is used the system
     * default language is set as the preference's LanguageItem
     * @param String languageCode The iso639 languageCode for LanguageItem
     */
    public void setLanguageItem(String languageCode) {
        LanguageItem languageItem;
        if (AppLocaleUtils.isFollowSystemLanguage(languageCode)) {
            languageItem = LanguageItem.makeFollowSystemLanguageItem();
        } else {
            languageItem = LanguagesManager.getInstance().getLanguageItem(languageCode);
        }
        setLanguageItem(languageItem);
    }

    /**
     * By default only the summary text is synced to the LanguageItem. Enabling this will make the
     * preference title the display name and summary the native display name.
     * @param boolean use
     */
    public void useLanguageItemForTitle(boolean useForTitle) {
        mUseLanguageItemForTitle = useForTitle;
        updateDisplay();
    }

    /**
     * Update the title and summary to display
     */
    private void updateDisplay() {
        if (mLanguageItem == null) {
            return;
        }
        String displayName = mLanguageItem.getDisplayName();
        if (mUseLanguageItemForTitle) {
            setTitle(displayName);
            String nativeName = mLanguageItem.getNativeDisplayName();
            if (TextUtils.equals(displayName, nativeName)) {
                // Clear summary if native name is the same as display name.
                setSummary("");
            } else {
                setSummary(nativeName);
            }
        } else {
            setSummary(displayName);
        }
    }
}


text:
package gnu.java.lang.management;

import java.lang.management.MemoryUsage;

/**
 * Provides access to information on the memory resources or
 * pools used by the current invocation of the virtual machine.
 *
 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
 * @since 1.5
 */
final class VMMemoryPoolMXBeanImpl
{

  /**
   * Returns memory usage statistics for the specified pool
   * just after a best-effort attempt to free memory.  This
   * is valid only for certain garbage collectors.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return a {@link java.lang.management.MemoryUsage} object
   *         containing the statistics or null
   *         if this pool does not support such statistics.
   */
  static native MemoryUsage getCollectionUsage(String name);

  /**
   * Returns the collection usage threshold for the specified pool.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.CollectionUsageThresholdSupport,
   * is defined).  The value is initially zero.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return the collection usage threshold.
   */
  static native long getCollectionUsageThreshold(String name);

  /**
   * Returns the number of times the collection usage threshold
   * has been met or exceeded by the specified pool.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.CollectionUsageThresholdSupport,
   * is defined).
   *
   * @param name the name of the pool to obtain statistics on.
   * @return the collection usage threshold count.
   */
  static native long getCollectionUsageThresholdCount(String name);

  /**
   * Returns an array of names of memory managers which manage
   * the specified pool.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return a list of memory managers for the pool.
   */
  static native String[] getMemoryManagerNames(String name);

  /**
   * Returns the peak usage level of the specified pool.
   * This is only called if the pool is valid.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return a {@link java.lang.management.MemoryUsage} object
   *         containing the statistics.
   */
  static native MemoryUsage getPeakUsage(String name);

  /**
   * Returns the type of memory used by the specified pool.
   * The value must be either "HEAP" or "NON_HEAP".
   *
   * @param name the name of the pool to obtain statistics on.
   * @return the type of the given pool.
   */
  static native String getType(String name);

  /**
   * Returns the current usage level of the specified pool.
   * This is only called if the pool is valid.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return a {@link java.lang.management.MemoryUsage} object
   *         containing the statistics.
   */
  static native MemoryUsage getUsage(String name);

  /**
   * Returns the usage threshold for the specified pool.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.UsageThresholdSupport,
   * is defined).  The value is initially defined by the
   * virtual machine.
   *
   * @param name the name of the pool to obtain statistics on.
   * @return the usage threshold.
   */
  static native long getUsageThreshold(String name);

  /**
   * Returns the number of times the usage threshold
   * has been met or exceeded by the specified pool.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.UsageThresholdSupport,
   * is defined).
   *
   * @param name the name of the pool to obtain statistics on.
   * @return the usage threshold count.
   */
  static native long getUsageThresholdCount(String name);

  /**
   * Returns true if the specified pool is still valid i.e.
   * it is still in use by the virtual machine.
   *
   * @param name the name of the pool to check the validity of.
   * @return true if the pool is valid.
   */
  static native boolean isValid(String name);

  /**
   * Resets the peak usage level to the current usage level for
   * the specified pool.
   *
   * @param name the name of the pool to reset the peak usage of.
   */
  static native void resetPeakUsage(String name);

  /**
   * Sets the collection usage threshold for the specified
   * pool to the supplied value.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.CollectionUsageThresholdSupport,
   * is defined).
   *
   * @param name the name of the pool to set the threshold of.
   * @param threshold the new threshold level.
   */
  static native void setCollectionUsageThreshold(String name, long threshold);

  /**
   * Sets the usage threshold for the specified pool to the supplied value.
   * This is only called if this functionality is supported
   * by the virtual machine (i.e. the appropriate property,
   * gnu.java.lang.management.UsageThresholdSupport,
   * is defined).
   *
   * @param name the name of the pool to set the threshold of.
   * @param threshold the new threshold level.
   */
  static native void setUsageThreshold(String name, long threshold);

}


text:
Spørgsmål og svar

Har du yderligere spørgsmål er du velkommen til at stille dem her.

Please enable JavaScript to view the comments powered by Disqus.


text:
ndtilecache Functions
*************************

*For questions on these functions, please contact Kunal Lillaney at lillaney@jhu.edu*


text:
package org.peelframework.flink.beans.experiment

import java.io.FileWriter
import java.nio.file.{Files, Paths}

import com.typesafe.config.Config
import org.peelframework.core.beans.data.{DataSet, ExperimentOutput}
import org.peelframework.core.beans.experiment.Experiment
import org.peelframework.core.beans.system.System
import org.peelframework.core.util.{Version, shell}
import org.peelframework.flink.beans.system.Flink
import spray.json._

/** An `Experiment` implementation which handles the execution of a single Flink job. */
class FlinkExperiment(
    command: String,
    systems: Set[System],
    runner : Flink,
    runs   : Int,
    inputs : Set[DataSet],
    outputs: Set[ExperimentOutput],
    name   : String,
    config : Config) extends Experiment(command, systems, runner, runs, inputs, outputs, name, config) {

  def this(
    command: String,
    runner : Flink,
    runs   : Int,
    inputs : Set[DataSet],
    outputs: Set[ExperimentOutput],
    name   : String,
    config : Config) = this(command, Set.empty[System], runner, runs, inputs, outputs, name, config)

  override def run(id: Int, force: Boolean): Experiment.Run[Flink] = {
    new FlinkExperiment.SingleJobRun(id, this, force)
  }

  def copy(name: String = name, config: Config = config) = {
    new FlinkExperiment(command, systems, runner, runs, inputs, outputs, name, config)
  }
}

object FlinkExperiment {

  case class State(
    command         : String,
    runnerID        : String,
    runnerName      : String,
    runnerVersion   : String,
    var runExitCode : Option[Int] = None,
    var runTime     : Long = 0,
    var plnExitCode : Option[Int] = None) extends Experiment.RunState

  object StateProtocol extends DefaultJsonProtocol with NullOptions {
    implicit val stateFormat = jsonFormat7(State)
  }

  /** A private inner class encapsulating the logic of single run. */
  class SingleJobRun(val id: Int, val exp: FlinkExperiment, val force: Boolean) extends Experiment.SingleJobRun[Flink, State] {

    import org.peelframework.flink.beans.experiment.FlinkExperiment.StateProtocol._

    val runnerLogPath = exp.config.getString(s"system.${exp.runner.configKey}.path.log")

    override def isSuccessful = state.runExitCode.getOrElse(-1) == 0 // FIXME: && state.plnExitCode.getOrElse(-1) == 0

    override protected def loadState(): State = {
      if (Files.isRegularFile(Paths.get(s"$home/state.json"))) {
        try {
          scala.io.Source.fromFile(s"$home/state.json").mkString.parseJson.convertTo[State]
        } catch {
          case e: Throwable => State(command, exp.runner.beanName, exp.runner.name, exp.runner.version)
        }
      } else {
        State(command, exp.runner.beanName, exp.runner.name, exp.runner.version)
      }
    }

    override protected def writeState() = {
      val fw = new FileWriter(s"$home/state.json")
      fw.write(state.toJson.prettyPrint)
      fw.close()
    }

    override protected def runJob() = {
      // try to get the experiment run plan
      val (plnExit, _) = {
        // assemble options
        val opts = Seq(
          if (Version(exp.runner.version) <= Version("0.8")) Some("-e") else Option.empty[String]
        )
        // execute command
        Experiment.time(this !(s"info ${opts.flatten.mkString(" ")} ${command.trim}", s"$home/run.pln", s"$home/run.pln"))
      }
      state.plnExitCode = Some(plnExit)
      // try to execute the experiment run plan
      val (runExit, t) = Experiment.time(this !(s"run ${command.trim}", s"$home/run.out", s"$home/run.err"))
      state.runTime = t
      state.runExitCode = Some(runExit)
    }

    override def cancelJob() = {
      val ids = (shell !! s"${exp.config.getString(s"system.${exp.runner.configKey}.path.home")}/bin/flink list -r | tail -n +2 | head -n 1 | cut -d':' -f4 | tr -d ' '").split(Array('\n', ' '))
      for (id <- ids) shell ! s"${exp.config.getString(s"system.${exp.runner.configKey}.path.home")}/bin/flink cancel -i $id"
      state.runTime = exp.config.getLong("experiment.timeout") * 1000
      state.runExitCode = Some(-1)
    }

    private def !(command: String, outFile: String, errFile: String) = {
      shell ! s"${exp.config.getString(s"system.${exp.runner.configKey}.path.home")}/bin/flink ${command.trim} > $outFile 2> $errFile"
    }
  }

}


text:
[linkerd.io](https://linkerd.io)

## Quickstart ##

Before starting on, you'll need to install protoc 3.0+ either via a package manager like homebrew, or by downloading a binary from the protobuf release page: https://github.com/google/protobuf/releases.

To get up and running quickly, run:

```
$ ./sbt linkerd-examples/http:run
...
I 0201 21:17:41.992 THREAD52: serving http on localhost/127.0.0.1:4140
```

Then, you may browse to http://localhost:9990 to see an admin
dashboard. Running `curl http://localhost:9990/admin/shutdown` will
initiate a graceful shutdown of a running router.

### Running ###

The `linkerd` project's packaging configurations may also be used to
run linkerd locally, e.g.:

```
> linkerd/minimal:run path/to/config.yml
```

#### Example configurations ####

Furthermore, the `linkerd/examples` project contains example configurations
that may be quickly started:

```
> linkerd-examples/http:run
```

As additional configuration files are added into `examples/*.yaml`,
these configurations will be discovered by sbt and added as
configurations.


text:
namespace dart {

uintptr_t SignalHandler::GetProgramCounter(const mcontext_t& mcontext) {
  uintptr_t pc = 0;

#if defined(HOST_ARCH_IA32)
  pc = static_cast<uintptr_t>(mcontext->__ss.__eip);
#elif defined(HOST_ARCH_X64)
  pc = static_cast<uintptr_t>(mcontext->__ss.__rip);
#elif defined(HOST_ARCH_ARM)
  pc = static_cast<uintptr_t>(mcontext->__ss.__pc);
#elif defined(HOST_ARCH_ARM64)
  pc = static_cast<uintptr_t>(mcontext->__ss.__pc);
#else
#error Unsuported architecture.
#endif  // HOST_ARCH_...

  return pc;
}

uintptr_t SignalHandler::GetFramePointer(const mcontext_t& mcontext) {
  uintptr_t fp = 0;

#if defined(HOST_ARCH_IA32)
  fp = static_cast<uintptr_t>(mcontext->__ss.__ebp);
#elif defined(HOST_ARCH_X64)
  fp = static_cast<uintptr_t>(mcontext->__ss.__rbp);
#elif defined(HOST_ARCH_ARM)
  fp = static_cast<uintptr_t>(mcontext->__ss.__r[7]);
#elif defined(HOST_ARCH_ARM64)
  fp = static_cast<uintptr_t>(mcontext->__ss.__fp);
#else
#error Unsuported architecture.
#endif  // HOST_ARCH_...

  return fp;
}

uintptr_t SignalHandler::GetCStackPointer(const mcontext_t& mcontext) {
  uintptr_t sp = 0;

#if defined(HOST_ARCH_IA32)
  sp = static_cast<uintptr_t>(mcontext->__ss.__esp);
#elif defined(HOST_ARCH_X64)
  sp = static_cast<uintptr_t>(mcontext->__ss.__rsp);
#elif defined(HOST_ARCH_ARM)
  sp = static_cast<uintptr_t>(mcontext->__ss.__sp);
#elif defined(HOST_ARCH_ARM64)
  sp = static_cast<uintptr_t>(mcontext->__ss.__sp);
#else
  UNIMPLEMENTED();
#endif  // HOST_ARCH_...

  return sp;
}

uintptr_t SignalHandler::GetDartStackPointer(const mcontext_t& mcontext) {
#if defined(TARGET_ARCH_ARM64) && !defined(USING_SIMULATOR)
  return static_cast<uintptr_t>(mcontext->__ss.__x[SPREG]);
#else
  return GetCStackPointer(mcontext);
#endif
}

uintptr_t SignalHandler::GetLinkRegister(const mcontext_t& mcontext) {
  uintptr_t lr = 0;

#if defined(HOST_ARCH_IA32)
  lr = 0;
#elif defined(HOST_ARCH_X64)
  lr = 0;
#elif defined(HOST_ARCH_ARM)
  lr = static_cast<uintptr_t>(mcontext->__ss.__lr);
#elif defined(HOST_ARCH_ARM64)
  lr = static_cast<uintptr_t>(mcontext->__ss.__lr);
#else
#error Unsupported architecture.
#endif  // HOST_ARCH_...

  return lr;
}

void SignalHandler::InstallImpl(SignalAction action) {
  struct sigaction act = {};
  act.sa_handler = NULL;
  act.sa_sigaction = action;
  sigemptyset(&act.sa_mask);
  act.sa_flags = SA_RESTART | SA_SIGINFO;
  int r = sigaction(SIGPROF, &act, NULL);
  ASSERT(r == 0);
}

void SignalHandler::Remove() {
  // Ignore future SIGPROF signals because by default SIGPROF will terminate
  // the process and we may have some signals in flight.
  struct sigaction act = {};
  act.sa_handler = SIG_IGN;
  sigemptyset(&act.sa_mask);
  act.sa_flags = 0;
  int r = sigaction(SIGPROF, &act, NULL);
  ASSERT(r == 0);
}

}  // namespace dart

#endif  // defined(HOST_OS_MACOS)


text:
(function() {
	angular
		.module('app.controllers', [])
		.controller('DefaultController', ['$scope', '$mdSidenav', '$location', '$mdDialog', function($scope, $mdSidenav, $location, $mdDialog) {
			$scope.toggleSidenav = function(menuId) {
				$mdSidenav(menuId).toggle();
			};

			$scope.navigateTo = function (where) {
				$location.path(where);
			};

			$scope.goTo = function (where, ev) {
				if (where === '/logout') {
					var confirm = $mdDialog.confirm()
			          .title('Logout?')
			          .content('Are you sure you want to logout?')
			          .ariaLabel('Logout?')
			          .targetEvent(ev)
			          .ok('Logout')
			          .cancel('Cancel');

				    $mdDialog.show(confirm).then(function() {
				    	window.location.href = window.location.origin + where;
				    }, function() {
				    	// do nothing
				    });
				} else {
					window.location.href = window.location.origin + where;
				}
			};
		}])
		.controller('UsersController', ['$scope', '$location', '$http', function($scope, $location, $http) {
			var users = [];

			$http
				.get('/api/users')
				.then(function(response) {
					users = response.data;
					$scope.users = users;
				}, function(response) {
					console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
				});

			// scope vars
			$scope.searchEnabled = false;
			$scope.adminFilter = 0;

			$scope.expand = function (userId) {
				$location.path('/users/' + userId);
			};

			$scope.toggleSearch = function () {
				$scope.searchEnabled = !$scope.searchEnabled;
				if (!$scope.searchEnabled) {
					$scope.search = '';
				}
			};

			$scope.sortBy = function (by) {
				switch (by) {
					case 'firstName':
						$scope.users.sort(function (a, b) {
							if (a.first_name === null) {
								return 1;
							}
							return a.first_name.localeCompare(b.first_name);
						});
						break;
					case 'lastName':
						$scope.users.sort(function (a, b) {
							if (a.last_name === null) {
								return 1;
							}
							return a.last_name.localeCompare(b.last_name);
						});
						break;
					case 'username':
						$scope.users.sort(function (a, b) {
							return a.username.localeCompare(b.username);
						});
						break;
				}
			};

			$scope.$watch('adminFilter', function (value) {
				switch (value) {
					case '1':
						var filteredUsers = [];
						users.forEach(function (user) {
							if (user.is_admin === '1') {
								filteredUsers.push(user);
							}
						});
						$scope.users = filteredUsers;
						break;
					case '2':
						var filteredUsers = [];
						users.forEach(function (user) {
							if (user.is_admin === '0') {
								filteredUsers.push(user);
							}
						});
						$scope.users = filteredUsers;
						break;
					default:
						$scope.users = users;
				}
			});
		}])
		.controller('UserController', ['$scope', '$location', '$http', '$routeParams', '$mdDialog', '$mdToast', function($scope, $location, $http, $routeParams, $mdDialog, $mdToast) {
			$http
				.get('/api/users/' + $routeParams.userId)
				.then(function(response) {
					$scope.user = response.data;
					$scope.user.is_admin = response.data.is_admin === '1';
				}, function(response) {
					console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
				});

			$scope.onBackPressed = function () {
				$location.path('/users');
			};

			$scope.onUserSave = function (ev) {
				if ($scope.user.email === '' || ! /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i.test($scope.user.email)) {
					$mdDialog.show(
				      $mdDialog.alert()
				        .parent(angular.element(document.body))
				        .clickOutsideToClose(true)
				        .title('Errors')
				        .content('User\'s email must be valid.')
				        .ariaLabel('Article Update Errors')
				        .ok('Got it!')
				        .targetEvent(ev)
				    );
				} else {
					var payload = {
						first_name: $scope.user.first_name,
						last_name: $scope.user.last_name,
						email: $scope.user.email,
						description: $scope.user.description,
						is_admin: $scope.user.is_admin
					}

					$http
						.put('/api/users/' + $routeParams.userId, payload)
						.then(function (response) {
							$mdToast.show(
						      $mdToast.simple()
						        .content('User Updated!')
						        .position("bottom right")
						        .hideDelay(2000)
						    );
						    $location.path('/users');
						}, function (response) {
							console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
						});
				}
			};

			$scope.onUserDelete = function (ev) {
				var confirm = $mdDialog.confirm()
			          .title('Delete user?')
			          .content('This will permanently delete the user and this action cannot be undone.')
			          .ariaLabel('Delete user?')
			          .targetEvent(ev)
			          .ok('Delete')
			          .cancel('Cancel');

			    $mdDialog.show(confirm).then(function() {
			    	$http
						.delete('/api/users/' + $routeParams.userId)
						.then(function (response) {
							$mdToast.show(
						      $mdToast.simple()
						        .content('User Deleted!')
						        .position("bottom right")
						        .hideDelay(2000)
						    );
						    $location.path('/users');
						}, function (response) {
							console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
						});
			    }, function() {
			    	// do nothing
			    });
			};
		}])
		.controller('ArticlesController', ['$scope', '$http', '$location', function($scope, $http, $location) {
			var articles = [];

			$http
				.get('/api/articles?paginate=false&admin=true')
				.then(function(response) {
					articles = response.data;
					filterFunction();
				}, function(response) {
					console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
				});

			$scope.expand = function (articleId) {
				$location.path('/articles/' + articleId);
			};

			$scope.onCreateArticle = function () {
				$location.path('/articles/add');
			};

			$scope.dateFilter = 0;
			$scope.statusFilter = 2;

			$scope.searchEnabled = false;
			$scope.toggleSearch = function() {
				$scope.searchEnabled = !$scope.searchEnabled;
				if (!$scope.searchEnabled) {
					$scope.search = '';
				}
			};

			var filterFunction = function () {
				var dateFilter = $scope.dateFilter;
				var statusFilter = $scope.statusFilter;

				if (dateFilter == 0 && statusFilter == 2) {
					$scope.articles = articles;
				} else if (dateFilter == 0) {
					var filteredArticles = [];
					articles.forEach(function (article) {
						if (article.status == statusFilter) {
							filteredArticles.push(article);
						}
					});
					$scope.articles = filteredArticles;
				} else if (statusFilter == 2) {
					switch (dateFilter) {
						case '1': // today
							var startOfToday = moment().startOf('day').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfToday) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							return;
						case '2': // this week
							var startOfWeek = moment().startOf('week').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfWeek) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
						case '3': // this month
							var startOfMonth = moment().startOf('month').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfMonth) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
						case '4': // this year
							var startOfYear = moment().startOf('year').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfYear) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
					}
				} else {
					switch (dateFilter) {
						case '1': // today
							var startOfToday = moment().startOf('day').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfToday && article.status == statusFilter) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
						case '2': // this week
							var startOfWeek = moment().startOf('week').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfWeek && article.status == statusFilter) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
						case '3': // this month
							var startOfMonth = moment().startOf('month').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfMonth && article.status == statusFilter) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
						case '4': // this year
							var startOfYear = moment().startOf('year').toDate().getTime();

							var filteredArticles = [];
							articles.forEach(function (article) {
								if (moment(article.pub_date) >= startOfYear && article.status == statusFilter) {
									filteredArticles.push(article);
								}
							});
							$scope.articles = filteredArticles;
							break;
					}
				}
			};

			$scope.$watch('dateFilter', filterFunction);
			$scope.$watch('statusFilter', filterFunction);
		}])
		.controller('ArticleController', ['$scope', '$location', '$http', '$routeParams', '$mdDialog', '$mdToast', function($scope, $location, $http, $routeParams, $mdDialog, $mdToast) {
			$http
				.get('/api/articles/' + $routeParams.articleId + '?admin=true')
				.then(function(response) {
					$scope.article = response.data;
				}, function(response) {
					console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
				});

			$scope.onBackPressed = function () {
				$location.path('/articles');
			};

			$scope.onArticleSave = function (ev) {
				if ($scope.article.title === '' || $scope.article.content === '') {
					$mdDialog.show(
				      $mdDialog.alert()
				        .parent(angular.element(document.body))
				        .clickOutsideToClose(true)
				        .title('Errors')
				        .content('Article\'s title and content must not be empty. Please fix this before clicking update.')
				        .ariaLabel('Article Update Errors')
				        .ok('Got it!')
				        .targetEvent(ev)
				    );
				} else {
					var payload = {
						title: $scope.article.title,
						subtitle: $scope.article.subtitle,
						content: $scope.article.content,
						status: $scope.article.status
					}

					$http
						.put('/api/articles/' + $routeParams.articleId, payload)
						.then(function (response) {
							$mdToast.show(
						      $mdToast.simple()
						        .content('Article Updated!')
						        .position("bottom right")
						        .hideDelay(2000)
						    );
						    $location.path('/articles');
						}, function (response) {
							console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
						});
				}
			};

			$scope.onArticleDelete = function (ev) {
				var confirm = $mdDialog.confirm()
			          .title('Delete article?')
			          .content('This will permanently delete the article and this cannot be undone.')
			          .ariaLabel('Delete Article?')
			          .targetEvent(ev)
			          .ok('Delete')
			          .cancel('Cancel');

			    $mdDialog.show(confirm).then(function() {
			    	$http
						.delete('/api/articles/' + $routeParams.articleId)
						.then(function (response) {
							$mdToast.show(
						      $mdToast.simple()
						        .content('Article Deleted!')
						        .position("bottom right")
						        .hideDelay(2000)
						    );
						    $location.path('/articles');
						}, function (response) {
							console.error(response.config.method + ' ' + response.config.url + ' : ' + response.status + ' ' + response.statusText);
						});
			    }, function() {
			    	// do nothing
			    });
			};

			$scope.previewArticle = function () {
				window.location.href = '/articles/' + $routeParams.articleId;
			};

			$scope.tinymceOptions = {
				theme: 'modern',
				skin: 'light'
			};

			$scope.onViewComments = function () {
				$location.path('/articles/' + $routeParams.articleId + '/comments');
			};
		}])
		.controller('ArticleCommentsController', ['$scope', '$location', '$http', '$routeParams', '$mdToast', '$mdDialog', function ($scope, $location, $http, $routeParams, $mdToast, $mdDialog) {
			$http
				.get('/api/articles/' + $routeParams.articleId + '/comments')
				.then(function(response) {
					$scope.comments = response.data;
				}, function(response) {

				});
		}])
		.controller('ArticleAddController', ['$scope', '$location', '$http', '$mdToast', '$mdDialog', function ($scope, $location, $http, $mdToast, $mdDialog) {
			$scope.onBackPressed = function () {
				$location.path('/articles');
			};

			$scope.onArticleSave = function (ev) {
				if ($scope.article.title === '' || $scope.article.content == '') {
					$mdDialog.show(
				      $mdDialog.alert()
				        .parent(angular.element(document.body))
				        .clickOutsideToClose(true)
				        .title('Errors')
				        .content('Article\'s title and content must not be empty. Please fix this before clicking update.')
				        .ariaLabel('Article Update Errors')
				        .ok('Got it!')
				        .targetEvent(ev)
				    );
				} else {
					var payload = {
						title: $scope.article.title,
						subtitle: $scope.article.subtitle,
						content: $scope.article.content,
						status: $scope.article.status
					}

					$http
						.post('/api/articles', payload)
						.then(function (response) {
							$mdToast.show(
						      $mdToast.simple()
						        .content('Article Added!')
						        .position("bottom right")
						        .hideDelay(2000)
						    );
						    $location.path('/articles');
						}, function (response) {
							$mdDialog.show(
						      $mdDialog.alert()
						        .parent(angular.element(document.body))
						        .clickOutsideToClose(true)
						        .title('Sorry!')
						        .content(response.status + ' ' + response.statusText)
						        .ariaLabel('Article Update Errors')
						        .ok('Got it!')
						        .targetEvent(ev)
						    );
						});
				}
			};

			$scope.tinymceOptions = {
				theme: 'modern',
				skin: 'light'
			};
		}]);
})();


text:
package org.drools.core.meta.org.test;

import org.drools.core.factmodel.traits.AbstractTraitFactory;
import org.drools.core.metadata.Lit;
import org.drools.core.metadata.ManyValuedMetaProperty;
import org.drools.core.metadata.MetaClass;
import org.drools.core.metadata.MetaProperty;
import org.drools.core.metadata.OneValuedMetaProperty;
import org.drools.core.metadata.ToManyPropertyLiteral;
import org.drools.core.metadata.ToOnePropertyLiteral;
import org.drools.core.metadata.With;
import org.drools.core.util.ClassUtils;

import java.io.Serializable;
import java.net.URI;
import java.util.Collections;
import java.util.List;

public class SubKlass_<T extends SubKlass> extends Klass_<T> implements Serializable {

    public SubKlass_( T x ) {
        super( x );
        metaClassInfo = SubKlass_Meta.getInstance();
    }

    public static final OneValuedMetaProperty<SubKlass,Integer> subProp = SubKlass_Meta.subProp;

    public static final ManyValuedMetaProperty<SubKlass,AnotherKlass,List<AnotherKlass>> links = SubKlass_Meta.links;

    public static <X extends SubKlass> SubKlass_NewInstance<X> newSubKlass( URI id, With... args ) {
        return SubKlass_Meta.getInstance().newInstance( id, args );
    }
    public static <X extends SubKlass> SubKlass_NewInstance<X> newSubKlass( With... args ) {
        return SubKlass_Meta.getInstance().newInstance( args );
    }

    public static <X, K extends SubKlass> SubKlass_Don<X,K> donSubKlass( X core, With... args ) {
        return new SubKlass_Don<X,K>( core, args );
    }

    public static SubKlass_Modify<? extends SubKlass> modify( SubKlass x, With... args ) {
        return new SubKlass_Modify<SubKlass>( x, args );
    }

    public SubKlass_Modify<T> modify( With... args ) {
        return new SubKlass_Modify<T>( getTarget(), args );
    }

    public static class SubKlass_NewInstance<T extends SubKlass> extends Klass_NewInstance<T> {

        public SubKlass_NewInstance( URI id, With... args ) {
            super( id, args );
        }
        public SubKlass_NewInstance( With... args ) {
            super( args );
        }

        protected T construct() {
            return (T) new SubKlassImpl();
        }

        public SubKlass_NewInstance<T> subProp( int newSubProp ) {
            getSetter().subProp( newSubProp );
            return this;
        }

        public SubKlass_NewInstance<T> links( List<AnotherKlass> newLinks, Lit mode ) {
            getSetter().links( newLinks, mode );
            return this;
        }

        public SubKlass_NewInstance<T> links( AnotherKlass newLink, Lit mode ) {
            getSetter().links( newLink, mode );
            return this;
        }

        public SubKlass_NewInstance<T> prop( String newProp ) {
            getSetter().prop( newProp );
            return this;
        }

        public SubKlass_NewInstance<T> another( AnotherKlass newAnother ) {
            getSetter().another( newAnother );
            return this;
        }

        protected SubKlass_Modify<T> getSetter() {
            if ( setter == null ) {
                setter = new SubKlass_Modify( null, this.with );
            }
            return (SubKlass_Modify<T>) setter;
        }

        @Override
        public Class<T> getInstanceClass() {
            return SubKlass_Meta.getInstance().getTargetClass();
        }
    }

    public static class SubKlass_Modify<T extends SubKlass> extends  Klass_.Klass_Modify<T> implements Serializable {
        public SubKlass_Modify( T x, With... args ) {
            super( x, args );
        }

        public SubKlass_Modify<T> prop( String newVal ) {
            super.prop( newVal );
            return this;
        }

        public SubKlass_Modify<T> another( AnotherKlass newVal ) {
            super.another( newVal );
            return this;
        }

        public SubKlass_Modify<T> subProp( Integer newVal ) {
            addTask( subProp, newVal );
            return this;
        }

        public SubKlass_Modify<T> links( List<AnotherKlass> newLinks, Lit mode ) {
            addTask( links, newLinks, mode );
            return this;
        }

        public SubKlass_Modify<T> links( AnotherKlass newLink, Lit mode ) {
            addTask( links, Collections.singletonList( newLink ), mode );
            return this;
        }

        @Override
        protected MetaClass<T> getMetaClassInfo() {
            return SubKlass_Meta.getInstance();
        }

        public Class getModificationClass() {
            return SubKlass.class;
        }
    }

    public static class SubKlass_Meta<T extends SubKlass> extends Klass_Meta<T> implements Serializable {

        private static SubKlass_Meta instance;

        public static SubKlass_Meta getInstance() {
            if ( instance == null ) {
                instance = new SubKlass_Meta( new MetaProperty[] {  prop, another, subProp, links  } );
            }
            return instance;
        }

        public static final OneValuedMetaProperty<SubKlass,Integer> subProp =
                new ToOnePropertyLiteral<SubKlass,Integer>( 2, "subProp", URI.create( "http://www.test.org#SubKlass?subProp" ) ) {
                    public Integer get( SubKlass o ) { return o.getSubProp(); }
                    public void set( SubKlass o, Integer value ) { o.setSubProp( value ); }
                    public boolean isDatatype() { return true; }
                };

        public static final ManyValuedMetaProperty<SubKlass,AnotherKlass,List<AnotherKlass>> links =
                new ToManyPropertyLiteral<SubKlass,AnotherKlass>( 3, "links", URI.create( "http://www.test.org#SubKlass?links" ) ) {
                    public List<AnotherKlass> get( SubKlass o ) { return o.getLinks(); }
                    public void set( SubKlass o, List<AnotherKlass> value ) { o.setLinks( value ); }
                    public boolean isDatatype() { return false; }
                };

        protected SubKlass_Meta( MetaProperty<T,?,?>[] propertyLiterals ) {
            super( propertyLiterals );
        }

        @Override
        protected void cachePropertyNames() {
            propertyNames = ClassUtils.getAccessibleProperties( SubKlass.class );
        }

        @Override
        public URI getUri() {
            if ( key == null ) {
                key = URI.create( "http://www.test.org#SubKlass"  );
            }
            return key;
        }

        @Override
        public Object getId() {
            return getUri();
        }

        public SubKlass_NewInstance<T> newInstance( URI id, With... args ) {
            return new SubKlass_NewInstance<T>( id, args );
        }
        public SubKlass_NewInstance<T> newInstance( With... args ) {
            return new SubKlass_NewInstance<T>( args );
        }

        @Override
        public Class<T> getTargetClass() {
            return (Class<T>) SubKlass.class;
        }
    }

    public static class SubKlass_Don<K, T extends SubKlass> extends Klass_Don<K,T> implements Serializable {
        public SubKlass_Don( K target, With... args ) {
            super( target, args );
        }

        @Override
        protected MetaClass<T> getMetaClassInfo() {
            return SubKlass_Meta.getInstance();
        }

        @Override
        public Class<T> getTrait() {
            return SubKlass_Meta.getInstance().getTargetClass();
        }

        @Override
        public SubKlass_Don<K,T> setTraitFactory( AbstractTraitFactory factory ) {
            super.setTraitFactory( factory );
            return this;
        }

        public SubKlass_Don<K,T> prop( String newVal ) {
            super.prop( newVal );
            return this;
        }

        public SubKlass_Don<K,T> another( AnotherKlass newVal ) {
            super.another( newVal );
            return this;
        }

        protected SubKlass_Modify<T> getSetter() {
            if ( setter == null ) {
                setter = new SubKlass_Modify( null, this.with );
            }
            return (SubKlass_Modify<T>) setter;
        }

        public SubKlass_Don<K,T> subProp( Integer newVal ) {
            getSetter().subProp( newVal );
            return this;
        }

        public SubKlass_Don<K,T> links( List<AnotherKlass> newLinks, Lit mode ) {
            getSetter().links( newLinks, mode );
            return this;
        }

        public SubKlass_Don<K,T> links( AnotherKlass newLink, Lit mode ) {
            getSetter().links( newLink, mode );
            return this;
        }
    }

}


text:
@import Foundation;
@import UIKit;
@import WebKit;
@import SystemConfiguration;
@import CommonCrypto;

#import <sys/utsname.h>
#import <sqlite3.h>

FOUNDATION_EXPORT double QuicklyVersionNumber;
FOUNDATION_EXPORT const unsigned char QuicklyVersionString[];


text:
package com.morgan.shared.account;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.morgan.shared.nav.AbstractTokenBasedApplicationPlaceRepresentation;
import com.morgan.shared.nav.ApplicationPlace;

/**
 * {@link ApplicationPlace} for creating new accounts.
 *
 * @author mark@mark-morgan.net (Mark Morgan)
 */
public class AccountCreationPlaceRepresentation
    extends AbstractTokenBasedApplicationPlaceRepresentation {

  private static final String TOKEN = "newacct";

  @Inject public AccountCreationPlaceRepresentation() {
    super(TOKEN);
  }

  @Override public AccountCreationApplicationPlace parseFromPartsAfterToken(
      ImmutableList<String> remainingParts,
      ImmutableMap<String, String> parameterMap) {
    return remainingParts.isEmpty() ? new AccountCreationApplicationPlace() : null;
  }

  @Override protected Iterable<String> getPathPartsAfterTokenFor(ApplicationPlace place) {
    Preconditions.checkArgument(place instanceof AccountCreationApplicationPlace);

    return ImmutableList.of();
  }
}


text:
.class public final Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;
.super Lcom/android/server/SystemService;
.source "TimaKeystoreService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/enterprise/keystore/TimaKeystoreService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Lifecycle"
.end annotation

# instance fields
.field private mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

# direct methods
.method public constructor <init>(Landroid/content/Context;)V
    .locals 2

    invoke-direct {p0, p1}, Lcom/android/server/SystemService;-><init>(Landroid/content/Context;)V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    const-string/jumbo v0, "TimaKeystoreService"

    const-string/jumbo v1, "TimeKeystoreService DKS LifeCycle creator"

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    new-instance v0, Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    invoke-direct {v0, p1}, Lcom/android/server/enterprise/keystore/TimaKeystoreService;-><init>(Landroid/content/Context;)V

    iput-object v0, p0, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    return-void
.end method

# virtual methods
.method public onBootPhase(I)V
    .locals 1

    invoke-static {}, Lcom/android/server/enterprise/keystore/TimaKeystoreService;->-wrap4()Z

    move-result v0

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    invoke-static {v0, p1}, Lcom/android/server/enterprise/keystore/TimaKeystoreService;->-wrap8(Lcom/android/server/enterprise/keystore/TimaKeystoreService;I)V

    :cond_0
    return-void
.end method

.method public onStart()V
    .locals 3

    const-string/jumbo v0, "TimaKeystoreService"

    const-string/jumbo v1, "TimeKeystoreService DKS LifeCycle onStart"

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    const-string/jumbo v0, "knox_timakeystore_policy"

    iget-object v1, p0, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    invoke-virtual {p0, v0, v1}, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->publishBinderService(Ljava/lang/String;Landroid/os/IBinder;)V

    const-string/jumbo v0, "knox_timakeystore_policy"

    iget-object v1, p0, Lcom/android/server/enterprise/keystore/TimaKeystoreService$Lifecycle;->mService:Lcom/android/server/enterprise/keystore/TimaKeystoreService;

    const/4 v2, 0x0

    invoke-static {v0, v1, v2}, Lcom/android/server/enterprise/EnterpriseDeviceManagerService;->addPolicyService(Ljava/lang/String;Ljava/lang/Object;Z)V

    return-void
.end method


text:
from datetime import datetime
from datetime import timedelta

date = datetime.utcnow()
print "PC's Local Time is", datetime.now()
print "CN Beijing Time is", date+timedelta(hours=8)
print "US Pacific Time is", date+timedelta(hours=-8)


text:
require 'optparse'

module RedisMonitor
  class CommandLineParser
    DEFAULTS = {
      http_server: 'webrick',
      http_port: 6369,
      redis_host: 'localhost',
      redis_port: 6379,
    }

    def self.parse(argv)
      arguments = DEFAULTS.dup
      arguments[:database] ||= {}

      parser = OptionParser.new do |op|
        op.on('--http-port port',  'specify http port (default is 6369)') do |val|
          arguments[:http_port] = val.to_i
        end
        op.on('--host redis-host',  'specify redis host (default is localhost)') do |val|
          arguments[:redis_host] = val
        end
        op.on('--port redis-port',  'specify redis port (default is 6379)') do |val|
          arguments[:redis_port] = val.to_i
        end
        op.on('--editable',  'the content will be editable (default is editable)') do |val|
          arguments[:permissions] ||= {}
          arguments[:permissions][:remove_content] = true
        end
        op.on('--not-editable',  'the content will be not editable (default is editable)') do |val|
          arguments[:permissions] ||= {}
          arguments[:permissions][:remove_content] = false
        end
        op.on('--credentials credentials',  'access only with credentials (format user:password)') do |val|
          user, password = val.to_s.split(':')
          arguments[:credentials] = {user: user, password: password}
        end
        op.on('--database-adapter database-adapter', 'database adapter (mysql2, sqlite3...)') do |val|
          arguments[:database][:adapter] = val
          arguments[:database_config] = true
        end
        op.on('--database-host database-host', 'database host') do |val|
          arguments[:database][:host] = val
          arguments[:database_config] = true
        end
        op.on('--database-port database-port', 'database port') do |val|
          arguments[:database][:port] = val
          arguments[:database_config] = true
        end
        op.on('--database-name database-name', 'database name') do |val|
          arguments[:database][:database] = val
          arguments[:database_config] = true
        end
      end
      parser.parse!(argv)

      arguments
    end
  end
end


text:
namespace Oxide.Plugins
{
    public abstract class BeastsOfPreyPlugin : CSharpPlugin
    {

    }
}


text:
package ca.andrewalbert.nanogenmo2015;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;
import static java.util.stream.Collectors.joining;

/**
 *
 * @author andrew
 */
public class FetchPlainTextGutenbergBookFromLocalResourcesFolder implements BookFetcher {

    @Override
    public String fetch(String bookFileName) throws IOException {

        List<String> lines = Files.readAllLines(Paths.get("src/main/resources/" + bookFileName), Charset.forName("UTF-8"));
        List<String> linesNoHeaderNoFooter = new LinkedList<>();
        boolean isHeader = true;
        for (String line : lines) {
            if (isHeader) {
                if (line.matches(".*\\*\\*\\* START OF THIS PROJECT GUTENBERG EBOOK .*")) {
                    isHeader = false;
                }
            } else {
                if (line.matches(".*\\*\\*\\* END OF THIS PROJECT GUTENBERG EBOOK.*")) {
                    break;
                }
                linesNoHeaderNoFooter.add(line);
            }
        }

        return linesNoHeaderNoFooter.stream()
                .collect(joining("\n"));
    }
}


text:
layout: post
date: 2009-08-24
time: "09:00:00"
authors: ["Greg Wilson"]
title: Bad News and Good News
tags: ["Noticed"]
---

The bad news is, retractions of scientific papers have risen tenfold since 1990. The good news is, the rate has gone from 0.0007% to 0.007%. Going back to bad news, though, some estimates of how many papers ought to be retracted are around 1%, so we still have a long way to go.


text:
GPy.examples package
====================

Submodules
----------

GPy.examples.classification module
----------------------------------

.. automodule:: GPy.examples.classification
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.coreg_example module
---------------------------------

.. automodule:: GPy.examples.coreg_example
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.dimensionality_reduction module
--------------------------------------------

.. automodule:: GPy.examples.dimensionality_reduction
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.non_gaussian module
--------------------------------

.. automodule:: GPy.examples.non_gaussian
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.regression module
------------------------------

.. automodule:: GPy.examples.regression
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.stochastic module
------------------------------

.. automodule:: GPy.examples.stochastic
    :members:
    :undoc-members:
    :show-inheritance:

GPy.examples.tutorials module
-----------------------------

.. automodule:: GPy.examples.tutorials
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: GPy.examples
    :members:
    :undoc-members:
    :show-inheritance:


text:
import {
  AUTHENTICATE,
  AUTHENTICATE_FAILED,
  AUTHENTICATE_SUCCEEDED,
  FETCH,
  INITIALIZE,
  INVALIDATE_SESSION,
  INVALIDATE_SESSION_FAILED,
  UPDATE_SESSION,
  CLEAR_ERROR,
  RESTORE,
  RESTORE_FAILED,
  SYNC_TAB
} from './actionTypes'

export const authenticate = (authenticator, payload) => ({
  type: AUTHENTICATE,
  meta: { authenticator },
  payload
})

export const authenticateSucceeded = (authenticator, payload) => ({
  type: AUTHENTICATE_SUCCEEDED,
  meta: { authenticator },
  payload
})

export const authenticateFailed = payload => ({
  type: AUTHENTICATE_FAILED,
  payload
})

export const fetch = (url, options) => ({
  type: FETCH,
  payload: { url, options }
})

export const clearError = () => ({
  type: CLEAR_ERROR
})

export const invalidateSession = () => ({
  type: INVALIDATE_SESSION
})

export const invalidateSessionFailed = () => ({
  type: INVALIDATE_SESSION_FAILED
})

export const updateSession = payload => ({
  type: UPDATE_SESSION,
  payload
})

export const restore = payload => ({
  type: RESTORE,
  payload
})

export const restoreFailed = () => ({
  type: RESTORE_FAILED
})

export const initialize = payload => ({
  type: INITIALIZE,
  payload
})

export const syncTab = payload => ({
  type: SYNC_TAB,
  payload
})


text:
<?php

namespace Symfony\Component\Form\ValueTransformer;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

use Symfony\Component\Form\Configurable;

/**
 * Implements functionality shared by most value transformers
 *
 * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
 */
abstract class BaseValueTransformer extends Configurable implements ValueTransformerInterface
{
    /**
     * The locale of this transformer as accepted by the class Locale
     * @var string
     */
    protected $locale;

    /**
     * Constructor.
     *
     * @param array $options     An array of options
     *
     * @throws \InvalidArgumentException when a option is not supported
     * @throws \RuntimeException         when a required option is not given
     */
    public function __construct(array $options = array())
    {
        $this->locale = class_exists('\Locale', false) ? \Locale::getDefault() : 'en';

        parent::__construct($options);
    }

    /**
     * {@inheritDoc}
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }
}


text:
[![Go Report Card](https://goreportcard.com/badge/github.com/Avalanche-io/c4)](https://goreportcard.com/report/github.com/Avalanche-io/c4)
[![Build Status](https://travis-ci.org/Avalanche-io/c4.svg?branch=master)](https://travis-ci.org/Avalanche-io/c4)
[![GoDoc](https://godoc.org/github.com/Avalanche-io/c4?status.svg)](https://godoc.org/github.com/avalanche-io/c4)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)

```go
import "github.com/Avalanche-io/c4"
```

This is a Go package that implements the C4 ID system **SMPTE standard ST 2114:2017**. C4 IDs are universally unique and consistent identifiers that standardize the derivation and formatting of data identification so that all users independently agree on the identification of any block or set of blocks of data.

C4 IDs are 90 character long strings suitable for use in filenames, URLs, database fields, or anywhere else that a string identifier might normally be used. In ram C4 IDs are represented in a 64 byte "digest" format.

#### Features

- A single C4 id can represent multiple files.
- C4 ids are unique, random, and unforgeable.
- C4 ids are identical for the same file in different locations or points in time.
- A network connection is not required to generate C4 ids.
- A C4 id can be used in filenames, URLs, json and xml.
- C4 ids can be selected easily with double click (_a problem for many unique identifiers_).
- Easily discover C4 ids in arbitrary text with a simple regex `c4[1-9A-HJ-NP-Za-km-z]{88}`
- Naming files by their C4 id automatically deduplicates them.

#### Comparison of Encodings

C4 is the shortest self identifying SHA-512 encoding and is the only standardized encoding.
To illustrate, the following is the SHA-512 of "foo" in hex, base64 and c4 encodings:

```yaml
# encoding     length   id
  hex          135:     sha512-f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7
  base64        95:     sha512-9/u6bgY2+JDlb7vzKD5STG+jIErimDgtYkdB0NxmODJuKCxBvl5CVNiCB3LFUYosWowMf37aGVlKfrU5RT4e1w==
  c4            90:     c43inc2qGhSWQUMRvDMW6GAjJnRFY5sxq399wcUcWLTuPai84A2QWTfYu1gAW8f5FmZFGeYpLsSPyrSUh9Ao3J68Cc
```

### Example Usage

```go
package main

import (
  "fmt"
  "strings"

  "github.com/Avalanche-io/c4"
)

func main() {

  // Generate a C4 ID for any contiguous block of data...
  id := c4.Identify(strings.NewReader("alfa"))
  fmt.Println(id)
  // output: c43zYcLni5LF9rR4Lg4B8h3Jp8SBwjcnyyeh4bc6gTPHndKuKdjUWx1kJPYhZxYt3zV6tQXpDs2shPsPYjgG81wZM1

  // Generate a C4 ID for any number of non-contiguous blocks...
  var ids c4.IDs
  var inputs = []string{"alfa", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india"}
  for _, input := range inputs {
    ids = append(ids, c4.Identify(strings.NewReader(input)))
  }
  fmt.Println(ids.ID())
  // output: c435RzTWWsjWD1Fi7dxS3idJ7vFgPVR96oE95RfDDT5ue7hRSPENePDjPDJdnV46g7emDzWK8LzJUjGESMG5qzuXqq
}
```

---

### Releases

Current release: [v0.8.0](https://github.com/Avalanche-io/c4/tree/v0.8.0)

### Links

Videos:
  - [C4 Framework Universal Asset ID](https://youtu.be/ZHQY0WYmGYU)
  - [The Magic of C4](https://youtu.be/vzh0JzKhY4o)

[C4 ID Whitepaper](http://www.cccc.io/c4id-whitepaper-u2.pdf)

### Contributing

Contributions are welcome. The following are some general guidelines for project organization. If you have questions please open an issue.

The `master` branch holds the current release, and older releases can be found by their version number. The `dev` branch represents the development branch from which bug and feature branches should be taken. Pull requests that are accepted will be merged against the `dev` branch and then pushed to versioned releases as appropriate.

Feature and bug branches should follow the github integrated naming convention.  Features should be given the `new` tag, and bugs the `bug` tag.  Here is an example of checking out a feature branch:

```bash
> git checkout dev
Switched to branch 'dev'
Your branch is up-to-date with 'origin/dev'.
> git checkout -b new/#99_some_github_issue
...
```

If a branch for an issue is already listed in this repository, then check it out and work from it.

### License
This software is released under the MIT license.  See [LICENSE](./LICENSE) for more information.


text:
/*
 * This header provides constants specific to AM33XX pinctrl bindings.
 */

#ifndef _DT_BINDINGS_PINCTRL_AM33XX_H
#define _DT_BINDINGS_PINCTRL_AM33XX_H

#include <dt-bindings/pinctrl/omap.h>

/* am33xx specific mux bit defines */
#undef PULL_ENA
#undef INPUT_EN

#define PULL_DISABLE		(1 << 3)
#define INPUT_EN		(1 << 5)
#define SLEWCTRL_SLOW		(1 << 6)
#define SLEWCTRL_FAST		0

/* update macro depending on INPUT_EN and PULL_ENA */
#undef PIN_OUTPUT
#undef PIN_OUTPUT_PULLUP
#undef PIN_OUTPUT_PULLDOWN
#undef PIN_INPUT
#undef PIN_INPUT_PULLUP
#undef PIN_INPUT_PULLDOWN

#define PIN_OUTPUT		(PULL_DISABLE)
#define PIN_OUTPUT_PULLUP	(PULL_UP)
#define PIN_OUTPUT_PULLDOWN	0
#define PIN_INPUT		(INPUT_EN | PULL_DISABLE)
#define PIN_INPUT_PULLUP	(INPUT_EN | PULL_UP)
#define PIN_INPUT_PULLDOWN	(INPUT_EN)

/* undef non-existing modes */
#undef PIN_OFF_NONE
#undef PIN_OFF_OUTPUT_HIGH
#undef PIN_OFF_OUTPUT_LOW
#undef PIN_OFF_INPUT_PULLUP
#undef PIN_OFF_INPUT_PULLDOWN
#undef PIN_OFF_WAKEUPENABLE

#endif


text:
JSONNET_FMT := jsonnetfmt -n 2 --max-blank-lines 2 --string-style s --comment-style s

all: fmt prometheus_alerts.yaml dashboards_out lint

fmt:
	find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
		xargs -n 1 -- $(JSONNET_FMT) -i

prometheus_alerts.yaml: mixin.libsonnet config.libsonnet alerts.libsonnet
	jsonnet -S alerts.jsonnet > $@

dashboards_out: mixin.libsonnet config.libsonnet dashboards.libsonnet
	@mkdir -p dashboards_out
	jsonnet -J vendor -m dashboards_out dashboards.jsonnet

lint: prometheus_alerts.yaml
	find . -name 'vendor' -prune -o -name '*.libsonnet' -print -o -name '*.jsonnet' -print | \
		while read f; do \
			$(JSONNET_FMT) "$$f" | diff -u "$$f" -; \
		done

	promtool check rules prometheus_alerts.yaml

.PHONY: jb_install
jb_install:
	jb install

clean:
	rm -rf dashboards_out prometheus_alerts.yaml


text:
import {findNodesByType} from '../../../';
import {expect} from 'chai';
import * as ts from 'typescript';

describe('#sourceFiles/findNodesByType', () => {

	describe('findNodesByType()', () => {

		it('should return all nodes by type', () => {
			const sourceFile = <ts.SourceFile>ts.createSourceFile(
				'/main.ts',
				'const a = 1; const b = 2;',
				ts.ScriptTarget.Latest
			);

			const nodes = findNodesByType<ts.Identifier>(ts.SyntaxKind.Identifier, sourceFile);

			expect(nodes.length).to.be.equal(2);
			expect(nodes[0].text).to.be.equal('a');
			expect(nodes[1].text).to.be.equal('b');
		});

	});

});


text:
<?php

namespace App\Test\TestCase\Avatar;

use App\Avatar\Service;
use Cake\Core\Configure;
use PHPUnit\Framework\TestCase;
use Webmozart\Assert\Assert;

class ServiceTest extends TestCase
{
    /**
     * @var \App\Avatar\Service $Service
     */
    public $Service;

    public function setUp()
    {
        $this->Service = new Service();
    }

    public function tearDown()
    {
        unset($this->Service);
    }

    public function testDefaultAvatarSource(): void
    {
        $avatar = $this->Service->getAvatarSource();
        $default = Configure::read('Avatar.order.0');

        $this->assertInstanceOf($default, $avatar);
    }

    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvokeAvatarSourceWrongClass(): void
    {
        $this->Service->invokeAvatarSource('\Foo\Bar\Baz');
    }

    public function testGetImageName(): void
    {
        $result = $this->Service->getImageName(['id' => 'foobar']);
        $extension = Configure::read('Avatar.extension');

        $this->assertEquals($result, 'foobar' . $extension);
    }

    public function testGetImage(): void
    {
        $options = (array)Configure::readOrFail('Avatar.order');

        $options = array_merge($options, [
            'id' => '123',
            'email' => 'foo@bar.com',
            'name' => 'Foobar',
        ]);

        $this->assertSame('/uploads/avatars/123.png', $this->Service->getImage($options));

        unlink(WWW_ROOT . Configure::readOrFail('Avatar.directory') . '123.png');
    }

    public function testIsImage(): void
    {
        $data = ['type' => 'image/png'];
        $this->assertTrue($this->Service->isImage($data));

        $data = ['type' => 'document/pdf'];
        $this->assertFalse($this->Service->isImage($data));
    }

    public function testIsAllowedSize(): void
    {
        $data = ['size' => 524287];
        $this->assertTrue($this->Service->isAllowedSize($data));

        $data = ['size' => 524288];
        $this->assertFalse($this->Service->isAllowedSize($data));
    }

    public function testGetImageResource(): void
    {
        $data = ['name' => 'cake-logo.png', 'tmp_name' => WWW_ROOT . 'img' . DS . 'cake-logo.png'];
        $this->assertInternalType('resource', $this->Service->getImageResource($data));

        $data = ['name' => 'cakephp.jpg', 'tmp_name' => WWW_ROOT . 'img' . DS . 'branding' . DS . 'cakephp' . DS . 'cakephp.jpg'];
        $this->assertInternalType('resource', $this->Service->getImageResource($data));

        $path = WWW_ROOT . 'img' . DS . 'cake-logo.png';
        $this->assertInternalType('resource', $this->Service->getImageResource($path, true));

        $data = ['name' => 'doc.pdf'];
        $result = $this->Service->getImageResource($data);
        Assert::boolean($result);
        $this->assertFalse($result);
    }

    public function testSaveImage(): void
    {
        $filename = 'test_save_avatar_image.png';
        $data = ['name' => 'cake-logo.png', 'tmp_name' => WWW_ROOT . 'img' . DS . 'cake-logo.png'];
        $resource = $this->Service->getImageResource($data);
        Assert::resource($resource);

        $customDir = WWW_ROOT . Configure::readOrFail('Avatar.customDirectory');

        $this->assertTrue($this->Service->saveImage($customDir . $filename, $resource));

        unlink(WWW_ROOT . Configure::readOrFail('Avatar.customDirectory') . $filename);
    }

    public function testRemoveImageResource(): void
    {
        $data = ['name' => 'cake-logo.png', 'tmp_name' => WWW_ROOT . 'img' . DS . 'cake-logo.png'];
        $resource = $this->Service->getImageResource($data);
        Assert::resource($resource);

        $this->assertTrue($this->Service->removeImageResource($resource));
    }
}


text:
package edu.asu.plp.tool.backend.plpisa.assembler2.instructions;

import edu.asu.plp.tool.backend.isa.exceptions.AssemblerException;

@FunctionalInterface
public interface AssemblerDirectiveStep {

		public String perform() throws AssemblerException;

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.surmon.pattern.exporter;

import com.sun.media.jai.codec.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import org.openide.awt.*;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.surmon.pattern.api.ImageStack;
import org.surmon.pattern.api.PatternImage;
import org.surmon.pattern.api.utils.ImageConverter;
import org.surmon.pattern.project.api.Project;
import org.surmon.pattern.project.api.ProjectInfo;

@ActionID(
        category = "File",
        id = "org.surmon.pattern.exporter.ExportAction"
)
@ActionRegistration(
        iconBase = "org/surmon/pattern/exporter/resources/extract_16.png",
        displayName = "#CTL_ExportAction"
)
@ActionReferences({
    @ActionReference(path = "Menu/File", position = 1300),
    @ActionReference(path = "Toolbars/File", position = 200),
    @ActionReference(path = "Shortcuts", name = "D-E")
})
@Messages("CTL_ExportAction=Export ...")
public final class ExportAction implements ActionListener {

    private JFileChooser fc;

    @Override
    public void actionPerformed(ActionEvent e) {

        // get project to export
        Project project = Utilities.actionsGlobalContext().lookup(Project.class);

        if (project == null) {
            return;
        }

        // initiate and show dialog
        fc = new JFileChooser();
        fc.setDialogTitle("Save project");

        ProjectInfo info = project.getLookup().lookup(ProjectInfo.class);
        if (info != null) {
            fc.setSelectedFile(new File(info.getDisplayName()));
        }

        int code = fc.showSaveDialog(null);

        // handle
        if (code == JFileChooser.APPROVE_OPTION) {
            final File file = fc.getSelectedFile();
            //if (file.exists() && file.isFile()) {
                TIFFEncodeParam params = new TIFFEncodeParam();
                OutputStream out = null;
                try {
                    out = new FileOutputStream(file+ ".tif");
                } catch (FileNotFoundException ex) {
                    Exceptions.printStackTrace(ex);
                }
                ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);

                ImageStack data = project.getLookup().lookup(ImageStack.class);
                List<BufferedImage> images = new ArrayList<>();

                for (PatternImage image : data.getImages()) {
                    images.add(ImageConverter.toBufferedImage(image.getPixels()));
                }

                params.setExtraImages(images.iterator());
                try {
                    encoder.encode(images.get(0));
                    out.close();
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }

            //}
        }
    }
}


text:
/*global tarteaucitron */
tarteaucitron.lang = {
    "middleBarHead": "☝ 🍪",
    "adblock": "Ahoj! Táto stránka je transparentná a umožňuje vám vybrať služby tretích strán, ktoré chcete povoliť.",
    "adblock_call": "Prosím, vypnite blokovanie reklám k začatiu prispôsobovania",
    "reload": "Obnovte stránku",

    "alertBigScroll": "Pokračovaním v posúvaní,",
    "alertBigClick": "Ak budete pokračovať v prehliadaní tejto webovej stránky,",
    "alertBig": "povoľujete všetky služby tretích strán",

    "alertBigPrivacy": "Táto stránka používa cookies a dáva vám kontrolu nad tým, čo chcete aktivovať",
    "alertSmall": "Spravovať služby",
    "personalize": "Prispôsobiť",
    "acceptAll": "OK, prijať všetko",
    "close": "Zatvoriť",

    "privacyUrl": "Zásady ochrany osobných údajov",

    "all": "Prednosť pre všetky služby",

    "info": "Ochrana vášho súkromia",
    "disclaimer": "Povolením týchto služieb tretích strán, prijímate ich cookies a používanie sledovacích technológií potrebných pre ich správne fungovanie.",
    "allow": "Povoliť",
    "deny": "Odmietnúť",
    "noCookie": "Táto služba nepoužíva cookies.",
    "useCookie": "Túto službu je možné nainštalovať",
    "useCookieCurrent": "Táto služba je nainštalovaná",
    "useNoCookie": "Táto služba nenainštalovala žiadny súbor cookie.",
    "more": "Čítaj viac",
    "source": "Pozrite si oficiálnu webovú stránku",
    "credit": "Správca súborov cookie od tarteaucitron.js",
    "noServices": "Táto webová stránka nepoužíva žiadny súbor cookie, ktorý vyžaduje váš súhlas.",

    "toggleInfoBox": "Zobraziť/skryť informácie o ukladaní súborov cookie",
    "title": "Panel riadenia súborov cookie",
    "cookieDetail": "Podrobnosti súboru cookie pre",
    "ourSite": "na našich stránkach",
    "newWindow": "(nové okno)",
    "allowAll": "Povoľte všetky súbory cookie",
    "denyAll": "Odmietnuť všetky súbory cookie",

    "icon": "Cookies",

    "fallback": "je zakázané.",

    "ads": {
        "title": "Reklamná sieť",
        "details": "Reklamné siete môžu generovať príjmy predajom reklamného priestoru na webe."
    },
    "analytic": {
        "title": "Meranie publika",
        "details": "Služby merania publika používané na generovanie užitočnej štatistickej účasti na zlepšenie stránky."
    },
    "social": {
        "title": "Sociálne siete",
        "details": "Sociálne siete môžu zlepšiť použiteľnosť stránky a pomôcť ju propagovať prostredníctvom akcií."
    },
    "video": {
        "title": "Videá",
        "details": "Služby zdieľania videa pomáhajú pridať na web bohatý obsah a zvýšiť jeho viditeľnosť."
    },
    "comment": {
        "title": "Komentáre",
        "details": "Manažéri komentárov uľahčujú zadávanie komentárov a bojujú proti spamu."
    },
    "support": {
        "title": "Podpora",
        "details": "Podporné služby vám umožňujú skontaktovať sa s tímom stránok a pomôcť vám ich vylepšiť."
    },
    "api": {
        "title": "APIs",
        "details": "Rozhrania API sa používajú na načítanie skriptov: geolokácia, vyhľadávače, preklady, ..."
    },
    "other": {
        "title": "Ostatné",
        "details": "Služby na zobrazovanie webového obsahu."
    },

    "mandatoryTitle": "Mandatory cookies",
    "mandatoryText": "This site uses cookies necessary for its proper functioning which cannot be deactivated."
};