text:
using System.Net.Sockets;
using System.Net.Test.Common;

using Xunit;
using Xunit.Abstractions;

namespace System.Net.NetworkInformation.Tests
{
    [PlatformSpecific(PlatformID.OSX)]
    public class IPInterfacePropertiesTest_OSX
    {
        private readonly ITestOutputHelper _log;

        public IPInterfacePropertiesTest_OSX()
        {
            _log = TestLogging.GetInstance();
        }

        [Fact]
        public void IPInfoTest_AccessAllProperties_NoErrors()
        {
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                _log.WriteLine("Nic: " + nic.Name);
                _log.WriteLine("- Supports IPv4: " + nic.Supports(NetworkInterfaceComponent.IPv4));
                _log.WriteLine("- Supports IPv6: " + nic.Supports(NetworkInterfaceComponent.IPv6));

                IPInterfaceProperties ipProperties = nic.GetIPProperties();

                Assert.NotNull(ipProperties);

                Assert.Throws<PlatformNotSupportedException>(() => ipProperties.AnycastAddresses);

                Assert.Throws<PlatformNotSupportedException>(() => ipProperties.DhcpServerAddresses);

                Assert.NotNull(ipProperties.DnsAddresses);
                _log.WriteLine("- Dns Addresses: " + ipProperties.DnsAddresses.Count);
                foreach (IPAddress dns in ipProperties.DnsAddresses)
                {
                    _log.WriteLine("-- " + dns.ToString());
                }
                Assert.NotNull(ipProperties.DnsSuffix);
                _log.WriteLine("- Dns Suffix: " + ipProperties.DnsSuffix);

                Assert.NotNull(ipProperties.GatewayAddresses);
                _log.WriteLine("- Gateway Addresses: " + ipProperties.GatewayAddresses.Count);
                foreach (GatewayIPAddressInformation gateway in ipProperties.GatewayAddresses)
                {
                    _log.WriteLine("-- " + gateway.Address.ToString());
                }

                Assert.Throws<PlatformNotSupportedException>(() => ipProperties.IsDnsEnabled);

                Assert.Throws<PlatformNotSupportedException>(() => ipProperties.IsDynamicDnsEnabled);

                Assert.NotNull(ipProperties.MulticastAddresses);
                _log.WriteLine("- Multicast Addresses: " + ipProperties.MulticastAddresses.Count);
                foreach (IPAddressInformation multi in ipProperties.MulticastAddresses)
                {
                    _log.WriteLine("-- " + multi.Address.ToString());
                    Assert.Throws<PlatformNotSupportedException>(() => multi.IsDnsEligible);
                    Assert.Throws<PlatformNotSupportedException>(() => multi.IsTransient);
                }

                Assert.NotNull(ipProperties.UnicastAddresses);
                _log.WriteLine("- Unicast Addresses: " + ipProperties.UnicastAddresses.Count);
                foreach (UnicastIPAddressInformation uni in ipProperties.UnicastAddresses)
                {
                    _log.WriteLine("-- " + uni.Address.ToString());
                    Assert.Throws<PlatformNotSupportedException>(() => uni.AddressPreferredLifetime);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.AddressValidLifetime);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.DhcpLeaseLifetime);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.DuplicateAddressDetectionState);

                    Assert.NotNull(uni.IPv4Mask);
                    _log.WriteLine("--- IPv4 Mask: " + uni.IPv4Mask);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.IsDnsEligible);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.IsTransient);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.PrefixOrigin);
                    Assert.Throws<PlatformNotSupportedException>(() => uni.SuffixOrigin);

                    // Prefix Length
                    Assert.Throws<PlatformNotSupportedException>(() => uni.PrefixLength);
                }

                Assert.Throws<PlatformNotSupportedException>(() => ipProperties.WinsServersAddresses);
            }
        }

        [Fact]
        public void IPInfoTest_AccessAllIPv4Properties_NoErrors()
        {
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                _log.WriteLine("Nic: " + nic.Name);

                IPInterfaceProperties ipProperties = nic.GetIPProperties();

                _log.WriteLine("IPv4 Properties:");

                IPv4InterfaceProperties ipv4Properties = ipProperties.GetIPv4Properties();

                _log.WriteLine("Index: " + ipv4Properties.Index);
                Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingActive);
                Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsAutomaticPrivateAddressingEnabled);
                Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsDhcpEnabled);
                Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.IsForwardingEnabled);
                _log.WriteLine("Mtu: " + ipv4Properties.Mtu);
                Assert.Throws<PlatformNotSupportedException>(() => ipv4Properties.UsesWins);
            }
        }

        [Fact]
        public void IPInfoTest_AccessAllIPv6Properties_NoErrors()
        {
            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                _log.WriteLine("Nic: " + nic.Name);

                IPInterfaceProperties ipProperties = nic.GetIPProperties();

                _log.WriteLine("IPv6 Properties:");

                IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();

                if (ipv6Properties == null)
                {
                    _log.WriteLine("IPv6Properties is null");
                    continue;
                }

                _log.WriteLine("Index: " + ipv6Properties.Index);
                _log.WriteLine("Mtu: " + ipv6Properties.Mtu);
                Assert.Throws<PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(ScopeLevel.Link));
            }
        }

        [Fact]
        [Trait("IPv6", "true")]
        public void IPv6ScopeId_AccessAllValues_Success()
        {
            Assert.True(Capability.IPv6Support());

            foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
            {
                _log.WriteLine("Nic: " + nic.Name);

                if (!nic.Supports(NetworkInterfaceComponent.IPv6))
                {
                    continue;
                }

                IPInterfaceProperties ipProperties = nic.GetIPProperties();

                IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties();

                Array values = Enum.GetValues(typeof(ScopeLevel));
                foreach (ScopeLevel level in values)
                {
                    Assert.Throws<PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(level));
                }
            }
        }
    }
}


text:
SET FOREIGN_KEY_CHECKS = 0;

DELETE FROM `files` WHERE id != 1;
TRUNCATE `config_files`;

DELETE FROM `application` WHERE `application_name` IN ('net.violet.air', 'net.violet.weather', 'net.violet.bilan', 'net.violet.trafic', 'net.violet.bourse', 'net.violet.clock');

SET FOREIGN_KEY_CHECKS = 1;

redpajama_set_name: RedPajamaGithub


text:
import test from 'ava'
import * as fetchMock from 'fetch-mock'
import {
  createMockSku,
  createMockSkuId,
  CONV_ID,
  ACCESS_TOKEN,
  PACKAGE_NAME,
} from './lib/stubs'
import { getSkus, consume } from './../src/digital-goods-service-api'

test.afterEach(t => {
  fetchMock.reset()
})

test.serial('getSkus returns an object of Skus', async t => {
  const expectedSkus = {
    id0: createMockSku({
      skuId: createMockSkuId('SKU_TYPE_IN_APP', 'id0', PACKAGE_NAME),
    }),
    id1: createMockSku({
      skuId: createMockSkuId('SKU_TYPE_SUBSCRIPTION', 'id1', PACKAGE_NAME),
    }),
  }
  fetchMock.post(
    `https://actions.googleapis.com/v3/packages/${PACKAGE_NAME}/skus:batchGet`,
    { skus: Object.values(expectedSkus) })
  const res = await getSkus(CONV_ID, ACCESS_TOKEN, PACKAGE_NAME, {
    SKU_TYPE_IN_APP: ['id0'],
    SKU_TYPE_SUBSCRIPTION: ['id1'],
  })
  t.deepEqual(res, expectedSkus)
})

test.serial('consume executes succesfully', async t => {
  fetchMock.post(
    `https://actions.googleapis.com/v3/conversations/${CONV_ID}/entitlement:consume`,
    {}) // not an actual value of consume response
  const res = await consume(CONV_ID, ACCESS_TOKEN, 'test-token')
  t.deepEqual(res, {})
})


text:
#region License

#endregion

#region Imports

using System;
using System.Collections;
using Spring.Util;

#endregion

namespace Spring.Dao.Support
{
	/// <summary>
	/// Miscellaneous utility methods for DAO implementations.
	/// Useful with any data access technology.
	/// </summary>
	/// <author>Mark Pollack (.NET)</author>
	public class DataAccessUtils
	{

		#region Constructor (s)
		/// <summary>
		/// Initializes a new instance of the <see cref="DataAccessUtils"/> class.
                /// </summary>
		public 	DataAccessUtils()
		{

		}

		#endregion

		#region Methods

	    public static object RequiredUniqueResultSet(IList results)
	    {
	        int size = (results != null ? results.Count : 0);
	        if (size == 0)
	        {
	            throw new EmptyResultDataAccessException(1);
	        }
	        if ( ! CollectionUtils.HasUniqueObject(results))
	        {
	            throw new IncorrectResultSizeDataAccessException(1, size);
	        }
	        IEnumerator enumerator = results.GetEnumerator();
	        enumerator.MoveNext();
	        return enumerator.Current;
	    }

        /// <summary>
        /// Return a translated exception if this is appropriate, or null if the exception could
        /// not be translated.
        /// </summary>
        /// <param name="rawException">The raw exception we may wish to translate.</param>
        /// <param name="pet">The PersistenceExceptionTranslator to use to perform the translation.</param>
        /// <returns>A translated exception if translation is possible, or or null if the exception could
        /// not be translated.</returns>
        public static DataAccessException TranslateIfNecessary(Exception rawException, IPersistenceExceptionTranslator pet)
        {
            AssertUtils.ArgumentNotNull(pet, "PersistenceExceptionTranslator must not be null");
            return pet.TranslateExceptionIfPossible(rawException);
        }

	    #endregion
	}

}


text:
// Copyright 2014 The Oppia Authors. 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Directive for the state graph visualization.
 */

// TODO(brianrodri): Add all other interaction IDs to this list, then remove
// the list altogether.
oppia.constant('SUPPORTED_HTML_RENDERINGS_FOR_INTERACTION_IDS', ['TextInput']);

oppia.directive('unresolvedAnswersOverview', [
  'UrlInterpolationService', function(UrlInterpolationService) {
    return {
      restrict: 'E',
      scope: {},
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/pages/exploration_editor/editor_tab/' +
        'unresolved_answers_overview_directive.html'),
      controller: [
        '$scope', '$rootScope', '$uibModal', 'EditorStateService',
        'ExplorationStatesService', 'StateRulesStatsService',
        'ExplorationRightsService', 'stateInteractionIdService',
        'INTERACTION_SPECS', 'EditabilityService',
        'StateTopAnswersStatsService',
        'SUPPORTED_HTML_RENDERINGS_FOR_INTERACTION_IDS',
        function(
            $scope, $rootScope, $uibModal, EditorStateService,
            ExplorationStatesService, StateRulesStatsService,
            ExplorationRightsService, stateInteractionIdService,
            INTERACTION_SPECS, EditabilityService,
            StateTopAnswersStatsService,
            SUPPORTED_HTML_RENDERINGS_FOR_INTERACTION_IDS) {
          var MAXIMUM_UNRESOLVED_ANSWERS = 5;
          var MINIMUM_UNRESOLVED_ANSWER_FREQUENCY = 2;

          $scope.unresolvedAnswersData = null;
          $scope.latestRefreshDate = new Date();
          $scope.unresolvedAnswersOverviewIsShown = false;

          $scope.SHOW_TRAINABLE_UNRESOLVED_ANSWERS = (
            GLOBALS.SHOW_TRAINABLE_UNRESOLVED_ANSWERS);

          /**
           * @returns {boolean} - answers from this state can be rendered with
           * HTML.
           */
          var isStateInteractionIdHtmlRenderable = function() {
            var state = ExplorationStatesService.getState(
              EditorStateService.getActiveStateName());
            return (!!state &&
              SUPPORTED_HTML_RENDERINGS_FOR_INTERACTION_IDS.indexOf(
                state.interaction.id) !== -1);
          };

          $scope.isUnresolvedAnswersOverviewShown = function() {
            return (
              StateTopAnswersStatsService.hasStateStats(
                EditorStateService.getActiveStateName()) &&
              isStateInteractionIdHtmlRenderable());
          };

          $scope.getCurrentInteractionId = function() {
            return stateInteractionIdService.savedMemento;
          };

          $scope.isCurrentInteractionLinear = function() {
            var interactionId = $scope.getCurrentInteractionId();
            return interactionId && INTERACTION_SPECS[interactionId].is_linear;
          };

          $scope.isCurrentInteractionTrainable = function() {
            var interactionId = $scope.getCurrentInteractionId();
            return (
              interactionId &&
              INTERACTION_SPECS[interactionId].is_trainable);
          };

          $scope.isEditableOutsideTutorialMode = function() {
            return EditabilityService.isEditableOutsideTutorialMode();
          };

          $scope.openTeachOppiaModal = function() {
            $rootScope.$broadcast('externalSave');

            $uibModal.open({
              templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
                '/pages/exploration_editor/editor_tab/' +
                'teach_oppia_modal_directive.html'),
              backdrop: true,
              controller: [
                '$scope', '$injector', '$uibModalInstance', '$http', '$filter',
                'ExplorationHtmlFormatterService', 'TrainingModalService',
                'stateInteractionIdService', 'stateCustomizationArgsService',
                'ContextService', 'EditorStateService',
                'ExplorationStatesService', 'TrainingDataService',
                'AnswerClassificationService', 'EXPLICIT_CLASSIFICATION',
                'UrlInterpolationService', 'TRAINING_DATA_CLASSIFICATION',
                'AngularNameService', 'DEFAULT_OUTCOME_CLASSIFICATION',
                'AlertsService',
                function(
                    $scope, $injector, $uibModalInstance, $http, $filter,
                    ExplorationHtmlFormatterService, TrainingModalService,
                    stateInteractionIdService, stateCustomizationArgsService,
                    ContextService, EditorStateService,
                    ExplorationStatesService, TrainingDataService,
                    AnswerClassificationService, EXPLICIT_CLASSIFICATION,
                    UrlInterpolationService, TRAINING_DATA_CLASSIFICATION,
                    AngularNameService, DEFAULT_OUTCOME_CLASSIFICATION,
                    AlertsService) {
                  var _explorationId = (
                    ContextService.getExplorationId());
                  var _stateName = EditorStateService.getActiveStateName();
                  var _state = ExplorationStatesService.getState(_stateName);
                  var interactionId = stateInteractionIdService.savedMemento;

                  var rulesServiceName = (
                    AngularNameService.getNameOfInteractionRulesService(
                      interactionId));

                  // Inject RulesService dynamically.
                  var rulesService = $injector.get(rulesServiceName);

                  // Timeout for the toast that is shown when a response has
                  // been confirmed or fixed.
                  var TOAST_TIMEOUT = 2000;

                  var fetchAndShowUnresolvedAnswers = function(
                      expId, stateName) {
                    var unresolvedAnswersUrl = (
                      UrlInterpolationService.interpolateUrl(
                        '/createhandler/get_top_unresolved_answers/' +
                        '<exploration_id>', {
                          exploration_id: expId
                        }));
                    $http.get(unresolvedAnswersUrl, {
                      params: {
                        state_name: stateName
                      }
                    }).success(function(response) {
                      $scope.showUnresolvedAnswers(response.unresolved_answers);
                    }).error(function(response) {
                      $log.error(
                        'Error occurred while fetching unresolved answers ' +
                        'for exploration ' + _explorationId + 'state ' +
                        _stateName + ': ' + response);
                      $scope.showUnresolvedAnswers([]);
                    });
                  };

                  $scope.showUnresolvedAnswers = function(unresolvedAnswers) {
                    $scope.loadingDotsAreShown = false;
                    $scope.unresolvedAnswers = [];

                    unresolvedAnswers.forEach(function(item) {
                      var acs = AnswerClassificationService;
                      var answer = item.answer;
                      var classificationResult = (
                        acs.getMatchingClassificationResult(
                          _explorationId, _stateName, _state, answer,
                          rulesService));
                      var classificationType = (
                        classificationResult.classificationCategorization);
                      if (classificationType !== EXPLICIT_CLASSIFICATION &&
                        classificationType !== TRAINING_DATA_CLASSIFICATION &&
                        !TrainingDataService.isConfirmedUnclassifiedAnswer(
                          answer)) {
                        var answerTemplate = (
                          ExplorationHtmlFormatterService.getAnswerHtml(
                            answer, stateInteractionIdService.savedMemento,
                            stateCustomizationArgsService.savedMemento));
                        var feedbackHtml = (
                          classificationResult.outcome.feedback.getHtml());
                        $scope.unresolvedAnswers.push({
                          answer: answer,
                          answerTemplate: answerTemplate,
                          classificationResult: classificationResult,
                          feedbackHtml: feedbackHtml
                        });
                      }
                    });
                  };

                  $scope.confirmAnswerAssignment = function(answerIndex) {
                    answer = $scope.unresolvedAnswers[answerIndex];
                    $scope.unresolvedAnswers.splice(answerIndex, 1);

                    var classificationType = (
                      answer.classificationResult.classificationCategorization);
                    var truncatedAnswer = $filter(
                      'truncateInputBasedOnInteractionAnswerType')(
                      answer.answer, interactionId, 12);
                    var successToast = (
                      'The answer ' + truncatedAnswer +
                      ' has been successfully trained.');

                    if (classificationType === DEFAULT_OUTCOME_CLASSIFICATION) {
                      TrainingDataService.associateWithDefaultResponse(
                        answer.answer);
                      AlertsService.addSuccessMessage(
                        successToast, TOAST_TIMEOUT);
                      return;
                    }

                    TrainingDataService.associateWithAnswerGroup(
                      answer.classificationResult.answerGroupIndex,
                      answer.answer);
                    AlertsService.addSuccessMessage(
                      successToast, TOAST_TIMEOUT);
                  };

                  $scope.openTrainUnresolvedAnswerModal = function(
                      answerIndex) {
                    var selectedAnswerIndex = answerIndex;
                    var unresolvedAnswer = (
                      $scope.unresolvedAnswers[answerIndex]);
                    var answer = unresolvedAnswer.answer;
                    var answerGroupIndex = (
                      unresolvedAnswer.classificationResult.answerGroupIndex);
                    return TrainingModalService.openTrainUnresolvedAnswerModal(
                      answer, function() {
                        $scope.unresolvedAnswers.splice(selectedAnswerIndex, 1);
                        var truncatedAnswer = $filter(
                          'truncateInputBasedOnInteractionAnswerType')(
                          answer, interactionId, 12);
                        var successToast = (
                          'The response for ' + truncatedAnswer +
                          ' has been fixed.');
                        AlertsService.addSuccessMessage(
                          successToast, TOAST_TIMEOUT);
                      });
                  };

                  $scope.finishTeaching = function(reopen) {
                    $uibModalInstance.dismiss();
                  };

                  $scope.loadingDotsAreShown = true;
                  fetchAndShowUnresolvedAnswers(_explorationId, _stateName);
                }]
            });
          };

          $scope.getUnresolvedStateStats = function() {
            return StateTopAnswersStatsService.getUnresolvedStateStats(
              EditorStateService.getActiveStateName());
          };
        }
      ]
    };
  }]);


text:
struct vc_in_buffer {
	void * data;
	size_t filled;
	uint32_t jiffies;
};

struct vc_in_queue {
	struct vc_in_buffer buffers[2];
	struct vc_in_buffer dummy;
	struct vc_in_buffer * pending;
	struct vc_in_buffer * ready;
};

struct vc_out_buffer {
	struct vb2_buffer vb;
	struct list_head list;
	size_t filled;
};

struct vc_out_queue {
	struct list_head active;
	int frame;
	//TO be completed later
};

struct vc_device_format {
	char * name;
	int    fourcc;
	int    bit_depth;
};

struct vc_device {
	dev_t dev_number;
	struct v4l2_device        v4l2_dev;
    struct video_device       vdev;

    //input buffer
    struct vc_in_queue        in_queue;
    spinlock_t                in_q_slock;
    spinlock_t                in_fh_slock;
    unsigned char             fb_isopen;

    //output buffer
    struct vb2_queue          vb_out_vidq;
    struct vc_out_queue       vc_out_vidq;
    spinlock_t                out_q_slock;
    //Output framerate
    struct v4l2_fract         output_fps;

    //Input framebuffer
    char                      vc_fb_fname[FB_NAME_MAXLENGTH];
    struct proc_dir_entry*    vc_fb_procf;
    struct mutex              vc_mutex;

    //Submitter thread
    struct task_struct *      sub_thr_id;

    //Format descriptor
    size_t                    nr_fmts;
    struct vc_device_format   out_fmts[PIXFMTS_MAX];

    struct v4l2_pix_format    output_format;
    struct v4l2_pix_format    input_format;

    //Conversion switches
    unsigned char             conv_pixfmt_on;
    unsigned char             conv_res_on;
};

struct vc_device * create_vcdevice( size_t idx, struct vcmod_device_spec * dev_spec );
void destroy_vcdevice( struct vc_device * vcdev );

int submitter_thread( void * data );
int check_supported_pixfmt( struct vc_device * dev, unsigned int fourcc );

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements. See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>nifi-asn1-bundle</artifactId>
        <groupId>org.apache.nifi</groupId>
        <version>1.19.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>nifi-asn1-services</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-record-serialization-service-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-record</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-utils</artifactId>
            <version>1.19.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.beanit</groupId>
            <artifactId>asn1bean</artifactId>
            <version>1.13.0</version>
        </dependency>
        <dependency>
            <groupId>com.beanit</groupId>
            <artifactId>asn1bean-compiler</artifactId>
            <version>1.13.0</version>
        </dependency>
        <dependency>
            <groupId>com.beanit</groupId>
            <artifactId>jasn1-compiler</artifactId>
            <version>1.11.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.8.1</version>
        </dependency>

        <!-- For Test -->
        <dependency>
            <groupId>org.apache.nifi</groupId>
            <artifactId>nifi-mock</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.6.0</version>
                <executions>
                    <execution>
                        <id>compile-asn</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>java</goal>
                        </goals>

                        <configuration>
                            <mainClass>com.beanit.asn1bean.compiler.Compiler</mainClass>
                            <arguments>
                                <argument>-f</argument>
                                <argument>${basedir}/src/test/resources/simple_types.asn</argument>
                                <argument>${basedir}/src/test/resources/complex_types.asn</argument>
                                <argument>${basedir}/src/test/resources/example.asn</argument>
                                <argument>${basedir}/src/test/resources/tbcd_string.asn</argument>
                                <argument>-o</argument>
                                <argument>${basedir}/target/generated-test-sources</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>add-test-sources</id>
                        <phase>process-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>${basedir}/target/generated-test-sources</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.rat</groupId>
                <artifactId>apache-rat-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>checkstyle-suppressions.xml</exclude>
                        <exclude>src/test/resources/test.asn</exclude>
                        <exclude>src/test/resources/example.asn</exclude>
                        <exclude>src/test/resources/simple_types.asn</exclude>
                        <exclude>src/test/resources/complex_types.asn</exclude>
                        <exclude>src/test/resources/tbcd_string.asn</exclude>
                        <exclude>src/test/resources/examples/basic-types.dat</exclude>
                        <exclude>src/test/resources/examples/composite.dat</exclude>
                        <exclude>src/test/resources/examples/tbcd-string.dat</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <executions>
                    <execution>
                        <id>check-style</id>
                        <phase>verify</phase>
                        <configuration>
                            <encoding>UTF-8</encoding>
                            <suppressionsLocation>${basedir}/checkstyle-suppressions.xml</suppressionsLocation>
                            <sourceDirectories>
                                <sourceDirectory>${project.build.sourceDirectory}</sourceDirectory>
                                <sourceDirectory>${project.build.testSourceDirectory}</sourceDirectory>
                            </sourceDirectories>
                        </configuration>
                        <goals>
                            <goal>check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('profile', '0005_profile_is_archive'),
    ]

    operations = [
        migrations.AddField(
            model_name='profile',
            name='days_of_unread',
            field=models.IntegerField(default=30, blank=True, null=True),
        ),
    ]


text:
<?php

namespace Blogger\BlogBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class RegistrationFormType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->add('lastName');
    }

    public function configureOptions(OptionsResolver $resolver)
    {

    }

    public function getName()
    {
        return 'blog_bundle_registration_form';
    }
}


text:
from __future__ import print_function
import sys,os
import mxnet as mx
import numpy as np
import time
import math
import data_helpers
from collections import namedtuple

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) # get a logger to accuracies are printed

logs = sys.stderr

CNNModel = namedtuple("CNNModel", ['cnn_exec', 'symbol', 'data', 'label', 'param_blocks'])

def make_text_cnn(sentence_size, num_embed, batch_size, vocab_size,
        num_label=2, filter_list=[3, 4, 5], num_filter=100,
        dropout=0., with_embedding=True):

    input_x = mx.sym.Variable('data') # placeholder for input
    input_y = mx.sym.Variable('softmax_label') # placeholder for output

    # embedding layer
    if not with_embedding:
        embed_layer = mx.sym.Embedding(data=input_x, input_dim=vocab_size, output_dim=num_embed, name='vocab_embed')
        conv_input = mx.sym.Reshape(data=embed_layer, target_shape=(batch_size, 1, sentence_size, num_embed))
    else:
        conv_input = input_x

    # create convolution + (max) pooling layer for each filter operation
    pooled_outputs = []
    for i, filter_size in enumerate(filter_list):
        convi = mx.sym.Convolution(data=conv_input, kernel=(filter_size, num_embed), num_filter=num_filter)
        relui = mx.sym.Activation(data=convi, act_type='relu')
        pooli = mx.sym.Pooling(data=relui, pool_type='max', kernel=(sentence_size - filter_size + 1, 1), stride=(1,1))
        pooled_outputs.append(pooli)

    # combine all pooled outputs
    total_filters = num_filter * len(filter_list)
    concat = mx.sym.Concat(*pooled_outputs, dim=1)
    h_pool = mx.sym.Reshape(data=concat, target_shape=(batch_size, total_filters))

    # dropout layer
    if dropout > 0.0:
        h_drop = mx.sym.Dropout(data=h_pool, p=dropout)
    else:
        h_drop = h_pool

    # fully connected
    cls_weight = mx.sym.Variable('cls_weight')
    cls_bias = mx.sym.Variable('cls_bias')

    fc = mx.sym.FullyConnected(data=h_drop, weight=cls_weight, bias=cls_bias, num_hidden=num_label)

    # softmax output
    sm = mx.sym.SoftmaxOutput(data=fc, label=input_y, name='softmax')

    return sm

def setup_cnn_model(ctx, batch_size, sentence_size, num_embed, vocab_size,
        dropout=0.5, initializer=mx.initializer.Uniform(0.1), with_embedding=True):

    cnn = make_text_cnn(sentence_size, num_embed, batch_size=batch_size,
            vocab_size=vocab_size, dropout=dropout, with_embedding=with_embedding)
    arg_names = cnn.list_arguments()

    input_shapes = {}
    if with_embedding:
        input_shapes['data'] = (batch_size, 1, sentence_size, num_embed)
    else:
        input_shapes['data'] = (batch_size, sentence_size)

    arg_shape, out_shape, aux_shape = cnn.infer_shape(**input_shapes)
    arg_arrays = [mx.nd.zeros(s, ctx) for s in arg_shape]
    args_grad = {}
    for shape, name in zip(arg_shape, arg_names):
        if name in ['softmax_label', 'data']: # input, output
            continue
        args_grad[name] = mx.nd.zeros(shape, ctx)

    cnn_exec = cnn.bind(ctx=ctx, args=arg_arrays, args_grad=args_grad, grad_req='add')

    param_blocks = []
    arg_dict = dict(zip(arg_names, cnn_exec.arg_arrays))
    for i, name in enumerate(arg_names):
        if name in ['softmax_label', 'data']: # input, output
            continue
        initializer(name, arg_dict[name])

        param_blocks.append( (i, arg_dict[name], args_grad[name], name) )

    out_dict = dict(zip(cnn.list_outputs(), cnn_exec.outputs))

    data = cnn_exec.arg_dict['data']
    label = cnn_exec.arg_dict['softmax_label']

    return CNNModel(cnn_exec=cnn_exec, symbol=cnn, data=data, label=label, param_blocks=param_blocks)

def train_cnn(model, X_train_batch, y_train_batch, X_dev_batch, y_dev_batch, batch_size,
        optimizer='rmsprop', max_grad_norm=5.0, learning_rate=0.0005, epoch=200):
    m = model
    # create optimizer
    opt = mx.optimizer.create(optimizer)
    opt.lr = learning_rate

    updater = mx.optimizer.get_updater(opt)

    for iteration in range(epoch):
        tic = time.time()
        num_correct = 0
        num_total = 0
        for begin in range(0, X_train_batch.shape[0], batch_size):
            batchX = X_train_batch[begin:begin+batch_size]
            batchY = y_train_batch[begin:begin+batch_size]
            if batchX.shape[0] != batch_size:
                continue

            m.data[:] = batchX
            m.label[:] = batchY

            # forward
            m.cnn_exec.forward(is_train=True)

            # backward
            m.cnn_exec.backward()

            # eval on training data
            num_correct += sum(batchY == np.argmax(m.cnn_exec.outputs[0].asnumpy(), axis=1))
            num_total += len(batchY)

            # update weights
            norm = 0
            for idx, weight, grad, name in m.param_blocks:
                grad /= batch_size
                l2_norm = mx.nd.norm(grad).asscalar()
                norm += l2_norm * l2_norm

            norm = math.sqrt(norm)
            for idx, weight, grad, name in m.param_blocks:
                if norm > max_grad_norm:
                    grad *= (max_grad_norm / norm)

                updater(idx, grad, weight)

                # reset gradient to zero
                grad[:] = 0.0

        # decay learning rate
        if iteration % 50 == 0 and iteration > 0:
            opt.lr *= 0.5
            print('reset learning rate to %g' % opt.lr,file=logs)

        # end of training loop
        toc = time.time()
        train_time = toc - tic
        train_acc = num_correct * 100 / float(num_total)

        # saving checkpoint
        if (iteration + 1) % 10 == 0:
            prefix = 'cnn'
            m.symbol.save('checkpoint/%s-symbol.json' % prefix)
            save_dict = {('arg:%s' % k) :v  for k, v in m.cnn_exec.arg_dict.items()}
            save_dict.update({('aux:%s' % k) : v for k, v in m.cnn_exec.aux_dict.items()})
            param_name = 'checkpoint/%s-%04d.params' % (prefix, iteration)
            mx.nd.save(param_name, save_dict)
            print('Saved checkpoint to %s' % param_name,file=logs)

        # evaluate on dev set
        num_correct = 0
        num_total = 0
        for begin in range(0, X_dev_batch.shape[0], batch_size):
            batchX = X_dev_batch[begin:begin+batch_size]
            batchY = y_dev_batch[begin:begin+batch_size]

            if batchX.shape[0] != batch_size:
                continue

            m.data[:] = batchX
            m.cnn_exec.forward(is_train=False)

            num_correct += sum(batchY == np.argmax(m.cnn_exec.outputs[0].asnumpy(), axis=1))
            num_total += len(batchY)

        dev_acc = num_correct * 100 / float(num_total)
        print('Iter [%d] Train: Time: %.3fs, Training Accuracy: %.3f \
                --- Dev Accuracy thus far: %.3f' % (iteration, train_time, train_acc, dev_acc), file=logs)

def main():
    print('Loading data...')
    # word2vec = data_helpers.load_google_word2vec('data/GoogleNews-vectors-negative300.bin')
    word2vec = data_helpers.load_pretrained_word2vec('data/rt.vec')
    x, y = data_helpers.load_data_with_word2vec(word2vec)

    # randomly shuffle data
    np.random.seed(10)
    shuffle_indices = np.random.permutation(np.arange(len(y)))
    x_shuffled = x[shuffle_indices]
    y_shuffled = y[shuffle_indices]

    # split train/dev set
    x_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:]
    y_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:]
    print('Train/Dev split: %d/%d' % (len(y_train), len(y_dev)))
    print('train shape:', x_train.shape)
    print('dev shape:', x_dev.shape)

    # reshpae for convolution input
    x_train = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1], x_train.shape[2]))
    x_dev = np.reshape(x_dev, (x_dev.shape[0], 1, x_dev.shape[1], x_dev.shape[2]))

    num_embed = x_train.shape[-1]
    sentence_size = x_train.shape[2]
    print('sentence max words', sentence_size)
    print('embedding size', num_embed)
    batch_size = 50

    cnn_model = setup_cnn_model(mx.gpu(1), batch_size, sentence_size, num_embed, dropout=0.5)
    train_cnn(cnn_model, x_train, y_train, x_dev, y_dev, batch_size)

def train_without_pretrained_embedding():
    x, y, vocab, vocab_inv = data_helpers.load_data()
    vocab_size = len(vocab)

    # randomly shuffle data
    np.random.seed(10)
    shuffle_indices = np.random.permutation(np.arange(len(y)))
    x_shuffled = x[shuffle_indices]
    y_shuffled = y[shuffle_indices]

    # split train/dev set
    x_train, x_dev = x_shuffled[:-1000], x_shuffled[-1000:]
    y_train, y_dev = y_shuffled[:-1000], y_shuffled[-1000:]
    print('Train/Dev split: %d/%d' % (len(y_train), len(y_dev)))
    print('train shape:', x_train.shape)
    print('dev shape:', x_dev.shape)
    print('vocab_size', vocab_size)

    batch_size = 50
    num_embed = 300
    sentence_size = x_train.shape[1]

    print('batch size', batch_size)
    print('sentence max words', sentence_size)
    print('embedding size', num_embed)

    cnn_model = setup_cnn_model(mx.gpu(0), batch_size, sentence_size, num_embed, vocab_size, dropout=0.5, with_embedding=False)
    train_cnn(cnn_model, x_train, y_train, x_dev, y_dev, batch_size)

if __name__ == '__main__':
    if not os.path.exists("checkpoint"):
        os.mkdir("checkpoint")
    train_without_pretrained_embedding()


text:
package hell.entities.items;

import hell.interfaces.Item;

public abstract class ItemImpl implements Item {
    private String name;
    private int strengthBonus;
    private int agilityBonus;
    private int intelligenceBonus;
    private int hitPointsBonus;
    private int damageBonus;

    protected ItemImpl(String name, int strengthBonus, int agilityBonus, int intelligenceBonus, int hitPointsBonus, int damageBonus) {
        this.name = name;
        this.strengthBonus = strengthBonus;
        this.agilityBonus = agilityBonus;
        this.intelligenceBonus = intelligenceBonus;
        this.hitPointsBonus = hitPointsBonus;
        this.damageBonus = damageBonus;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public int getStrengthBonus() {
        return this.strengthBonus;
    }

    @Override
    public int getAgilityBonus() {
        return this.agilityBonus;
    }

    @Override
    public int getIntelligenceBonus() {
        return this.intelligenceBonus;
    }

    @Override
    public int getHitPointsBonus() {
        return this.hitPointsBonus;
    }

    @Override
    public int getDamageBonus() {
        return this.damageBonus;
    }

    @Override
    public String toString() {
        return this.name;
    }
}


text: public class <caret>B {}


text:
<!--

    Copyright (c) 2012-2016 Codenvy, S.A.
    All rights reserved. This program and the accompanying materials
    are made available under the terms of the Eclipse Public License v1.0
    which accompanies this distribution, and is available at
    http://www.eclipse.org/legal/epl-v10.html

    Contributors:
      Codenvy, S.A. - initial API and implementation

-->
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
    <id>terminal</id>
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/dir</directory>
            <outputDirectory></outputDirectory>
        </fileSet>
    </fileSets>
</assembly>


text:
Meteor.startup(function () {
    // code to run on server at startup
  });

Meteor.publish("needs", function () {
  return Needs.find();
});

Meteor.publish("categories", function() {
  return Categories.find();
});

Meteor.publish("userData", function () {
  if (this.userId) {
    return Meteor.users.find({_id: this.userId},
      {fields: {'organization': 1}});
  } else {
    this.ready();
  }
});


text:
#ifndef BITCOIN_CHAINPARAMSCONSTANTS_H
#define BITCOIN_CHAINPARAMSCONSTANTS_H
/**
 * Chain params constants for each tracked chain.
 * @generated by contrib/devtools/chainparams/generate_chainparams_constants.py
 */

#include <primitives/blockhash.h>
#include <uint256.h>

namespace ChainParamsConstants {
    const BlockHash MAINNET_DEFAULT_ASSUME_VALID = BlockHash::fromHex("000000000000000002604b1075406a655d3588532eff9d461ba3b0077c7b599d");
    const uint256 MAINNET_MINIMUM_CHAIN_WORK = uint256S("00000000000000000000000000000000000000000134abd2dd57c5029c83da21");
    const uint64_t MAINNET_ASSUMED_BLOCKCHAIN_SIZE = 203;
    const uint64_t MAINNET_ASSUMED_CHAINSTATE_SIZE = 3;

    const BlockHash TESTNET_DEFAULT_ASSUME_VALID = BlockHash::fromHex("000000000002a4932f1440c0397af3fc3dc87ee0881829b934241b4e8ed62d5c");
    const uint256 TESTNET_MINIMUM_CHAIN_WORK = uint256S("000000000000000000000000000000000000000000000067b221b87800d667e0");
    const uint64_t TESTNET_ASSUMED_BLOCKCHAIN_SIZE = 55;
    const uint64_t TESTNET_ASSUMED_CHAINSTATE_SIZE = 2;
} // namespace ChainParamsConstants

#endif // BITCOIN_CHAINPARAMSCONSTANTS_H


text:
Pasword Generartor (Visual Basic)
===============================

A Visual Basic  simple program for generating random passwords and strong salts [ideal for websites].

## Requirements
- Visual Studio 2012 Express
*I'm not sure if this will compile in older Visual Studio compilers.*

## Usage

**Compiling Project**

1. Double click *Password Generator.sln* so Visual Studio Express [or better] can open the project.
2. Compile the project to create a binary file.
3. Double click the generated binary file.

**Using the binary file**

1. Download the binary file [Password Generator.zip](https://github.com/LagrangianPoint/Pasword-Generartor-Visual-Basic/raw/master/Password%20Generator/bin/Debug/Password%20Generator.zip)
2. Double click to run it.


text:
from os.path import exists
import os
import time
import sys
import logging
import subprocess
import settings
import schedule
import cron
import shutil

# this import must happen before any github api stuff gets imported.  it sets
# up caching on the api functions so we don't run out of api requests
import patch  # noqa: F401

import github_api as gh
import github_api.prs
import github_api.voting
import github_api.repos
import github_api.comments
import github_api.issues

# Has a sideeffect of creating private key if one doesn't exist already
# Currently imported just for the sideeffect (not currently being used)
import encryption  # noqa: F401

class LessThanFilter(logging.Filter):
    """
    Source: https://stackoverflow.com/questions/2302315
    """
    def __init__(self, exclusive_maximum, name=""):
        super(LessThanFilter, self).__init__(name)
        self.max_level = exclusive_maximum

    def filter(self, record):
        """
        non-zero return means we log this message
        """
        return 1 if record.levelno < self.max_level else 0

def main():
    # Set up logging stuff
    logging_handler_out = logging.StreamHandler(sys.stdout)
    logging_handler_out.setLevel(settings.LOG_LEVEL_OUT)
    logging_handler_out.addFilter(LessThanFilter(settings.LOG_LEVEL_ERR))

    logging_handler_err = logging.StreamHandler(sys.stderr)
    logging_handler_err.setLevel(settings.LOG_LEVEL_ERR)

    logging.basicConfig(level=logging.NOTSET,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        datefmt='%m-%d %H:%M',
                        handlers=[logging_handler_out, logging_handler_err])

    logging.getLogger("requests").propagate = False
    logging.getLogger("sh").propagate = False
    logging.getLogger("peewee").propagate = False

    log = logging.getLogger("chaosbot")

    if exists("voters.json"):
        log.info("Moving voters.json to server directory!")
        shutil.move("./voters.json", "./server/voters.json")

    api = gh.API(settings.GITHUB_USER, settings.GITHUB_SECRET)

    log.info("checking if I crashed before...")

    # check if chaosbot is not on the tip of the master branch
    check_for_prev_crash(api, log)

    log.info("starting up and entering event loop")

    os.system("pkill uwsgi")

    subprocess.Popen(["/root/.virtualenvs/chaos/bin/uwsgi",
                      "--socket", "127.0.0.1:8085",
                      "--wsgi-file", "webserver.py",
                      "--callable", "__hug_wsgi__",
                      "--check-static", "/root/workspace/Chaos/server/",
                      "--daemonize", "/root/workspace/Chaos/log/uwsgi.log"])

    # Schedule all cron jobs to be run
    cron.schedule_jobs(api)

    log.info("Setting description to {desc}".format(desc=settings.REPO_DESCRIPTION))
    github_api.repos.set_desc(api, settings.URN, settings.REPO_DESCRIPTION)

    log.info("Ensure creation of issue/PR labels")
    for label, color in settings.REPO_LABELS.items():
        github_api.repos.create_label(api, settings.URN, label, color)

    while True:
        # Run any scheduled jobs on the next second.
        schedule.run_pending()
        time.sleep(1)

def check_for_prev_crash(api, log):
    """
    Check if Chaosbot is attempting a recovery from a failure. If it is, then
    read the failure file created by chaos_wrapper.sh and make a github issue
    for the failure.
    """
    if exists(settings.CHAOSBOT_FAILURE_FILE):
        with open(settings.CHAOSBOT_FAILURE_FILE, "r") as cff:
            log.info("it looks like I did... posting on github...")

            # read the failure file... the format is
            #
            #   FAILED_GIT_SHA CURRENT_GIT_SHA
            #
            # where FAILED_GIT_SHA is the one that crashed, and CURRENT_GIT_SHA
            # is the one currently running.
            failed, current = cff.readline().split(" ")

            # read the error log
            # Currently, I'm just reading the last 200 lines... which I think
            # ought to be enough, but if anyone has a better way to do this,
            # please do it.
            dump = subprocess.check_output(["tail", "-n", "200", settings.CHAOSBOT_STDERR_LOG])

            # Create a github issue for the problem
            title = "Help! I crashed! --CB"
            labels = ["crash report"]
            body = """
Oh no! I crashed!

Failed on SHA {failed}
Rolled back to SHA {current}

Error log:
```
{dump}
```
""".format(failed=failed, current=current, dump=bytes.decode(dump))

            gh.issues.create_issue(api, settings.URN, title, body, labels)

            # remove the error file
            os.remove(settings.CHAOSBOT_FAILURE_FILE)

if __name__ == "__main__":
    main()


text:
package com.jinject.action.api;

public interface IActionBinder {

}


text:
		<title>WebGL - 09 Lots of moving objects</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="stylesheet" href="./style/webgl.css" type="text/css">

WebGL - 09 Lots of moving objects

			<canvas id="glcanvas" width="1280px" height="720px">
				No <canvas> suppport in your browser.
			</canvas>

		    <input type="checkbox" id="twinkle" checked /> Twinkle

		    (Use cursor keys to rotate, and Page Up/Page Down to zoom out/in)

			<- Back


text:
package com.avos.demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.avos.demo.R;

public class CreateTodo extends Activity {

	private EditText nameText;
	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.create_todo);
		setTitle(R.string.create_todo);

		nameText = (EditText) findViewById(R.id.name);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String name = extras.getString("name");
			position = extras.getInt("position");

			if (name != null) {
				nameText.setText(name);
			}
		}

		Button confirmButton = (Button) findViewById(R.id.confirm);
		confirmButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Bundle bundle = new Bundle();
				bundle.putString("name", nameText.getText().toString());
				bundle.putInt("position", position);

				Intent intent = new Intent();
				intent.putExtras(bundle);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
	}

}


text:
//$Id: main.cc 836 2007-05-09 03:02:38Z jjongsma $ -*- c++ -*-

#include <gtkmm/main.h>
#include "examplewindow.h"

int main(int argc, char *argv[])
{
  Gtk::Main kit(argc, argv);

  ExampleWindow window;
  //Shows the window and returns when it is closed.
  Gtk::Main::run(window);

  return 0;
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DataTableFormatters
{
    internal class MarkupDataTableFormatter : BaseDataTableFormatter
    {
        private readonly IFormatConfiguration[] _options;

        public MarkupDataTableFormatter(IFormatConfiguration[] options)
        {
            _options = options;
        }

        protected override IEnumerable<string> GetStringRepresentation(DataTable dataTable)
        {
            if (dataTable == null)
                throw new ArgumentNullException("dataTable");

            var columnWidths = dataTable.DataColumns().Select(ColumnMaxElementLength).ToList();

            return Concatenate(
                Headers(columnWidths),
                Contents(dataTable.DataRows(), columnWidths));
        }

        private static ColumnAndWidth ColumnMaxElementLength(DataColumn column)
        {
            int? maxLength = column.Table.DataRows()
                .Select(row => (int?)row[column].ToString().Length)
                .Max();

            return new ColumnAndWidth(
                column,
                Math.Max(
                    column.ColumnName.Length,
                    maxLength ?? 0));
        }

        private IEnumerable<string> Headers(IList<ColumnAndWidth> columnWidths)
        {
            return Interlace(
                "

",
                columnWidths.Select(x =>
                {
                    var alignedColumnName = Align(x.ColumnName, x.ColumnName, x.Width);
                    return alignedColumnName;
                }),
                "	",
                "

");
        }

        private string Align(string columnName, string content, int width)
        {
            return _options.OfType<RightAlign>().Any(x => x.ColumnName == columnName)
                ? content.PadLeft(width)
                : content.PadRight(width);
        }

        private IEnumerable<string> Contents(IEnumerable<DataRow> rows, IList<ColumnAndWidth> columnWidths)
        {
            return rows.SelectMany(row => Row(columnWidths, row));
        }

        private IEnumerable<string> Row(IList<ColumnAndWidth> columnWidths, DataRow row)
        {
            return Interlace(
                "

",
                columnWidths.Select((x, i) => Cell(row, i, x)),
                "	",
                "

");
        }

        private string Cell(DataRow row, int index, ColumnAndWidth columnWidth)
        {
            string stringRepresentation;
            if (row[index] == DBNull.Value)
            {
                stringRepresentation = "NULL";
            }
            else
            {
                var format = _options.OfType<CustomFormat>().FirstOrDefault(y => y.ColumnName == columnWidth.ColumnName);
                var formatString = format == null ? "{0}" : "{0:" + format.FormatString + "}";
                stringRepresentation = string.Format(formatString, row[index]);
            }

            string alignedContent = Align(columnWidth.ColumnName, stringRepresentation, columnWidth.Width);
            return alignedContent;
        }

        private static IEnumerable<T> Interlace<T>(T prefix, IEnumerable<T> list, T separator, T suffix)
        {
            yield return prefix;
            if (list.Any())
            {
                yield return list.First();
                foreach (T item in list.Skip(1))
                {
                    yield return separator;
                    yield return item;
                }
            }

            yield return suffix;
        }

        private static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] lists)
        {
            return lists.SelectMany(x => x);
        }

        private class ColumnAndWidth
        {
            public ColumnAndWidth(DataColumn column, int width)
            {
                ColumnName = column.ColumnName;
                Width = width;
            }

            public string ColumnName { get; set; }
            public int Width { get; set; }
        }
    }
}


text:
/*eslint max-len: 0, no-var:0 */

const charsRegex = /[\0\b\t\n\r\x1a"'\\]/g; // eslint-disable-line no-control-regex
const charsMap = {
  '\0': '\\0',
  '\b': '\\b',
  '\t': '\\t',
  '\n': '\\n',
  '\r': '\\r',
  '\x1a': '\\Z',
  '"': '\\"',
  "'": "\\'",
  '\\': '\\\\',
};

function wrapEscape(escapeFn) {
  return function finalEscape(val, ctx = {}) {
    return escapeFn(val, finalEscape, ctx);
  };
}

function makeEscape(config = {}) {
  const finalEscapeDate = config.escapeDate || dateToString;
  const finalEscapeArray = config.escapeArray || arrayToList;
  const finalEscapeBuffer = config.escapeBuffer || bufferToString;
  const finalEscapeString = config.escapeString || escapeString;
  const finalEscapeObject = config.escapeObject || escapeObject;
  const finalWrap = config.wrap || wrapEscape;

  function escapeFn(val, finalEscape, ctx) {
    if (val === undefined || val === null) {
      return 'NULL';
    }
    switch (typeof val) {
      case 'boolean':
        return val ? 'true' : 'false';
      case 'number':
        return val + '';
      case 'object':
        if (val instanceof Date) {
          val = finalEscapeDate(val, finalEscape, ctx);
        } else if (Array.isArray(val)) {
          return finalEscapeArray(val, finalEscape, ctx);
        } else if (Buffer.isBuffer(val)) {
          return finalEscapeBuffer(val, finalEscape, ctx);
        } else {
          return finalEscapeObject(val, finalEscape, ctx);
        }
    }
    return finalEscapeString(val, finalEscape, ctx);
  }

  return finalWrap ? finalWrap(escapeFn) : escapeFn;
}

function escapeObject(val, finalEscape, ctx) {
  if (val && typeof val.toSQL === 'function') {
    return val.toSQL(ctx);
  } else {
    return JSON.stringify(val);
  }
}

function arrayToList(array, finalEscape, ctx) {
  let sql = '';
  for (let i = 0; i < array.length; i++) {
    const val = array[i];
    if (Array.isArray(val)) {
      sql +=
        (i === 0 ? '' : ', ') + '(' + arrayToList(val, finalEscape, ctx) + ')';
    } else {
      sql += (i === 0 ? '' : ', ') + finalEscape(val, ctx);
    }
  }
  return sql;
}

function bufferToString(buffer) {
  return 'X' + escapeString(buffer.toString('hex'));
}

function escapeString(val, finalEscape, ctx) {
  let chunkIndex = (charsRegex.lastIndex = 0);
  let escapedVal = '';
  let match;

  while ((match = charsRegex.exec(val))) {
    escapedVal += val.slice(chunkIndex, match.index) + charsMap[match[0]];
    chunkIndex = charsRegex.lastIndex;
  }

  if (chunkIndex === 0) {
    // Nothing was escaped
    return "'" + val + "'";
  }

  if (chunkIndex < val.length) {
    return "'" + escapedVal + val.slice(chunkIndex) + "'";
  }

  return "'" + escapedVal + "'";
}

function dateToString(date, finalEscape, ctx = {}) {
  const timeZone = ctx.timeZone || 'local';

  const dt = new Date(date);
  let year;
  let month;
  let day;
  let hour;
  let minute;
  let second;
  let millisecond;

  if (timeZone === 'local') {
    year = dt.getFullYear();
    month = dt.getMonth() + 1;
    day = dt.getDate();
    hour = dt.getHours();
    minute = dt.getMinutes();
    second = dt.getSeconds();
    millisecond = dt.getMilliseconds();
  } else {
    const tz = convertTimezone(timeZone);

    if (tz !== false && tz !== 0) {
      dt.setTime(dt.getTime() + tz * 60000);
    }

    year = dt.getUTCFullYear();
    month = dt.getUTCMonth() + 1;
    day = dt.getUTCDate();
    hour = dt.getUTCHours();
    minute = dt.getUTCMinutes();
    second = dt.getUTCSeconds();
    millisecond = dt.getUTCMilliseconds();
  }

  // YYYY-MM-DD HH:mm:ss.mmm
  return (
    zeroPad(year, 4) +
    '-' +
    zeroPad(month, 2) +
    '-' +
    zeroPad(day, 2) +
    ' ' +
    zeroPad(hour, 2) +
    ':' +
    zeroPad(minute, 2) +
    ':' +
    zeroPad(second, 2) +
    '.' +
    zeroPad(millisecond, 3)
  );
}

function zeroPad(number, length) {
  number = number.toString();
  while (number.length < length) {
    number = '0' + number;
  }
  return number;
}

function convertTimezone(tz) {
  if (tz === 'Z') {
    return 0;
  }
  const m = tz.match(/([+\-\s])(\d\d):?(\d\d)?/);
  if (m) {
    return (
      (m[1] == '-' ? -1 : 1) *
      (parseInt(m[2], 10) + (m[3] ? parseInt(m[3], 10) : 0) / 60) *
      60
    );
  }
  return false;
}

module.exports = {
  arrayToList,
  bufferToString,
  dateToString,
  escapeString,
  charsRegex,
  charsMap,
  escapeObject,
  makeEscape,
};


text:
<?php

namespace Gettext\Utils;

class JsFunctionsScanner extends FunctionsScanner
{
    protected $code;
    protected $status = [];

    /**
     * Constructor.
     *
     * @param string $code The php code to scan
     */
    public function __construct($code)
    {
        // Normalize newline characters
        $this->code = str_replace(["\r\n", "\n\r", "\r"], "\n", $code);
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions(array $constants = [])
    {
        $length = strlen($this->code);
        $line = 1;
        $buffer = '';
        $functions = [];
        $bufferFunctions = [];
        $char = null;

        for ($pos = 0; $pos < $length; ++$pos) {
            $prev = $char;
            $char = $this->code[$pos];
            $next = isset($this->code[$pos + 1]) ? $this->code[$pos + 1] : null;

            switch ($char) {
                case '\\':
                    $prev = $char;
                    $char = $next;
                    $pos++;
                    $next = isset($this->code[$pos]) ? $this->code[$pos] : null;
                    break;

                case "\n":
                    ++$line;

                    if ($this->status('line-comment')) {
                        $this->upStatus();
                    }
                    break;

                case '/':
                    switch ($this->status()) {
                        case 'simple-quote':
                        case 'double-quote':
                        case 'line-comment':
                            break;

                        case 'block-comment':
                            if ($prev === '*') {
                                $this->upStatus();
                            }
                            break;

                        default:
                            if ($next === '/') {
                                $this->downStatus('line-comment');
                            } elseif ($next === '*') {
                                $this->downStatus('block-comment');
                            }
                            break;
                    }
                    break;

                case "'":
                    switch ($this->status()) {
                        case 'simple-quote':
                            $this->upStatus();
                            break;

                        case 'line-comment':
                        case 'block-comment':
                        case 'double-quote':
                            break;

                        default:
                            $this->downStatus('simple-quote');
                            break;
                    }
                    break;

                case '"':
                    switch ($this->status()) {
                        case 'double-quote':
                            $this->upStatus();
                            break;

                        case 'line-comment':
                        case 'block-comment':
                        case 'simple-quote':
                            break;

                        default:
                            $this->downStatus('double-quote');
                            break;
                    }
                    break;

                case '(':
                    switch ($this->status()) {
                        case 'simple-quote':
                        case 'double-quote':
                        case 'line-comment':
                        case 'block-comment':
                        case 'line-comment':
                            break;

                        default:
                            if ($buffer && preg_match('/(\w+)$/', $buffer, $matches)) {
                                $this->downStatus('function');
                                array_unshift($bufferFunctions, [$matches[1], $line, []]);
                                $buffer = '';
                                continue 3;
                            }
                            break;
                    }
                    break;

                case ')':
                    switch ($this->status()) {
                        case 'function':
                            if (($argument = self::prepareArgument($buffer))) {
                                $bufferFunctions[0][2][] = $argument;
                            }

                            if (!empty($bufferFunctions)) {
                                $functions[] = array_shift($bufferFunctions);
                            }

                            $this->upStatus();
                            $buffer = '';
                            continue 3;
                    }
                    break;

                case ',':
                    switch ($this->status()) {
                        case 'function':
                            if (($argument = self::prepareArgument($buffer))) {
                                $bufferFunctions[0][2][] = $argument;
                            }

                            $buffer = '';
                            continue 3;
                    }
                    break;

                case ' ':
                case '\t':
                    switch ($this->status()) {
                        case 'double-quote':
                        case 'simple-quote':
                            break;

                        default:
                            $buffer = '';
                            continue 3;
                    }
                    break;
            }

            switch ($this->status()) {
                case 'line-comment':
                case 'block-comment':
                    break;

                default:
                    $buffer .= $char;
                    break;
            }
        }

        return $functions;
    }

    /**
     * Get the current context of the scan.
     *
     * @param null|string $match To check whether the current status is this value
     *
     * @return string|bool
     */
    protected function status($match = null)
    {
        $status = isset($this->status[0]) ? $this->status[0] : null;

        if ($match !== null) {
            return $status === $match;
        }

        return $status;
    }

    /**
     * Add a new status to the stack.
     *
     * @param string $status
     */
    protected function downStatus($status)
    {
        array_unshift($this->status, $status);
    }

    /**
     * Removes and return the current status.
     *
     * @return string|null
     */
    protected function upStatus()
    {
        return array_shift($this->status);
    }

    /**
     * Prepares the arguments found in functions.
     *
     * @param string $argument
     *
     * @return string
     */
    protected static function prepareArgument($argument)
    {
        if ($argument && ($argument[0] === '"' || $argument[0] === "'")) {
            return substr($argument, 1, -1);
        }
    }
}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  tickRate: 10,
  _p: null, // current promise, null when not running
  _shoudStop: true, // set to true when running

  assertHasTickMethod: Ember.on('init', function () {
    Ember.assert(
      '`state-loop` requires a `tick` method to be defined in sub class',
      Ember.$.type(this.tick) === 'function'
    );
  }),

  run: function () {
    this.set('_shouldStop', false);

    const promise = new Ember.RSVP.Promise((resolve) => {
      const thunkTick = () => {
        Ember.run.later(() => {
          if (
            !this.get('_shouldStop') &&
            !this.get('isDestroyed') &&
            !this.get('isDestroying')
          ) {
            this.tick();
            thunkTick();
          } else {
            resolve();
          }
        }, this.get('tickRate'));
      };

      thunkTick();
    });

    this.set('_p', promise);
    return promise;
  },

  stop: function () {
    const p = this.get('_p');
    this.set('_shouldStop', true);
    this.set('_p', null);
    return p;
  }
});


text:
var Client = require('../models').Client;
var Invoice = require('../models').Invoice;
var InvoiceDetail = require('../models').InvoiceDetail;
var clientAttributes = ['clientId', 'firstName', 'lastName', 'address', 'phoneNumber', 'mobileNumber', 'pictureLocation']
module.exports = {
    create: function(client, res) {
        Client.create(client)
            .then((createdClient) => {

                res.json({ success: true, client: createdClient })
            })
            .catch((error) => {
                res.json({ success: false, error: "Client could no be added" });
            });
    },

    findOne: function(req, res) {
        Client.findOne({
                attributes: clientAttributes,
                where: { clientId: req.params.id },
                include: [{
                    model: Invoice,
                    as: 'purchases'
                }]
            })
            .then((client) => {
                res.json({ success: true, client: client });
            })
            .catch((error) => {
                console.log(error);
                res.json({ success: false, error: "Error finding client" });
            });
    },
    delete: function(req, res) {
        Client.findOne({ where: { clientId: req.params.id } }).then(client => {
            client.destroy()
                .then(() => res.json({ success: true }))
                .catch(error => res.json({ success: false, error: 'Client could not be deleted' }));

        }).catch(error => {
            res.json({ success: false, error: 'Client could not be found' });
        });
    },

    update: function(req, res) {
        Client.update(req.body, { where: { clientId: req.body.clientId } })
            .then((updated) => {
                if (updated[0] > 0)
                    res.json({ success: true });
                else
                    res.json({ success: false, error: "Client could not be found or no field was updated" });
            })
            .catch((error) => {
                res.json({ success: false, error: "Client could not be updated succesfully" });
            });
    },
    findAll: function(req, res) {
        Client.findAll({
                attributes: clientAttributes,
                include: [{
                    model: Invoice,
                    as: 'purchases'
                }]
            })
            .then((clients) => {
                res.json({ success: true, clients: clients });
            })
            .catch((error) => {
                res.json({ success: false, error: "Error finding clientes" });
            });
    }
};