text:
angular.module('roadmaps.ctrl', ['roadmaps.factory', 'services.server', 'services.user', 'scraper.ctrl'])

.controller('RoadMapsController', [ '$scope', '$http', '$stateParams', 'RoadMapsFactory', 'Server', 'User', '$timeout', '$state', function($scope, $http, $stateParams, RoadMapsFactory, Server, User, $timeout, $state){
  angular.extend($scope, RoadMapsFactory);

  var NODE_DEFAULTS = {
    title: 'New node title',
    description: 'New node description',
    resourceType: 'New node type',
    resourceURL: 'New node link (optional)',
    imageUrl: 'https://openclipart.org/image/2400px/svg_to_png/103885/SimpleStar.png'
  }

  var roadmapId = $stateParams.roadmapID;
  $scope.currentRoadMapData = {};
  $scope.renderedNodes = [];
  $('.tooltipped').tooltip({delay: 50});

  $scope.showComments = false;
  $scope.currentIndex = 0;

  $scope.toggleComments = function(){
    $scope.showComments = !$scope.showComments;
  };

  $scope.isAuthor = function (){
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username;
    if (username === roadmapAuthor){
      return true;
    } else {
      return false;
    }
  };

  $scope.resetCreationForm = function() {
    $scope.urlToScrape = "Paste a link here to get info automatically";
    $scope.currentCreationTitle = NODE_DEFAULTS.title;
    $scope.currentCreationDescription = NODE_DEFAULTS.description;
    $scope.currentCreationType = NODE_DEFAULTS.resourceType;
    $scope.currentCreationLink = NODE_DEFAULTS.resourceURL;
    $scope.currentCreationImage = 'New node image (optional)';
  }

  $scope.resetCreationForm();

  $scope.displayUrl = '';
  $scope.scrape = {};

  $scope.checkAndSubmit = function() {
    var url = $scope.urlToScrape;
    if (url.length < 4) return;
    if (url.substring(0, 4) !== 'http') url = 'http://' + url;

    $scope.displayUrl = url;
    console.log("scraping url", url);
    Server.scrape(url)
    .then(function (data) {
      console.log('web scrape data is', data);
        $scope.currentCreationTitle = data.title;
        $scope.currentCreationDescription = data.description;
        $scope.currentCreationType = data.type;
        $scope.currentCreationLink = url;
        $scope.currentCreationImage = data.imageUrl;
    });
  };

  $scope.showNodeCreator = function($index, boolean){
    console.log("SHOWNODECRETAOR $index:", $index);
    $scope.currentAddIndex = $index + 1;
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username;
    console.log("'mini-circle-' + $index", 'mini-circle-' + $index);
    $scope.currentAddIndex = $index;
    if( username !== roadmapAuthor ){
      $scope.nodeCreator = false;
      console.log("author fail");
    } else {

      $scope.displayNodeCreator = boolean;
    }
  }

  $scope.createNode = function($index) {
    console.log($scope.currentCreationImage);
    if( $scope.currentCreationImage === 'New node image (optional)' ){
      $scope.currentCreationImage = NODE_DEFAULTS.imageUrl;
    }
    $('#editor-placeholder').remove();
    console.log("CREATE NODE $index", $index);

    return Server.createNode({
      title: $scope.currentCreationTitle || NODE_DEFAULTS.title,
      description: $scope.currentCreationDescription || NODE_DEFAULTS.description,
      resourceType: $scope.currentCreationType || NODE_DEFAULTS.resourceType,
      resourceURL: $scope.currentCreationLink || NODE_DEFAULTS.resourceURL,
      imageUrl: $scope.currentCreationImage || NODE_DEFAULTS.imageUrl,
      parentRoadmap: roadmapId,
      saveAtIndex: $index + 1

    })
    .then(function(res){
      populateData();
      console.log("node created");
      $scope.displayNodeCreator = false;
      Materialize.toast('Node Added!', 4000, 'orangeToast');
      $scope.resetCreationForm();
    });
  };

  $scope.closeNodeCreator = function(){
    $scope.displayNodeCreator = false;
    $scope.resetCreationForm();
  }

  $scope.hideText = function ($index, field, idPrefix){
    $index = $index || 0;
    var elementID = '#' + idPrefix + '-' + field + '-' + $index;
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username || '';
    if( username !== roadmapAuthor ){
      return false;
    } else {
      if( !$scope[elementID] ){
        return  false;
      } else {
        return true;
      }
    }
  };

  $scope.showEditor = function ($index, field, boolean, idPrefix){
    var elementID = '#' + idPrefix + '-' + field + '-' + $index;
    $scope.currentIndex = $index;
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username;

    if( username !== roadmapAuthor ){
      $scope[elementID] = false;
      console.log("author fail");
    } else {
      if( field === 'circle' && idPrefix === 'mini'){
        $scope.resetCreationForm();
      }
      if( !$scope.currentResourceURL ) {
        $scope.currentResourceURL = $scope.currentLinks[0];
      }

      if(boolean === false && field !== 'circle'){
        $(elementID).val($scope.renderedNodes[$index][field]);
      }
      console.log("SHOW EDITOR");
      console.log('elementID', elementID);
      console.log('$scope[elementID]', $scope[elementID]);
      $scope[elementID] = boolean;
    }

  };

  $scope.getPlaceholder = function($index, field){
    var capitalizedField = field.substr(0, 1).toUpperCase() + field.substr(1);
    return $scope['current' + capitalizedField];
  };

  $scope.saveEdit = function($index, field, idPrefix){
    var elementID = '#' + idPrefix + '-' + field + '-' + $index;
    var newProperty = $(elementID).val();
    var updateObj = {};
    updateObj['_id'] = $scope.renderedNodes[$index]._id;
    updateObj[field] = newProperty;
    Server.updateNode(updateObj)
      .then(function(node) {
      $scope.showEditor($index, field, false, idPrefix);
      $scope.renderedNodes[$index][field] = newProperty;
      var capitalizedField = field.substr(0, 1).toUpperCase() + field.substr(1);
      $scope['current' + capitalizedField] = newProperty;
      if( field === 'resourceURL' ){
        $scope.currentLinks[0] = newProperty;
      }
    })
      .catch(function(){
        console.log('problem updating node', err);
      });
  };

  //roadMapTitle

  $scope.hideTitle = false;
  $scope.hideDesc = false;

  $scope.showTitleEditor = function (boolean){
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username;
    var storedTitle;

    if( username !== roadmapAuthor ){
      $scope.hideTitle = false;
    } else {
      $scope.hideTitle = boolean;
      return $scope.hideTitle;
    }

  };

  $scope.saveTitleEdit = function (){
    var newProperty = $('#main-title').val();
    var updateObj = {};
    updateObj['_id'] = roadmapId;
    updateObj['title'] = newProperty;
    Server.updateRoadmap(updateObj)
      .then(function(node) {
      $scope.hideTitle = false;
      $scope.roadMapTitle = newProperty;
    })
      .catch(function(){
        console.log('problem updating map title', err);
      });
  }

  $scope.showDescEditor = function (boolean){
    var username = localStorage.getItem('user.username');
    var roadmapAuthor = $scope.currentRoadMapData.author.username;
    var storedDesc;

    if( username !== roadmapAuthor ){
      $scope.hideDesc= false;
    } else {
      $scope.hideDesc = boolean;
      return $scope.hideDesc;
    }

  };

  $scope.saveDescEdit = function (){
    console.log('clicked saveDescEdit');
    var newProperty = $('#main-desc').val();
    var updateObj = {};
    updateObj['_id'] = roadmapId;
    updateObj['description'] = newProperty;
    console.log('new desc', newProperty);
    Server.updateRoadmap(updateObj)
      .then(function(node) {
      $scope.hideDesc = false;
      $scope.roadMapDesc = newProperty;
    })
      .catch(function(){
        console.log('problem updating map description', err);
      });
  }

 // Get the current number of upvotes from current map
 $scope.getCountVotes = function(votes){
    $scope.votesCount = 0;
    for(var i = 0; i < votes.length; i++){
      $scope.votesCount++;
    }
    return $scope.votesCount;
 }

 // Renders the nodes for the current roadmap to the page
  $scope.renderNodes = function(){
    var title = $scope.currentRoadMapData.title || 'test title';
    var nodes = $scope.currentRoadMapData.nodes || ['testnode1', 'testnode2'];
    var desc =  $scope.currentRoadMapData.description || 'default roadmap description - click to edit!';
    // Add an index to nodes to make ng-clicking easier
    nodes.map(function(node,index){
      node.index = index;
    });

    $scope.renderedNodes = nodes;
    $scope.roadMapTitle = title;
    $scope.roadMapDesc = desc;

    // User Logged in Data in the future
    // Some variable that holds that the user is logged in
    $scope.currentNode = nodes[0];
    $scope.renderCurrentNode();
  };
  // Make a $scope.renderComments()
  $scope.renderComments = function(){
    var comments = $scope.currentRoadMapData.comments;
    console.log(comments);
    comments.map(function(comment,index){
      comment.index = index;
    })
    $scope.renderedComments = comments;
  }

  // When roadmap (identified by its id) data is fetched, set it
  function populateData (stop){
    stop = stop || false;
    Server.getRoadmapById(roadmapId).then(function (res){
      if( !res.nodes.length && stop === false){
        populateData(true);
      }
      $scope.currentRoadMapData = res;
      console.log($scope.currentRoadMapData,'I am the roadmap');
    }, function(err){
      if (err) return console.log(err);
    })
    .then(function(){
      $scope.renderNodes();
      $scope.renderComments();
      // Set the upvotes and downvotes
      var currentMapUpVotes = $scope.currentRoadMapData.upvotes;
      var currentMapDownVotes = $scope.currentRoadMapData.downvotes;
      $scope.upVoteCount = $scope.getCountVotes(currentMapUpVotes);
      $scope.downVoteCount = $scope.getCountVotes(currentMapDownVotes);

      // append Editor Mode message
      var username = localStorage.getItem('user.username');
      var roadmapAuthor = $scope.currentRoadMapData.author.username;

      if( username === roadmapAuthor ){
        $('#editor-placeholder').append(
        '
' +
          '
' +
            '' +
          '
' +
          '
' +
              'Since you created this roadmap, you can add or edit properties by clicking on them.' +
          '
' +
          '
' +
            '' +
          '
' +
        '
'
        );
      }
    });
  }

  populateData();

  // Render Title
  // Assumes title links and description properties from get method
  $scope.renderCurrentNode = function(){
    // For now lets make $scope.loggedIn be false, if logged in we can change it to true later.
    $scope.loggedin = false;
    if($scope.loggedIn) {
      // Get node index
      // set currentNode into node at that index;
    } else {
      //links from a node
      var links = $scope.renderedNodes[0].resourceURL;
      //description of a node
      var description = $scope.renderedNodes[0].description;
      var title = $scope.renderedNodes[0].title;
    }

    $scope.currentTitle = title;
    $scope.currentLinks = [links];
    $scope.currentDescription = description;
  }

  $scope.selectNode = function($index) {

    var links = $scope.renderedNodes[$index].resourceURL;
    var description = $scope.renderedNodes[$index].description;
    var title = $scope.renderedNodes[$index].title;

    $scope.currentIndex = $index;
    $scope.currentTitle = title;
    $scope.currentLinks = links;
    $scope.currentResourceURL = $scope.currentLinks[0];
    $scope.currentDescription = description;
    $scope.currentNode = $scope.renderedNodes[$index];

  };
  // Submits a node to the user's inProgress.nodes array.
  $scope.submitCompletedNode = function() {
    var nodeId = $scope.currentNode._id;
    User.completeNodeById(nodeId);
    Materialize.toast('Node Complete!', 4000, 'orangeToast');
  }

  // Submits a roadmap to the user's completedRoadmaps array.
  $scope.submitCompletedRoadmap = function() {
    Materialize.toast('Map Complete!', 4000, 'orangeToast');
    User.completeRoadmapById(roadmapId);
    $state.go('home.dashboard', {type: 'completed'});
  }

  // After upvote, submits vote update to the roadmap's upvotes and downvotes array
  $scope.upVoteMap = function () {
    User.upvoteMapById(roadmapId)
    .then(function(data){
      var dataUpVoteCount = data.upvotes;
      var dataDownVoteCount = data.downvotes;
      // Update the upvote count
      $scope.upVoteCount = $scope.getCountVotes(dataUpVoteCount);
      // Update the downvote count
      $scope.downVoteCount = $scope.getCountVotes(dataDownVoteCount);
    })
  }

  // After downvote, submits vote update to the roadmap's upvotes and downvotes array
  $scope.downVoteMap = function () {
    User.downvoteMapById(roadmapId)
    .then(function(data){
      var dataUpVoteCount = data.upvotes;
      var dataDownVoteCount = data.downvotes;
      // Update the upvote count
      $scope.upVoteCount = $scope.getCountVotes(dataUpVoteCount);
      // Update the downvote count
      $scope.downVoteCount = $scope.getCountVotes(dataDownVoteCount);
    });
  };

  $scope.connectLines = function(){
    $('.endPointForConnection').connections();
  };

  // We need async because ng-repeat creates the nodes before this function runs set timeout changes the loop.
  $scope.asyncConnectLines = function(cb){
    setTimeout($scope.connectLines,0);
  };

  $scope.subject = '';
  $scope.content = '';

  $scope.postComment = function(){
    // Will probably need to refactor
    $scope.currentRoadMapData.comments = $scope.currentRoadMapData.comments || [];

    Server.createComment({
      subject: $scope.subject,
      content: $scope.content,
      roadmap: $scope.currentRoadMapData._id
    });
  };

}]);


text:
package io.fabric8.quickstarts.activemq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.SimpleMessageListenerContainer;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.util.FileSystemUtils;

import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.io.File;

@Configuration
@EnableAutoConfiguration
public class App {

    private static String destination = "QuickStarts.ActiveMQ.Spring.Boot";

    @Bean
    Receiver receiver() {
        return new Receiver();
    }

    @Bean
    MessageListenerAdapter adapter(Receiver receiver) {
        MessageListenerAdapter messageListener = new MessageListenerAdapter(receiver);
        messageListener.setDefaultListenerMethod("receiveMessage");
        return messageListener;
    }

    @Bean
    SimpleMessageListenerContainer container(MessageListenerAdapter messageListener,
                                             ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setMessageListener(messageListener);
        container.setConnectionFactory(connectionFactory);
        container.setDestinationName(destination);
        return container;
    }

    public static void main(String[] args) {
        // Clean out any ActiveMQ data from a previous run
        FileSystemUtils.deleteRecursively(new File("activemq-data"));

        // Launch the application
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);

        // Send a message
        MessageCreator messageCreator = new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage("<hello>world!</hello>");
            }
        };
        JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
        System.out.println("Sending a new message.");
        jmsTemplate.send(destination, messageCreator);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.davidbracewell.hermes;

import com.davidbracewell.config.Config;
import com.davidbracewell.hermes.corpus.Corpus;
import com.davidbracewell.hermes.corpus.CorpusFormats;
import com.davidbracewell.io.Resources;

import static com.davidbracewell.hermes.Types.*;

/**
 * @author David B. Bracewell
 */
public class OpenNLPExample {

   public static void main(String[] args) throws Exception {
      //Initializes configuration settings
      Hermes.initializeApplication(args);

      //Lets us the OpenNLP models instead of Herme's
      //Load the OpenNLP English defaults (May need to edit this file or override to point to your models)
      Config.loadConfig(Resources.fromClasspath("com/davidbracewell/hermes/opennlp/opennlp-english.conf"));

      //Create a prefix where the models are stored
      //The directory structure can be seen by looking in hermes-opennlp/src/main/resources/com/davidbracewell/hermes/opennlp/opennlp-english.conf
      Config.setProperty("data.cp", "/shared/data/models"); //This is the root

      Corpus corpus = Corpus.builder()
                            .format(CorpusFormats.PLAIN_TEXT_OPL)
                            .source(Resources.fromClasspath("com/davidbracewell/hermes/example_docs.txt"))
                            .build()
                            .annotate(TOKEN, SENTENCE, PART_OF_SPEECH, ENTITY);

      corpus.forEach(document -> document.sentences().forEach(sentence -> System.out.println(sentence.toPOSString())));

      //Write the corpus to a resource in one json per line format (the resource just prints to standard out)
      //The thing to check out is the "completed" section, which shows the annotations that have been completed on
      //the document and a description of the provider (should be OpenNLPxxxAnnotator!)
      corpus.write(Resources.fromStdout());

      //Other libraries (e.g. Stanford's CoreNLP, ClearNLP, Gate, etc.) can be wrapped and used as the default annotators.

   }

}//END OF Sandbox


text:
No roundtrip selected

Please select one!


text:
import contextlib
from decimal import Decimal
import importlib
import unittest

from dependency_injector.wiring import (
    wire,
    Provide,
    Provider,
    Closing,
    register_loader_containers,
    unregister_loader_containers,
)
from dependency_injector import containers, providers, errors

# Runtime import to avoid syntax errors in samples on Python < 3.5
import os
_TOP_DIR = os.path.abspath(
    os.path.sep.join((
        os.path.dirname(__file__),
        '../',
    )),
)
_SAMPLES_DIR = os.path.abspath(
    os.path.sep.join((
        os.path.dirname(__file__),
        '../samples/',
    )),
)
import sys
sys.path.append(_TOP_DIR)
sys.path.append(_SAMPLES_DIR)

from asyncutils import AsyncTestCase

from wiringstringidssamples import module, package
from wiringstringidssamples.service import Service
from wiringstringidssamples.container import Container, SubContainer

class WiringTest(unittest.TestCase):

    container: Container

    def setUp(self) -> None:
        self.container = Container(config={'a': {'b': {'c': 10}}})
        self.container.wire(
            modules=[module],
            packages=[package],
        )
        self.addCleanup(self.container.unwire)

    def test_package_lookup(self):
        from wiringstringidssamples.package import test_package_function
        service = test_package_function()
        self.assertIsInstance(service, Service)

    def test_package_subpackage_lookup(self):
        from wiringstringidssamples.package.subpackage import test_package_function
        service = test_package_function()
        self.assertIsInstance(service, Service)

    def test_package_submodule_lookup(self):
        from wiringstringidssamples.package.subpackage.submodule import test_function
        service = test_function()
        self.assertIsInstance(service, Service)

    def test_module_attributes_wiring(self):
        self.assertIsInstance(module.service, Service)
        self.assertIsInstance(module.service_provider(), Service)
        self.assertIsInstance(module.undefined, Provide)

    def test_class_wiring(self):
        test_class_object = module.TestClass()
        self.assertIsInstance(test_class_object.service, Service)

    def test_class_wiring_context_arg(self):
        test_service = self.container.service()

        test_class_object = module.TestClass(service=test_service)
        self.assertIs(test_class_object.service, test_service)

    def test_class_method_wiring(self):
        test_class_object = module.TestClass()
        service = test_class_object.method()
        self.assertIsInstance(service, Service)

    def test_class_classmethod_wiring(self):
        service = module.TestClass.class_method()
        self.assertIsInstance(service, Service)

    def test_instance_classmethod_wiring(self):
        instance = module.TestClass()
        service = instance.class_method()
        self.assertIsInstance(service, Service)

    def test_class_staticmethod_wiring(self):
        service = module.TestClass.static_method()
        self.assertIsInstance(service, Service)

    def test_instance_staticmethod_wiring(self):
        instance = module.TestClass()
        service = instance.static_method()
        self.assertIsInstance(service, Service)

    def test_class_attribute_wiring(self):
        self.assertIsInstance(module.TestClass.service, Service)
        self.assertIsInstance(module.TestClass.service_provider(), Service)
        self.assertIsInstance(module.TestClass.undefined, Provide)

    def test_function_wiring(self):
        service = module.test_function()
        self.assertIsInstance(service, Service)

    def test_function_wiring_context_arg(self):
        test_service = self.container.service()

        service = module.test_function(service=test_service)
        self.assertIs(service, test_service)

    def test_function_wiring_provider(self):
        service = module.test_function_provider()
        self.assertIsInstance(service, Service)

    def test_function_wiring_provider_context_arg(self):
        test_service = self.container.service()

        service = module.test_function_provider(service_provider=lambda: test_service)
        self.assertIs(service, test_service)

    def test_configuration_option(self):
        (
            value_int,
            value_float,
            value_str,
            value_decimal,
            value_required,
            value_required_int,
            value_required_float,
            value_required_str,
            value_required_decimal,
        ) = module.test_config_value()

        self.assertEqual(value_int, 10)
        self.assertEqual(value_float, 10.0)
        self.assertEqual(value_str, '10')
        self.assertEqual(value_decimal, Decimal(10))
        self.assertEqual(value_required, 10)
        self.assertEqual(value_required_int, 10)
        self.assertEqual(value_required_float, 10.0)
        self.assertEqual(value_required_str, '10')
        self.assertEqual(value_required_decimal, Decimal(10))

    def test_configuration_option_required_undefined(self):
        self.container.config.reset_override()
        with self.assertRaisesRegex(errors.Error, 'Undefined configuration option "config.a.b.c"'):
            module.test_config_value_required_undefined()

    def test_provide_provider(self):
        service = module.test_provide_provider()
        self.assertIsInstance(service, Service)

    def test_provided_instance(self):
        class TestService:
            foo = {
                'bar': lambda: 10,
            }

        with self.container.service.override(TestService()):
            some_value = module.test_provided_instance()
        self.assertEqual(some_value, 10)

    def test_subcontainer(self):
        some_value = module.test_subcontainer_provider()
        self.assertEqual(some_value, 1)

    def test_config_invariant(self):
        config = {
            'option': {
                'a': 1,
                'b': 2,
            },
            'switch': 'a',
        }
        self.container.config.from_dict(config)

        value_default = module.test_config_invariant()
        self.assertEqual(value_default, 1)

        with self.container.config.switch.override('a'):
            value_a = module.test_config_invariant()
        self.assertEqual(value_a, 1)

        with self.container.config.switch.override('b'):
            value_b = module.test_config_invariant()
        self.assertEqual(value_b, 2)

    def test_wire_with_class_error(self):
        with self.assertRaises(Exception):
            wire(
                container=Container,
                modules=[module],
            )

    def test_unwire_function(self):
        self.container.unwire()
        self.assertIsInstance(module.test_function(), Provide)

    def test_unwire_class(self):
        self.container.unwire()
        test_class_object = module.TestClass()
        self.assertIsInstance(test_class_object.service, Provide)

    def test_unwire_class_method(self):
        self.container.unwire()
        test_class_object = module.TestClass()
        self.assertIsInstance(test_class_object.method(), Provide)

    def test_unwire_package_function(self):
        self.container.unwire()
        from wiringstringidssamples.package.subpackage.submodule import test_function
        self.assertIsInstance(test_function(), Provide)

    def test_unwire_package_function_by_reference(self):
        from wiringstringidssamples.package.subpackage import submodule
        self.container.unwire()
        self.assertIsInstance(submodule.test_function(), Provide)

    def test_unwire_module_attributes(self):
        self.container.unwire()
        self.assertIsInstance(module.service, Provide)
        self.assertIsInstance(module.service_provider, Provider)
        self.assertIsInstance(module.undefined, Provide)

    def test_unwire_class_attributes(self):
        self.container.unwire()
        self.assertIsInstance(module.TestClass.service, Provide)
        self.assertIsInstance(module.TestClass.service_provider, Provider)
        self.assertIsInstance(module.TestClass.undefined, Provide)

    def test_wire_multiple_containers(self):
        sub_container = SubContainer()
        sub_container.wire(
            modules=[module],
            packages=[package],
        )
        self.addCleanup(sub_container.unwire)

        service, some_value = module.test_provide_from_different_containers()

        self.assertIsInstance(service, Service)
        self.assertEqual(some_value, 1)

    def test_closing_resource(self):
        from wiringstringidssamples import resourceclosing

        resourceclosing.Service.reset_counter()

        container = resourceclosing.Container()
        container.wire(modules=[resourceclosing])
        self.addCleanup(container.unwire)

        result_1 = resourceclosing.test_function()
        self.assertIsInstance(result_1, resourceclosing.Service)
        self.assertEqual(result_1.init_counter, 1)
        self.assertEqual(result_1.shutdown_counter, 1)

        result_2 = resourceclosing.test_function()
        self.assertIsInstance(result_2, resourceclosing.Service)
        self.assertEqual(result_2.init_counter, 2)
        self.assertEqual(result_2.shutdown_counter, 2)

        self.assertIsNot(result_1, result_2)

    def test_closing_resource_context(self):
        from wiringstringidssamples import resourceclosing

        resourceclosing.Service.reset_counter()
        service = resourceclosing.Service()

        container = resourceclosing.Container()
        container.wire(modules=[resourceclosing])
        self.addCleanup(container.unwire)

        result_1 = resourceclosing.test_function(service=service)
        self.assertIs(result_1, service)
        self.assertEqual(result_1.init_counter, 0)
        self.assertEqual(result_1.shutdown_counter, 0)

        result_2 = resourceclosing.test_function(service=service)
        self.assertIs(result_2, service)
        self.assertEqual(result_2.init_counter, 0)
        self.assertEqual(result_2.shutdown_counter, 0)

    def test_class_decorator(self):
        service = module.test_class_decorator()
        self.assertIsInstance(service, Service)

    def test_container(self):
        service = module.test_container()
        self.assertIsInstance(service, Service)

class WiringAndFastAPITest(unittest.TestCase):

    container: Container

    def test_bypass_marker_injection(self):
        container = Container()
        container.wire(modules=[module])
        self.addCleanup(container.unwire)

        service = module.test_function(service=Provide[Container.service])
        self.assertIsInstance(service, Service)

    def test_closing_resource_bypass_marker_injection(self):
        from wiringstringidssamples import resourceclosing

        resourceclosing.Service.reset_counter()

        container = resourceclosing.Container()
        container.wire(modules=[resourceclosing])
        self.addCleanup(container.unwire)

        result_1 = resourceclosing.test_function(
            service=Closing[Provide[resourceclosing.Container.service]],
        )
        self.assertIsInstance(result_1, resourceclosing.Service)
        self.assertEqual(result_1.init_counter, 1)
        self.assertEqual(result_1.shutdown_counter, 1)

        result_2 = resourceclosing.test_function(
            service=Closing[Provide[resourceclosing.Container.service]],
        )
        self.assertIsInstance(result_2, resourceclosing.Service)
        self.assertEqual(result_2.init_counter, 2)
        self.assertEqual(result_2.shutdown_counter, 2)

        self.assertIsNot(result_1, result_2)

class WireDynamicContainerTest(unittest.TestCase):

    def test_wire(self):
        sub = containers.DynamicContainer()
        sub.int_object = providers.Object(1)

        container = containers.DynamicContainer()
        container.config = providers.Configuration()
        container.service = providers.Factory(Service)
        container.sub = sub

        container.wire(
            modules=[module],
            packages=[package],
        )
        self.addCleanup(container.unwire)

        service = module.test_function()
        self.assertIsInstance(service, Service)

class WiringAsyncInjectionsTest(AsyncTestCase):

    def test_async_injections(self):
        from wiringstringidssamples import asyncinjections

        container = asyncinjections.Container()
        container.wire(modules=[asyncinjections])
        self.addCleanup(container.unwire)

        asyncinjections.resource1.reset_counters()
        asyncinjections.resource2.reset_counters()

        resource1, resource2 = self._run(asyncinjections.async_injection())

        self.assertIs(resource1, asyncinjections.resource1)
        self.assertEqual(asyncinjections.resource1.init_counter, 1)
        self.assertEqual(asyncinjections.resource1.shutdown_counter, 0)

        self.assertIs(resource2, asyncinjections.resource2)
        self.assertEqual(asyncinjections.resource2.init_counter, 1)
        self.assertEqual(asyncinjections.resource2.shutdown_counter, 0)

    def test_async_injections_with_closing(self):
        from wiringstringidssamples import asyncinjections

        container = asyncinjections.Container()
        container.wire(modules=[asyncinjections])
        self.addCleanup(container.unwire)

        asyncinjections.resource1.reset_counters()
        asyncinjections.resource2.reset_counters()

        resource1, resource2 = self._run(asyncinjections.async_injection_with_closing())

        self.assertIs(resource1, asyncinjections.resource1)
        self.assertEqual(asyncinjections.resource1.init_counter, 1)
        self.assertEqual(asyncinjections.resource1.shutdown_counter, 1)

        self.assertIs(resource2, asyncinjections.resource2)
        self.assertEqual(asyncinjections.resource2.init_counter, 1)
        self.assertEqual(asyncinjections.resource2.shutdown_counter, 1)

        resource1, resource2 = self._run(asyncinjections.async_injection_with_closing())

        self.assertIs(resource1, asyncinjections.resource1)
        self.assertEqual(asyncinjections.resource1.init_counter, 2)
        self.assertEqual(asyncinjections.resource1.shutdown_counter, 2)

        self.assertIs(resource2, asyncinjections.resource2)
        self.assertEqual(asyncinjections.resource2.init_counter, 2)
        self.assertEqual(asyncinjections.resource2.shutdown_counter, 2)

class AutoLoaderTest(unittest.TestCase):

    container: Container

    def setUp(self) -> None:
        self.container = Container(config={'a': {'b': {'c': 10}}})
        importlib.reload(module)

    def tearDown(self) -> None:
        with contextlib.suppress(ValueError):
            unregister_loader_containers(self.container)

        self.container.unwire()

    @classmethod
    def tearDownClass(cls) -> None:
        importlib.reload(module)

    def test_register_container(self):
        register_loader_containers(self.container)
        importlib.reload(module)

        service = module.test_function()
        self.assertIsInstance(service, Service)


text:
(function() {
  var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  define(function() {
    var View;
    return View = (function() {
      function View(model) {
        this.model = model;
        if (typeof model.on === "function") {
          model.on('update', __bind(function() {
            return this.render();
          }, this));
        }
        this.el = document.createElement(this.getTagName());
        this.render();
      }
      View.prototype.getTagName = function() {
        return 'div';
      };
      if (typeof $ !== "undefined" && $ !== null) {
        View.prototype.$ = function() {
          return $(this.el);
        };
      }
      View.prototype.appendTo = function(el) {
        return el.appendChild(this.el);
      };
      View.prototype.prependTo = function(el) {
        return el.prependChild(this.el);
      };
      View.prototype.render = function() {
        var data;
        data = this.model;
        return this.el.innerHTML = this.partial(data);
      };
      View.prototype.partial = function(data) {
        return '
This is a default partial
';
      };
      return View;
    })();
  });
}).call(this);


text:
from flask import Flask
from flask import render_template
from collections import namedtuple
from os import listdir
from os.path import isfile
from os.path import isdir
from flask_compress import Compress
compress = Compress()
def start_app():
    app = Flask(__name__)
    compress.init_app(app)
    return app

app = start_app()

Photo = namedtuple('Photo', ['name', 'src', 'index', 'page'])
albums = [[], [], [], []]
album_names = ['30週年慶相簿', '各實驗室懷舊相簿', '歷年相片合輯']

@app.route("/")
@app.route("/index")
def index():
    """index page"""
    img_loc = "../static/img/photos/"

    photos = [(img_loc+'p'+str(index)+'.jpg') for index in range(1, 7)]
    return render_template('index.html', tabName="清大資工40週年慶 - 首頁 NTHU CS 40 Anniversary", photos=photos, index=True)

@app.route("/activity")
def activity():
    return render_template('activity.html', tabName="系列活動", title="系列活動",  subtitle="心動即行動")

@app.route("/news")
def news():
    return render_template('news.html', tabName="最新消息", title="最新消息", subtitle="開放報名中")

@app.route('/post/<int:post_id>', methods=['GET', 'POST'])
@app.route('/post/', methods=['GET', 'POST'])
def show_post(post_id=1):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route("/album/", methods=['GET', 'POST'])
@app.route("/album/<int:album_id>&<int:page_id>")
def album(album_id = 1, page_id = 1):
    """ show the album page"""
    if album_id > 0:
        album_id -= 1
    else:
        album_id = 0

    if page_id > 0:
        page_id -= 1
    else:
        page_id = 0

    print("album: " + str(album_id) + " page: " + str(page_id))

    dir = './static/img/photos/album' + str(album_id) + '/'

    if len(albums[album_id]) == 0:
        albums[album_id] = getPhotos(dir)

    if len(albums[album_id]) % 40 == 0:
        pages_count = int(len(albums[album_id]) / 40)
    else:
        pages_count = int(len(albums[album_id]) / 40) + 1

    photos = albums[album_id][page_id*40 : (page_id+1)*40]

    print(str(page_id*40) + ", " + str((page_id+1)*40))
    #print(photos)

    return render_template('album.html', tabName="相簿", title="光陰集錦", subtitle="系慶相簿", \
                            album_id = album_id + 1, page_id = page_id + 1, photos=photos, pages_count = pages_count, albumName = album_names[album_id])

@app.route("/voting")
def voting():
    return render_template('voting.html', tabName="人氣王競賽", title="人氣王競賽", subtitle="拍照上傳FB")

@app.route("/history")
def history():
    return render_template('history.html', tabName="歷史沿革", title="", subtitle="")

@app.route("/celebrity")
def celebrity():
    return render_template('celebrity.html', tabName="風雲人物", title="風雲人物",  subtitle="傑出校友獎")

@app.route("/drive")
def drive():
    return render_template('googleDriveApi.html', tabName="google測試", title="",  subtitle="")

@app.route("/yearPhotos")
def yearPhotos():
    return render_template('yearPhotos.html', tabName='歷年系慶合照', title="歷年系慶合照",  subtitle="")

@app.route("/layout")
def layout():
    return render_template('layout.html', tabName="layout", title="layout", subtitle="subtitle", description="this is a small description")

def getPhotos(dir, photo_count = 0):
    """ GET PHOTOS recursively """
    if isfile(dir):
        return ['.' + dir]

    files = listdir(dir)
    photos = []
    page_photo_count = 40
    for photo in files:
        if isfile(dir+photo):
            if photo.endswith('.MOV') or photo.endswith('.db'):
                continue
            photos.append(Photo(photo, '.' + dir + photo, photo_count, photo_count/page_photo_count))
            photo_count += 1
        else:
            photos_tmp = getPhotos(dir + photo + '/', photo_count)
            photos.extend(photos_tmp)
            photo_count += len(photos_tmp)

    return photos

if __name__ == "__main__":
	app.run(host="0.0.0.0", port=5000, debug=True)


text: NGINX in Docker using Phusion's Baseimage.


text:
package localhost.steven.chemicalengineerhelper;

import android.util.TypedValue;
import android.os.Bundle;
import android.widget.TextView;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.view.View.OnClickListener;

public class MainPage extends AppCompatActivity {

    TypedValue outValue;
    OnClickListener bOpen;

    public native String stringFromJNI();

    //public native double convertToSI();

    static {
        System.loadLibrary("native-lib");

    }
    public String[] buttonText={"Unit Converter", "Internal Diameter Calculator (NPS)",
            "Density","Vapor Density","Reynolds Number (Diameter)",//0 to 2
            "Pipe Pressure Drop Incompressible (Darcy-Weisbach)","Pipe Pressure Drop Compressible (Darcy-Weisbach)",
            };
    //public final static String EXTRA_MESSAGE="PocketEngineer.Message";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);

        RelativeLayout relativeLayout=(RelativeLayout) findViewById(R.id.mainscreen);

        //global button settings
        TextView textView = new TextView(this);
        //textView.setText(Double.toString(convertToSI()));
        relativeLayout.addView(textView);

        //background attr
            outValue = new TypedValue();
            this.getTheme().resolveAttribute(android.R.attr.selectableItemBackground,outValue,true);
        //Open calc side window
            bOpen = new OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                openCalc(v);
                            }

                        };

        for(int buttonInit=0;buttonInit<buttonText.length;buttonInit++){
            Button thisButton=new Button(this);
            thisButton.setText(buttonText[buttonInit]);
            setupButton(thisButton,buttonInit);
            thisButton.setId(buttonInit);

            relativeLayout.addView(thisButton);
        }

    }

    //Calculation result page
    public void openCalc(View view){
        Intent intent=new Intent(MainPage.this,CalculateScreen.class);
        intent.putExtra("UniqueId","BID:"+Integer.toString(view.getId()));
        startActivity(intent);

    }

    public double eTxtToDbl(EditText eText){
        return Double.parseDouble(eText.getText().toString());

    }

    //Initiate button parameters
    public void setupButton(Button button, int position){

        //layout
        RelativeLayout.LayoutParams mpButtonParams;
        mpButtonParams =
                new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);

        mpButtonParams.setMargins(0,position*150,0,0);

        button.setLayoutParams(mpButtonParams);
        button.setBackgroundResource(outValue.resourceId);
        button.setOnClickListener(bOpen);
    }

}


text:
import requests, time

TOKEN = 'EAACEdEose0cBAOThXLZAVZBD98CaNdC8YOP9TImQP5YEWDTOwbPjgHB3vwwS5I4Elhj6ft9TRttAZCsWZCeUmSJsfFHtEn7MDZAXuoSr2x6SLIWSNbOTtZADRJpjXLhOz8LAlYnF4CnXjxwEgXZBs8N3B7ioM5LUPmXrFklmqVupwZDZD'

def getPosts():
    file = open('upposts.txt', 'r')
    upposts = []
    for line in file:
        line = line.rstrip()
        upposts.append(line)
    file.close()
    return upposts

def uping(upposts):
    # uplar all the postlari in da upposts.txt file

    for uppost in upposts:
        url = 'https://graph.facebook.com/%s/comments' % uppost
        message = 'up'
        payload = {'access_token': TOKEN, 'message': message}
        s = requests.post(url, data=payload)

        print "Wall post %s done" % uppost

if __name__ == '__main__':
    runNum = 3
    for i in range(runNum):
        uping(getPosts())
        time.sleep(60*100)


text:
/**
 *
 */
package com.fuhj.itower.ui.vm;

import java.util.List;
import java.util.Set;

import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Space;

import com.fuhj.itower.model.ITCity;
import com.fuhj.itower.model.ITProvince;
import com.fuhj.itower.service.LocationService;
import com.fuhj.itower.service.LoginService;
import com.fuhj.itower.service.model.Users;
import com.fuhj.log.AppLogger;
import com.fuhj.util.SpringUtil;
import com.fuhj.util.WebAppUtil;

/**
 * @Description: TODO
 * @author fu
 * @date 2016-3-31
 */
public class PermVM {
	private Component view;
	private LoginService loginService;
	private LocationService locationService;
	@Wire Listbox queryRangeLbx;
	Users currentUser = WebAppUtil.getSessionUser();

	@AfterCompose public void afterCompose(@ContextParam(ContextType.VIEW) Component view) {
		Selectors.wireComponents(view, this, false);
		Selectors.wireEventListeners(view, this);
		this.view = view;
		loginService = SpringUtil.getBean(LoginService.class);
		locationService = SpringUtil.getBean(LocationService.class);
		queryRangeLbxInit();
	}

	public void queryRangeLbxInit() {
		ITProvince itp = locationService.getProvinceById("0001928");
		List<ITCity> citys = locationService.findAllCityByProvinceId(itp.getItProvinceId());
		queryRangeLbx.setItemRenderer(new ListitemRenderer<ITCity>() {

			@Override public void render(Listitem item, ITCity data, int index) throws Exception {
				Listcell cell = new Listcell();
				Space sp = new Space();
				sp.setHeight("3px");
				cell.appendChild(sp);
				cell.appendChild(new Label(data.getCname()));
				item.appendChild(cell);
				if (currentUser.getPerm().contains(data.getItCityId())) {
					item.setSelected(true);
				}
				item.setValue(data);
			}
		});
		queryRangeLbx.setModel(new SimpleListModel<ITCity>(citys));
		queryRangeLbx.setCheckmark(true);
		queryRangeLbx.setMultiple(true);
	}

	@Command public void save() {
		Set<Listitem> set = queryRangeLbx.getSelectedItems();
		if (set.size() == 0) {
			Messagebox.show("请至少选择一项进行保存!", "提示", Messagebox.OK, Messagebox.EXCLAMATION);
			return;
		}
		StringBuffer permSB = new StringBuffer();
		for (Listitem listitem : set) {
			ITCity city = listitem.getValue();
			permSB.append(city.getItCityId()).append(",");
		}
		permSB.deleteCharAt(permSB.length() - 1);
		String perm = permSB.toString();
		AppLogger.sysDebug("save perm:" + perm);
		loginService.modifyUserPerm(currentUser.getId(), perm);
		currentUser.setPerm(perm);
		Messagebox.show("保存成功!", "成功", Messagebox.OK, Messagebox.INFORMATION);
	}
}


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

{% block meta_title %}{{ object.title }}{% endblock %}
{% block title %}
{{ object.title }}
({{ object.domain }})
{% endblock %}
{% load comments %}

{% block main %}

						<form method="post" action="{% url 'vote' %}">

						{% csrf_token %}
						<input type="hidden" id="id_link" name="link" class="hidden_id" value="{{ link.pk }}" />
						<input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
					<input id="id_object_pk" name="object_pk" type="hidden" value="11903" />

<input id="id_value_0" name="value" type="radio" value="-1" /> -1

<input id="id_value_1" name="value" type="radio" value="1" /> 1

						</form>

							{{ link.votes }}

       by {{ link.submitter }}
        {{  link.submitted_on|timesince  }} ago

Comments

{% if user.is_authenticated %}
  {% get_comment_form for object as form %}
  <form action="{% comment_form_target %}" method="POST">
    {% csrf_token %}
    {{ form.comment }}

    {{ form.content_type }}
    {{ form.object_pk }}
    {{ form.timestamp }}
    {{ form.security_hash }}
    <input type="hidden" name="name" value="{{ user }}" />
    <input type="hidden" name="email" value="{{ user.email|default:'d@ummy.com' }}" />
    <input type="hidden" name="url" value="" />
    <input type="hidden" name="next"
	   value="{% url 'link_detail' pk=object.id %}" />

    <input class="btn btn-warning btn-large" id="id_submit" type="submit" value="Add comment">

  </form>
{% else %}

Please log in
   to leave a comment.

{% endif %}

  {% render_comment_list for object %}

{% endblock %}


text:
<!doctype html>

  <title>Julie's</title>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <meta charset="utf-8">

  <link rel="import" href="bower_components/polymer/polymer.html">

  <link rel="import" href="bower_components/core-icons/core-icons.html">
  <link rel="import" href="bower_components/core-icon/core-icon.html">

  <link rel="import" href="bower_components/core-toolbar/core-toolbar.html">
  <link rel="import" href="bower_components/paper-tabs/paper-tabs.html">

  <link rel="import" href="bower_components/core-animated-pages/core-animated-pages.html">
  <link rel="import" href="bower_components/core-animated-pages/transitions/hero-transition.html">
  <link rel="import" href="bower_components/core-animated-pages/transitions/cross-fade.html">

  <link rel="import" href="bower_components/img-fixheight/img-fixheight.html">

  <link rel="import" href="bower_components/more-routing/more-routing.html">
  <link rel="import" href="bower_components/core-ajax/core-ajax.html">

  <link rel="import" href="src/elements/core-scroll-header-panel-shadow.html">

  <link rel="import" href="src/routes.html">
  <link rel="import" href="src/category-index.html">
  <link rel="import" href="src/category-paintings.html">

  <template is="auto-binding">
  <core-ajax auto url="api/json/v1/all.json" handleAs="json" response="{{data}}"></core-ajax>
  <core-scroll-header-panel-shadow id="mainscroll" flex condenses keepCondensedHeader forceCondensed?={{routepath!="/"}}
                                   class="{{ {'noscroll-transition': hideScrollbarTransition} | tokenList}}"
                                   headerHeight="560" condensedHeaderHeight="64">
    <core-toolbar>

Julie Tolomelli

        <more-route-selector>
          <paper-tabs scrol-active link>
            <paper-tab route="home">
              Travaux
            </paper-tab>
            <paper-tab route="about">
              L'artiste
            </paper-tab>
            <paper-tab route="blog">
              Blog
            </paper-tab>
            <paper-tab route="contact">
              Contact
            </paper-tab>
          </paper-tabs>
        </more-route-selector>
        <core-icon scrol-active icon="search" self-center></core-icon>

    </core-toolbar>

    <more-route-selector id="router" selectedPath={{routepath}}>
      <core-animated-pages class="content" transitions="hero-transition cross-fade-all"
                           on-core-animated-pages-transition-prepare="{{transitionstart}}"
                           on-core-animated-pages-transition-end="{{transitionend}}">
        <category-index data={{data}}></category-index>
        <category-paintings data={{data}}></category-paintings>

      </core-animated-pages>
    </more-route-selector>

  </core-scroll-header-panel-shadow>
  </template>


text:
using OmniXaml.TypeConversion;
using System;
using System.Globalization;

namespace Avalonia.Markup.Xaml.Converters
{
    public class DateTimeTypeConverter : ITypeConverter
    {
        public object ConvertFrom(IValueContext context, CultureInfo culture, object value)
        {
            if (culture == null)
            {
                throw new ArgumentNullException("culture");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            DateTimeFormatInfo dateTimeFormatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo));
            DateTime d = DateTime.ParseExact(value.ToString(), dateTimeFormatInfo.ShortDatePattern, culture);
            return d;
        }

        public object ConvertTo(IValueContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException("destinationType");
            }

            if (culture == null)
            {
                throw new ArgumentNullException("culture");
            }

            DateTime? d = value as DateTime?;

            if (!d.HasValue || destinationType != typeof(string))
            {
                throw new NotSupportedException();
            }
            DateTimeFormatInfo dateTimeFormatInfo = (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo));
            return d.Value.ToString(dateTimeFormatInfo.ShortDatePattern, culture);
        }

        public bool CanConvertTo(IValueContext context, Type destinationType)
        {
            return destinationType == typeof(string);
        }

        public bool CanConvertFrom(IValueContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }
    }
}


text:
package org.springframework.security.samples.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.springframework.security.samples.pages.AddPage.AddForm;

import java.util.List;
import java.util.function.Predicate;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * The contacts / manage page.
 *
 * @author Michael Simons
 */
public class ContactsPage {
	public static LoginPage accessManagePageWithUnauthenticatedUser(WebDriver driver, int port) {
		driver.get("http://localhost:" + port +"/secure/");
		return PageFactory.initElements(driver, LoginPage.class);
	}

	private final WebDriver webDriver;

	@FindBy(linkText = "Add")
	private WebElement a;

	@FindBy(css = "table tr")
	private List<WebElement> contacts;

	@FindBy(xpath = "//input[@type='submit' and @value='Logoff']")
	private WebElement logout;

	public ContactsPage(WebDriver webDriver) {
		this.webDriver = webDriver;
	}

	public ContactsPage isAtContactsPage() {
		assertThat(this.webDriver.getTitle()).isEqualTo("Your Contacts");
		return this;
	}

	public AddForm addContact() {
		a.click();
		final AddPage addPage = PageFactory.initElements(this.webDriver, AddPage.class);
		return addPage.addForm();
	}

	Predicate<WebElement> byEmail(final String val) {
		return e -> e.findElements(By.xpath("td[position()=3 and normalize-space()='" + val + "']")).size() == 1;
	}

	Predicate<WebElement> byName(final String val) {
		return e -> e.findElements(By.xpath("td[position()=2 and normalize-space()='" + val + "']")).size() == 1;
	}

	public DeleteContactLink andHasContact(final String name, final String email) {
		return this.contacts.stream()
			.filter(byEmail(email).and(byName(name)))
			.map(e -> e.findElement(By.cssSelector("td:nth-child(4) > a")))
			.findFirst()
			.map(e -> new DeleteContactLink(webDriver, e))
			.get();
	}

	public ContactsPage andConctactHasBeenRemoved(final String name, final String email) {
		assertThat(this.contacts.stream()
			.filter(byEmail(email).and(byName(name)))
			.findAny()).isEmpty();
		return this;
	}

	public HomePage logout() {
		this.logout.click();
		return PageFactory.initElements(this.webDriver, HomePage.class);
	}

	public static class DeleteContactLink {

		private final WebDriver webDriver;

		private final WebElement a;

		public DeleteContactLink(WebDriver webDriver, WebElement a) {
			this.webDriver = webDriver;
			this.a = a;
		}

		public DeleteConfirmationPage delete() {
			this.a.click();
			return PageFactory.initElements(this.webDriver, DeleteConfirmationPage.class);
		}
	}

	public static class DeleteConfirmationPage {
		private final WebDriver webDriver;

		@FindBy(linkText = "Manage")
		private WebElement a;

		public DeleteConfirmationPage(WebDriver webDriver) {
			this.webDriver = webDriver;
		}

		public ContactsPage andConfirmDeletion() {
			assertThat(this.webDriver.getTitle()).isEqualTo("Deletion completed");
			this.a.click();
			return PageFactory.initElements(this.webDriver, ContactsPage.class);
		}
	}
}


text:
var UI = {
    news: [],
    newsLines: 2,
    timer: null,
    hours: 0,
    days: 0,

    areaToDisplay: "City",
    populationToDisplay: 0,
    deathsToDisplay: 0,
    destructionToDisplay: 0,
    followersToDisplay: {clerics: 0, zealots: 0},

    create: function(){
        this.newsLines = 2;
        this.news[0] = "Click in a district to place";
        this.news[1] = "your first cleric.";
    },
    renderTop: function(ctx){
        // Border
        ctx.strokeRect(5,5,490,95);

        // Date
        // Day
        ctx.textAlign="center";
        ctx.fillStyle = "rgb(196,189,223)";
        ctx.fillRect(10,10,55,85);
        ctx.fillStyle = "rgb(211,157,139)";
        ctx.fillRect(70,10,55,85);
        ctx.fillStyle = "rgb(0,0,0)";
        ctx.font = "normal 13pt Arial";
        ctx.fillText("DAY",37,30);
        ctx.fillText("HOUR",97,30);

        ctx.font = "normal 35pt Arial";
        ctx.fillText(this.days,37,80);
        ctx.fillText(this.hours,97,80);

        // news
        ctx.fillStyle = "rgb(187,203,242)";
        ctx.font = "normal 17.5pt Arial";
        if (this.newsLines === 1)
        {
            ctx.fillText(this.news[0],310,60);
        }
        else
        {
            ctx.fillText(this.news[0],310,45);
            ctx.fillText(this.news[1],310, 75);
        }
    },
    renderBottom: function(ctx){
        // Border
        ctx.strokeRect(5,455,490,100);

        ctx.textAlign="left";
        // Follower Info
        ctx.fillStyle = "rgb(238,236,185)";
        ctx.font = "bold 15pt Arial";
        ctx.fillText("Followers",15,480);
        ctx.font = "normal 13pt Arial";
        ctx.fillText("Clerics: " + this.followersToDisplay.clerics,15,505);
        ctx.fillText("Zealots: " + this.followersToDisplay.zealots,15,525);

        // Divider
        ctx.fillStyle = "rgb(183,134,170)";
        ctx.fillRect(135, 460, 1, 90);

        // Area Info
        ctx.fillStyle = "rgb(242,170,158)";
        ctx.font = "bold 15pt Arial";
        ctx.fillText(this.areaToDisplay,150,480);
        ctx.font = "normal 13pt Arial";
        ctx.fillText("Population: " + this.populationToDisplay,150,505);
        ctx.fillText("Deaths: " + this.deathsToDisplay,150,525);
        ctx.fillText("Destruction: " + this.destructionToDisplay,150,545);

        // Tech Button
        if ((Input.mousePosition.x > 370 && Input.mousePosition.x < 490 &&
            Input.mousePosition.y > 460 && Input.mousePosition.y < 550) &&
            !FireTech.show && !MainGame.gameOver)
        {
            ctx.fillStyle = "rgb(147,109,119)";
            ctx.fillRect(370,465,120,85);
            ctx.fillStyle = "rgb(229,199,207)";
            ctx.fillRect(370,460,120,86);
        }
        else
        {
            ctx.fillStyle = "rgb(109,72,80)";
            ctx.fillRect(370,465,120,85);
            ctx.fillStyle = "rgb(196,151,159)";
            ctx.fillRect(370,460,120,86);
        }

        ctx.fillStyle = "rgb(20,2,6)";
        ctx.font = "bold 18pt Arial";
        ctx.fillText("Influence",377,487);
        ctx.textAlign="center";
        ctx.font = "normal 16pt Arial";
        ctx.fillText("Points: " + FireTech.techPoints ,432,530);

    },
    render: function()
    {
        var ctx = document.getElementById(MainGame.currentState).getContext("2d");
        // Styles that wont change:
        ctx.strokeStyle = "rgb(183,134,170)";
        ctx.lineWidth = 1;

        this.renderTop(ctx);
        this.renderBottom(ctx);
    },
    displayEvent: function(newsEventLine1, newsEventLine2){
        this.newsLines = 1;
        this.news[0] = newsEventLine1;

        if (typeof newsEventLine2 !== "undefined")
        {
            this.newsLines = 2;
            this.news[1] = newsEventLine2;
        }
    },
    displayAreaInfo: function()
    {
        this.getAreaInfo();
    },
    getAreaInfo: function()
    {
        // look for selected region and give it's info
        // Only getting city info for now
        this.areaToDisplay = "City";
        this.populationToDisplay = GameMap.population;
        this.deathsToDisplay = GameMap.startingPopulation - GameMap.population;
        this.destructionToDisplay = GameMap.destruction;
        this.followersToDisplay = GameMap.numberOfFollowers;

        for (var district in GameMap.districts)
        {
            if (GameMap.districts[district].mouseOver)
            {
                this.areaToDisplay = GameMap.districts[district].name;
                this.populationToDisplay = GameMap.districts[district].population;
                this.deathsToDisplay = GameMap.districts[district].startingPopulation - GameMap.districts[district].population;
                this.destructionToDisplay = GameMap.districts[district].destruction;
                this.followersToDisplay = GameMap.districts[district].numberOfFollowers;
            }
        }
    },
    openTechTree: function(){
        if (!FireTech.show)
        {
            console.log("Open Tech Tree");
            FireTech.show = true;

            FireTech.open();
        }
    },
    updateCounter: function(){
        if (this.timer === null)
        {
            this.timer = MainGame.timeNow();
        }
        else if(MainGame.timeNow() - this.timer >= GameMap.timePerHour)
        {
            this.timer = MainGame.timeNow();
            if (this.hours + 1 >= 24)
            {
                this.days++;
                this.hours = 0;
            }
            else
            {
                this.hours++;
            }
        }
    },
    deleteUI: function(){
        this.news = [];
        this.newsLines = 1;
        this.timer = null;
        this.hours = 0;
        this.days = 0;
    }
};


text:
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_RPC_PLUGINS_SDL_RPC_PLUGIN_INCLUDE_SDL_RPC_PLUGIN_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_RPC_PLUGINS_SDL_RPC_PLUGIN_INCLUDE_SDL_RPC_PLUGIN_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_

#include "application_manager/commands/request_from_mobile_impl.h"

namespace sdl_rpc_plugin {
namespace app_mngr = application_manager;

namespace commands {

class UnsubscribeWayPointsRequest
    : public app_mngr::commands::RequestFromMobileImpl {
 public:
  /**
   * \brief UnsubscribeWayPointsRequest class constructor
   **/
  UnsubscribeWayPointsRequest(
      const app_mngr::commands::MessageSharedPtr& message,
      app_mngr::ApplicationManager& application_manager,
      app_mngr::rpc_service::RPCService& rpc_service,
      app_mngr::HMICapabilities& hmi_capabilities,
      policy::PolicyHandlerInterface& policy_handler);

  /**
   * \brief UnsubscribeWayPointsRequest class destructor
   **/
  ~UnsubscribeWayPointsRequest();

  /**
   * @brief Execute command
   **/
  void Run() FINAL;

  /**
   * @brief Interface method that is called whenever new event received
   *
   * @param event The received event
   */
  void on_event(const app_mngr::event_engine::Event& event) FINAL;

  /**
   * @brief Init sets hash update mode for request
   */
  bool Init() FINAL;

  void OnTimeOut() FINAL;

 private:
  DISALLOW_COPY_AND_ASSIGN(UnsubscribeWayPointsRequest);
};

}  // namespace commands

}  // namespace sdl_rpc_plugin

#endif  // SRC_COMPONENTS_APPLICATION_MANAGER_RPC_PLUGINS_SDL_RPC_PLUGIN_INCLUDE_SDL_RPC_PLUGIN_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_


text:
package Atomic.core;

import glib.util.vector.GVector2f;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.HashMap;

public class Input implements KeyListener, MouseListener, MouseMotionListener{
	private HashMap<Integer,Boolean> keys = new HashMap<Integer,Boolean>();
	private HashMap<Integer,Boolean> mouses = new HashMap<Integer,Boolean>();
	private GVector2f mousePos = new GVector2f();

	public final static int KEY_W = 87;
	public final static int KEY_A = 65;
	public final static int KEY_S = 83;
	public final static int KEY_D = 68;
	public final static int KEY_Q = 81;
	public final static int KEY_E = 69;
	public final static int KEY_F = 70;
	public final static int KEY_UP = 38;
	public final static int KEY_LEFT = 37;
	public final static int KEY_DOWN = 40;
	public final static int KEY_RIGHT = 39;
	public final static int KEY_LCONTROL = 17;
	public final static int KEY_ENTER = 10;
	public final static int KEY_ESCAPE = 27;
	public final static int KEY_LALT = 18;
	public final static int KEY_LSHIFT = 16;
	public final static int KEY_SPACE = 32;

	public final static int BUTTON_LEFT = 1;
	public final static int BUTTON_RIGHT = 3;

	public boolean isKeyDown(int key){
		if(keys.containsKey(key)){
			return keys.get(key);
		}
		return false;
	}
	public boolean isMouseDown(int key){
		if(mouses.containsKey(key)){
			return mouses.get(key);
		}
		return false;
	}

	@Override
	public void keyPressed(KeyEvent e) {
		keys.put(e.getKeyCode(), true);

	}

	@Override
	public void keyReleased(KeyEvent e) {
		keys.put(e.getKeyCode(), false);

	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseDragged(MouseEvent e) {
		mousePos = new GVector2f(e.getX(),e.getY());

	}

	@Override
	public void mouseMoved(MouseEvent e) {
		mousePos = new GVector2f(e.getX(),e.getY());

	}

	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		mouses.put(e.getButton(), true);

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		mouses.put(e.getButton(), false);

	}
	public GVector2f getMousePos() {
		return mousePos;
	}
}


text: gamesCollection = new Mongo.Collection("Games");


text:
require("requirish")._(module);

var should = require("should");
var assert = require("better-assert");
var async = require("async");
var util = require("util");
var _ = require("underscore");

var opcua = require("index");

var OPCUAClient = opcua.OPCUAClient;
var StatusCodes = opcua.StatusCodes;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var DataValue = opcua.DataValue;

var browse_service = opcua.browse_service;
var BrowseDirection = browse_service.BrowseDirection;

var debugLog = require("lib/misc/utils").make_debugLog(__filename);

var resourceLeakDetector = require("test/helpers/resource_leak_detector").resourceLeakDetector;
var empty_nodeset_filename = require("path").join(__dirname, "../fixtures/fixture_empty_nodeset2.xml");

describe("testing Client-Server -Event", function () {

    this.timeout(10000);

    var port = 2222;
    var server;
    var endpointUrl;

    function start_server(done) {
        //xx resourceLeakDetector.start();
        server = new opcua.OPCUAServer({
            port: port,
            nodeset_filename: empty_nodeset_filename,
            maxAllowedSessionNumber: 10
        });

        server.start(function () {
            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            done();
        });
    }

    function end_server(done) {
        if (server) {
            server.shutdown(function () {
                //xx resourceLeakDetector.stop();
                server = null;
                done();
            });
        } else {
            done();
        }
    }

    it("should raise a close event once on normal disconnection", function (done) {

        var close_counter = 0;

        var client = new OPCUAClient();
        client.on("close", function (err) {

            //xx console.log(" client.on('close') Stack ", (new Error()).stack);
            //xx console.log(" Error ", err);

            should(err).eql(null, "No error shall be transmitted when client initiates the disconnection");
            close_counter++;
        });

        async.series([

            function (callback) {
                start_server(callback);
            },
            function (callback) {
                client.connect(endpointUrl, callback);
            },
            function (callback) {
                close_counter.should.eql(0);
                client.disconnect(callback);
            },
            function (callback) {
                close_counter.should.eql(1);
                callback(null);
            },
            function (callback) {
                end_server(callback);
            }
        ], done);

    });

    it("Client should raise a close event with an error when server initiates disconnection", function (done) {

        var close_counter = 0;
        var client = new OPCUAClient();

        var the_pending_callback = null;

        function on_close_func(err) {

            close_counter++;
            if (the_pending_callback) {
                close_counter.should.eql(1);
                var callback = the_pending_callback;
                the_pending_callback = null;

                should(err).be.instanceOf(Error);

                assert(_.isFunction(on_close_func));
                client.removeListener("close", on_close_func);

                setImmediate(callback);
            }

        }

        client.on("close", on_close_func);

        async.series([
            function (callback) {
                start_server(callback);
            },
            function (callback) {
                client.connect(endpointUrl, callback);
            },
            function (callback) {

                close_counter.should.eql(0);

                // client is connected but server initiate a immediate shutdown , closing all connections
                // delegate the call of the callback function of this step to when client has closed
                the_pending_callback = callback;

                end_server(function() {

                });
            },
            function (callback) {
                close_counter.should.eql(1);
                callback();
            }

        ], done);
    });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Buellia trypethelii Tuck.

### Remarks
null


text:
package scamell.michael.amulet;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

public class DrinkDiaryFragment extends ListFragment {

    public static final int REQUEST_CODE = 1234;

    private DrinkDiaryEntries dDE = new DrinkDiaryEntries();
    private DrinkDiaryEntryAdapter adapter;
    private DrinkDiaryFavouriteDrinksDialogFragment drinkDiaryFavouriteDrinksDialogFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_drink_diary, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);

        dDE = DrinkDiaryEntries.createDrinkDiaryEntriesFromStorage(getActivity(), "DrinkDiaryEntries.json");
        if (dDE != null) {
            adapter = new DrinkDiaryEntryAdapter(getActivity(), dDE);
            setListAdapter(adapter);
        }

        try {
            //noinspection ConstantConditions
            getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!dDE.getSelectedStatus(position)) {
                        //set the drink entries selected status to track it for deletion
                        dDE.setSelectedStatus(position, true);
                    }
                    view.setBackgroundResource(R.color.AmuletBlue);
                    return true;
                }
            });
        } catch (Exception e) {
            Log.e("ERROR_NULL_POINTER", "Couldn't get view onLongItemClick");
            e.printStackTrace();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.action_bar_drink_diary, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case R.id.action_add:
                UnitCalculatorFragment unitCalculatorFragment = new UnitCalculatorFragment();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                Bundle args = new Bundle();
                args.putBoolean("drink_diary_unit_calculator", true);
                unitCalculatorFragment.setArguments(args);
                fragmentManager.beginTransaction().replace(R.id.content_frame, unitCalculatorFragment, "unit_calculator").addToBackStack("Unit Calculator").commit();
                return true;
            case R.id.action_add_favourite:
                drinkDiaryFavouriteDrinksDialogFragment = new DrinkDiaryFavouriteDrinksDialogFragment();
                drinkDiaryFavouriteDrinksDialogFragment.setTargetFragment(this, REQUEST_CODE);
                drinkDiaryFavouriteDrinksDialogFragment.show(getFragmentManager(), "FavouriteDrinksDialogFragment");
                //delete drink diary item code
//            case R.id.action_delete:
//                for(int i = 0; i < dDE.getNumEntries(); i++)  {
//                    if(dDE.getEntry(i).isSelected) {
//                        dDE.removeEntry(i);
//                    }
//                }
//                dDE.saveToStorage(getActivity());
//                adapter.notifyDataSetChanged();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1234) {
            dDE.removeAllEntries();
            DrinkDiaryEntries drinkDiaryEntries = DrinkDiaryEntries.createDrinkDiaryEntriesFromStorage(getActivity(), "DrinkDiaryEntries.json");
            for (int i = 0; i < drinkDiaryEntries.getNumEntries(); i++) {
                dDE.addEntry(drinkDiaryEntries.getEntry(i));
            }
            adapter.updateView(dDE);
        }
    }

}


text:
/// <amd-module name="@angular/compiler-cli/src/version" />
/**
 * @module
 * @description
 * Entry point for all public APIs of the common package.
 */
import { Version } from '@angular/compiler';
export declare const VERSION: Version;


text:
SET DEFINE OFF;
ALTER TABLE AFW_19_CLE ADD (
  CONSTRAINT AFW_19_CLE_UK1
  UNIQUE (REF_DISPN_FONCT, REF_LANG, INDIC_INTER, CODE_KEYPR, CODE_KEYDW, INDIC_SHIFT, INDIC_ALT, INDIC_CTRL)
  ENABLE VALIDATE)
/


text:
layout: post
title: Code Cheatsheets
---

This is a collection of code cheatsheets that I've written to easily remember
the commonly used syntax of a language or software. This is
not meant to be a complete reference, but a quick guide to easily write code.
I'll be constantly updating this list as I learn new stuff.

##Quick Setup

If you need to view this site locally, just download the [cheatsheets](https://github.com/karloespiritu/CheatSheets) GitHub repo and run it locally.

```bash
~ gem install jekyll
~ git clone git@github.com:karloespiritu/cheatsheets.git
~ cd cheatsheets
~ jekyll serve
# => Now browse to http://localhost:4000
```

If you have questions or suggestions, feel free to [open an issue on GitHub](https://github.com/karloespiritu/cheatsheets/issues/new) or [ask me on Twitter](https://twitter.com/karloespiritu).

## About

This site is using the [BlackDoc](https://github.com/karloespiritu/BlackDoc) Jekyll theme, which can also be freely [downloaded](https://github.com/karloespiritu/BlackDoc) from Github.

Thanks for reading!


text:
module Sync.Mode (
	Mode(..),
	syncPatch
	) where

import Prelude.Unicode

import Sync.Base

-- | Sync mode
data Mode = Default | Mirror | New | Overwrite | Skip deriving (Eq, Ord, Read, Show, Enum, Bounded)

-- | Make patch to apply on @dst@, synchronizing updates on @src@
syncPatch ∷ (Ord k, Ord a) ⇒ Mode → Patch k a → Patch k a → Merge k a
syncPatch m src dst = case m of
	Default → combined
	Mirror → revert dst `chain` src
	New → tryResolve newestLeft combined
	Overwrite → fmap Merged ∘ resolve preferLeft $ combined
	Skip → fmap Merged ∘ resolved $ combined
	where
		combined = rebase src dst


text:
<?php if (!defined('IN_GS')) {die('you cannot load this page directly.');}

/**
 * Common variables used by the GetSimple News Manager Plugin.
 */

# path definitions
define('NMPOSTPATH', GSDATAPATH  . 'posts/');
define('NMBACKUPPATH', GSBACKUPSPATH  . 'posts/');
define('NMDATAPATH', GSDATAOTHERPATH  . 'news_manager/');
define('NMINCPATH', GSPLUGINPATH . 'news_manager/inc/');
define('NMLANGPATH', GSPLUGINPATH . 'news_manager/lang/');
define('NMTEMPLATEPATH', GSPLUGINPATH . 'news_manager/template/');

# file definitions
define('NMSETTINGS', NMDATAPATH . 'settings.xml');
define('NMPOSTCACHE', NMDATAPATH . 'posts.xml');

# URL parameters
if (!defined('NMPARAMPOST'))    define('NMPARAMPOST', 'post');
if (!defined('NMPARAMPAGE'))    define('NMPARAMPAGE', 'page');
if (!defined('NMPARAMARCHIVE')) define('NMPARAMARCHIVE', 'archive');
if (!defined('NMPARAMTAG'))     define('NMPARAMTAG', 'tag');
if (!defined('NMFIRSTPAGE'))    define('NMFIRSTPAGE', 1);

# includes
require_once(NMINCPATH . 'functions.php');
require_once(NMINCPATH . 'settings.php');
require_once(NMINCPATH . 'cache.php');
require_once(NMINCPATH . 'admin.php');
require_once(NMINCPATH . 'posts.php');
require_once(NMINCPATH . 'site.php');
require_once(NMINCPATH . 'sidebar.php');

# load settings
$data = @getXML(NMSETTINGS);
$NMPAGEURL       = isset($data->page_url) ? $data->page_url : ''; // default: no slug selected
$NMPRETTYURLS    = isset($data->pretty_urls) ? $data->pretty_urls : '';
$NMLANG          = isset($data->language) ? $data->language : 'en_US';
$NMSHOWEXCERPT   = isset($data->show_excerpt) ? $data->show_excerpt : '';
$NMEXCERPTLENGTH = isset($data->excerpt_length) ? $data->excerpt_length : '350';
$NMPOSTSPERPAGE  = isset($data->posts_per_page) ? $data->posts_per_page : '8';
$NMRECENTPOSTS   = isset($data->recent_posts) ? $data->recent_posts : '5';
# new settings (since 3.0)
$NMSETTING = array();
$NMSETTING['archivesby'] = isset($data->archivesby) ? $data->archivesby : 'm';
$NMSETTING['readmore'] = isset($data->readmore) ? $data->readmore : ((defined('NM2COMPAT') && NM2COMPAT) ? 'N' : 'R');
$NMSETTING['titlelink'] = isset($data->titlelink) ? $data->titlelink : 'Y';
$NMSETTING['gobacklink'] = isset($data->gobacklink) ? $data->gobacklink : 'B';
$NMSETTING['images'] = isset($data->images) ? $data->images : 'N';
$NMSETTING['imagewidth'] = isset($data->imagewidth) ? $data->imagewidth : '';
$NMSETTING['imageheight'] = isset($data->imageheight) ? $data->imageheight : '';
$NMSETTING['imagecrop'] = isset($data->imagecrop) ? $data->imagecrop : '';
$NMSETTING['imagealt'] = isset($data->imagealt) ? $data->imagealt : '';
$NMSETTING['imagelink'] = isset($data->imagelink) ? $data->imagelink : '';
$NMSETTING['enablecustomsettings'] = isset($data->enablecustomsettings) ? $data->enablecustomsettings : '';
$NMSETTING['customsettings'] = isset($data->customsettings) ? $data->customsettings : '';

# other globals
$NMPARENTURL = '?'; // to be assigned elsewhere

?>


text:
"use strict";

define(['lib/component'], function (defineComponent) {

  describe('(Core) constructor', function () {

    function testComponent() {
      this.testVal = 1066;
    }

    function testComponentDefaultAttrs() {
      this.defaultAttrs({core: 35});
    }

    function testComponentDefaultAttrsRequired() {
      this.defaultAttrs({req: null});
    }

    function withGoodDefaults() {
      this.defaultAttrs({extra: 38});
    }

    function withBadDefaults() {
      this.defaultAttrs({core: 38});
    }

    it('exports a define function', function () {
      expect(typeof defineComponent).toBe('function');
    });

    it('defineComponent() should return a component constructor', function () {
      var TestComponent = defineComponent(testComponent);

      expect(typeof TestComponent).toBe('function');
      expect(typeof TestComponent.attachTo).toBe('function');
      expect(TestComponent.prototype.testVal).toBe(1066);
    });

    it('has standard methods', function () {
      var TestComponent = defineComponent(testComponent);

      expect(typeof TestComponent.prototype.on).toBe('function');
      expect(typeof TestComponent.prototype.off).toBe('function');
      expect(typeof TestComponent.prototype.trigger).toBe('function');
    });

    it('can describe itself', function () {
      var TestComponent = defineComponent(testComponent, withGoodDefaults);
      expect(TestComponent.toString()).toBe('testComponent, withGoodDefaults');
    });

    it('adds core defaults', function () {
      var TestComponent = defineComponent(testComponentDefaultAttrs);
      var instance = (new TestComponent).initialize(document.body);

      expect(instance.attr.core).toBe(35);

      TestComponent.teardownAll();
    });

    it('throws error if required attr not specified', function () {
      var TestComponent = defineComponent(testComponentDefaultAttrsRequired);
      expect(function () {
        var instance = (new TestComponent).initialize(document.body);
      }).toThrow('Required attribute "req" not specified in attachTo for component "testComponentDefaultAttrsRequired".');

      TestComponent.teardownAll();
    });

    it("doesn't throw error if required attr is specified", function () {
      var TestComponent = defineComponent(testComponentDefaultAttrsRequired);
      expect(function () {
        var instance = (new TestComponent).initialize(document.body, { req: 'hello' });
      }).not.toThrow();

      TestComponent.teardownAll();
    });

    it("doesn't attach to empty jQuery objects", function () {
      var TestComponent = defineComponent(testComponentDefaultAttrs);
      var trouble = function () {
        (new TestComponent).initialize();
      };
      expect(trouble).toThrow(new Error("Component needs a node"));
    });

    it('adds mixin defaults', function () {
      var TestComponent = defineComponent(testComponent, withGoodDefaults);
      var instance = (new TestComponent).initialize(document.body);

      expect(instance.attr.extra).toBe(38);

      TestComponent.teardownAll();
    });

    it('adds core and mixin defaults', function () {
      var TestComponent = defineComponent(testComponentDefaultAttrs, withGoodDefaults);
      var instance = (new TestComponent).initialize(document.body);
      expect(instance.attr.core).toBe(35);
      expect(instance.attr.extra).toBe(38);

      TestComponent.teardownAll();
    });

    it('throws error when core and mixin defaults overlap', function () {
      expect(function () {
        defineComponent(testComponentDefaultAttrs, withBadDefaults);
      }).toThrow('utils.push attempted to overwrite "core" while running in protected mode');
    });

    describe('teardownAll', function () {

      it('should teardown all instances', function () {
        var TestComponent = defineComponent(testComponent);
        var instance1 = (new TestComponent).initialize(document.body)
        var instance2 = (new TestComponent).initialize(document.body);
        spyOn(instance1, 'teardown').andCallThrough();
        spyOn(instance2, 'teardown').andCallThrough();
        TestComponent.teardownAll();
        expect(instance1.teardown).toHaveBeenCalled();
        expect(instance2.teardown).toHaveBeenCalled();
      });

      it('should support teardowns that cause other teardowns', function () {
        var TestComponent = defineComponent(testComponent);
        var instance1 = (new TestComponent).initialize(document.body)
        var instance2 = (new TestComponent).initialize(document.body);
        var original = instance1.teardown;
        instance1.teardown = function () {
          instance2.teardown();
          original.call(this);
        }.bind(instance1);
        expect(function () {
          TestComponent.teardownAll();
        }).not.toThrow();
      });

    });

  });
});


text:
<?php

namespace Magento\CatalogInventory\Model\Indexer\Stock\Action;

/**
 * Class Row reindex action
 *
 * @package Magento\CatalogInventory\Model\Indexer\Stock\Action
 */
class Row extends \Magento\CatalogInventory\Model\Indexer\Stock\AbstractAction
{
    /**
     * Execute Row reindex
     *
     * @param int|null $id
     * @throws \Magento\Framework\Exception\LocalizedException
     *
     * @return void
     */
    public function execute($id = null)
    {
        if (!isset($id) || empty($id)) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('We can\'t rebuild the index for an undefined product.')
            );
        }
        try {
            $this->_reindexRows([$id]);
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage()), $e);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>a60_abstractDataServiceAdapter.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.5.1/build/cssgrids/cssgrids-min.css">

	<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

			Download

			Tutorials

			Docs

			Samples

			Support

			Blog

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AutoGeneratedKeyType

ComplexAspect

ComplexType

config

DataProperty

DataService

DataType

EntityAction

EntityAspect

EntityKey

EntityManager

EntityQuery

EntityState

EntityType

Enum

EnumSymbol

Event

FetchStrategy

FilterQueryOp

HttpResponse

JsonResultsAdapter

LocalQueryComparisonOptions

MergeStrategy

MetadataStore

NamingConvention

NavigationProperty

Predicate

Promise

QueryOptions

SaveOptions

ValidationError

ValidationOptions

Validator

~ajax_interface

~complexArray

~keyGenerator_interface

~primitiveArray

~relationArray

breeze

core

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: a60_abstractDataServiceAdapter.js

breeze.AbstractDataServiceAdapter = (function () {

  var ajaxImpl;

  var ctor = function () {
  };

  var proto = ctor.prototype; // minifies better (as seen in jQuery)

  proto.checkForRecomposition = function (interfaceInitializedArgs) {
    if (interfaceInitializedArgs.interfaceName === "ajax" && interfaceInitializedArgs.isDefault) {
      this.initialize();
    }
  };

  proto.initialize = function () {
    ajaxImpl = breeze.config.getAdapterInstance("ajax");

    // don't cache 'ajax' because then we would need to ".bind" it, and don't want to because of brower support issues.
    if (ajaxImpl && ajaxImpl.ajax) {
      return;
    }
    throw new Error("Unable to find ajax adapter for dataservice adapter '" + (this.name || '') + "'.");
  };

  proto.fetchMetadata = function (metadataStore, dataService) {
    var serviceName = dataService.serviceName;
    var url = dataService.qualifyUrl("Metadata");

    var deferred = Q.defer();

    ajaxImpl.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      success: function (httpResponse) {

        // might have been fetched by another query
        if (metadataStore.hasMetadataFor(serviceName)) {
          return deferred.resolve("already fetched");
        }
        var data = httpResponse.data;
        try {
          var metadata = typeof (data) === "string" ? JSON.parse(data) : data;
          metadataStore.importMetadata(metadata);
        } catch (e) {
          var errMsg = "Unable to either parse or import metadata: " + e.message;
          return handleHttpError(deferred, httpResponse, "Metadata query failed for: " + url + ". " + errMsg);
        }

        // import may have brought in the service.
        if (!metadataStore.hasMetadataFor(serviceName)) {
          metadataStore.addDataService(dataService);
        }

        return deferred.resolve(metadata);

      },
      error: function (httpResponse) {
        handleHttpError(deferred, httpResponse, "Metadata query failed for: " + url);
      }
    });
    return deferred.promise;
  };

  proto.executeQuery = function (mappingContext) {
    var adapter = mappingContext.adapter = this;
    var deferred = Q.defer();
    var url = mappingContext.getUrl();

    var params = {
      type: "GET",
      url: url,
      params: mappingContext.query.parameters,
      dataType: 'json',
      success: function (httpResponse) {
        var data = httpResponse.data;
        try {
          var rData;
          var results = data && (data.results || data.Results);
          if (results) {
            rData = { results: results, inlineCount: data.inlineCount || data.InlineCount, httpResponse: httpResponse };
          } else {
            rData = { results: data, httpResponse: httpResponse };
          }

          deferred.resolve(rData);
        } catch (e) {
          if (e instanceof Error) {
            deferred.reject(e);
          } else {
            handleHttpError(deferred, httpResponse);
          }
        }

      },
      error: function (httpResponse) {
        handleHttpError(deferred, httpResponse);
      }
    };
    if (mappingContext.dataService.useJsonp) {
      params.dataType = 'jsonp';
      params.crossDomain = true;
    }
    ajaxImpl.ajax(params);
    return deferred.promise;
  };

  proto.saveChanges = function (saveContext, saveBundle) {
    var adapter = saveContext.adapter = this;
    var deferred = Q.defer();
    saveBundle = adapter._prepareSaveBundle(saveContext, saveBundle);
    var bundle = JSON.stringify(saveBundle);

    var url = saveContext.dataService.qualifyUrl(saveContext.resourceName);

    ajaxImpl.ajax({
      type: "POST",
      url: url,
      dataType: 'json',
      contentType: "application/json",
      data: bundle,
      success: function (httpResponse) {
        httpResponse.saveContext = saveContext;
        var data = httpResponse.data;
        if (data.Errors || data.errors) {
          handleHttpError(deferred, httpResponse);
        } else {
          var saveResult = adapter._prepareSaveResult(saveContext, data);
          saveResult.httpResponse = httpResponse;
          deferred.resolve(saveResult);
        }
      },
      error: function (httpResponse) {
        httpResponse.saveContext = saveContext;
        handleHttpError(deferred, httpResponse);
      }
    });

    return deferred.promise;
  };

  proto._prepareSaveBundle = function (/*saveContext, saveBundle*/) {
    // The implementor should call _createChangeRequestInterceptor
    throw new Error("Need a concrete implementation of _prepareSaveBundle");
  };

  /**
   Returns a constructor function for a "ChangeRequestInterceptor"
   that can tweak the saveBundle both as it is built and when it is completed
   by a concrete DataServiceAdapater.

   Initialized with a default, no-op implementation that developers can replace with a
   substantive implementation that changes the individual entity change requests
   or aspects of the entire 'saveBundle' without having to write their own DataService adapters.

   @example
   var adapter = breeze.config.getAdapterInstance('dataService');
   adapter.changeRequestInterceptor = function (saveContext, saveBundle) {
        this.getRequest = function (request, entity, index) {
            // alter the request that the adapter prepared for this entity
            // based on the entity, saveContext, and saveBundle
            // e.g., add a custom header or prune the originalValuesMap
            return request;
        };
        this.done = function (requests) {
            // alter the array of requests representing the entire change-set
            // based on the saveContext and saveBundle
        };
    }
   @method changeRequestInterceptor
   @param saveContext {Object} The BreezeJS "context" for the save operation.
   @param saveBundle {Object} Contains the array of entities-to-be-saved (AKA, the entity change-set).
   @return {Function} Constructor for a "ChangeRequestInterceptor".
   **/
  proto.changeRequestInterceptor = DefaultChangeRequestInterceptor;

  //This is a default, no-op implementation that developers can replace.
  function DefaultChangeRequestInterceptor(saveContext, saveBundle) {
    /**
     Prepare and return the save data for an entity change-set.

     The adapter calls this method for each entity in the change-set,
     after it has prepared a "change request" for that object.

     The method can do anything to the request but it must return a valid, non-null request.
     @example
     this.getRequest = function (request, entity, index) {
            // alter the request that the adapter prepared for this entity
            // based on the entity, saveContext, and saveBundle
            // e.g., add a custom header or prune the originalValuesMap
            return request;
        };
     @method getRequest
     @param request {Object} The object representing the adapter's request to save this entity.
     @param entity {Entity} The entity-to-be-save as it is in cache
     @param index {Integer} The zero-based index of this entity in the change-set array
     @return {Function} The potentially revised request.
     **/
    this.getRequest = function (request, entity, index) {
      return request;
    };

    /**
     Last chance to change anything about the 'requests' array
     after it has been built with requests for all of the entities-to-be-saved.

     The 'requests' array is the same as 'saveBundle.entities' in many implementations

     This method can do anything to the array including add and remove requests.
     It's up to you to ensure that server will accept the requests array data as valid.

     Returned value is ignored.
     @example
     this.done = function (requests) {
            // alter the array of requests representing the entire change-set
            // based on the saveContext and saveBundle
        };
     @method done
     @param requests {Array of Object} The adapter's array of request for this changeset.
     **/
    this.done = function (requests) {
    };
  }

  proto._createChangeRequestInterceptor = function (saveContext, saveBundle) {
    var adapter = saveContext.adapter;
    var cri = adapter.changeRequestInterceptor;
    var isFn = __isFunction;

    if (isFn(cri)) {
      var pre = adapter.name + " DataServiceAdapter's ChangeRequestInterceptor";
      var post = " is missing or not a function.";
      var interceptor = new cri(saveContext, saveBundle);
      if (!isFn(interceptor.getRequest)) {
        throw new Error(pre + '.getRequest' + post);
      }
      if (!isFn(interceptor.done)) {
        throw new Error(pre + '.done' + post);
      }
      return interceptor;
    } else {
      return new DefaultChangeRequestInterceptor(saveContext, saveBundle);
    }
  }

  proto._prepareSaveResult = function (/* saveContext, data */) {
    throw new Error("Need a concrete implementation of _prepareSaveResult");
  };

  proto.jsonResultsAdapter = new JsonResultsAdapter({
    name: "noop",

    visitNode: function (/* node, mappingContext, nodeContext */) {
      return {};
    }

  });

  function handleHttpError(deferred, httpResponse, messagePrefix) {
    var err = createError(httpResponse);
    proto._catchNoConnectionError(err);
    if (messagePrefix) {
      err.message = messagePrefix + "; " + err.message;
    }
    return deferred.reject(err);
  }

  function createError(httpResponse) {
    var err = new Error();
    err.httpResponse = httpResponse;
    err.status = httpResponse.status;

    var errObj = httpResponse.data;

    if (!errObj) {
      err.message = httpResponse.error && httpResponse.error.toString();
      return err;
    }

    // some ajax providers will convert errant result into an object ( angular), others will not (jQuery)
    // if not do it here.
    if (typeof errObj === "string") {
      try {
        errObj = JSON.parse(errObj);
      } catch (e) {
        // sometimes httpResponse.data is just the error message itself
        err.message = errObj;
        return err;
      }
    }

    var saveContext = httpResponse.saveContext;

    // if any of the follow properties exist the source is .NET
    var tmp = errObj.Message || errObj.ExceptionMessage || errObj.EntityErrors || errObj.Errors;
    var isDotNet = !!tmp;
    var message, entityErrors;
    if (!isDotNet) {
      message = errObj.message;
      entityErrors = errObj.errors || errObj.entityErrors;
    } else {
      var tmp = errObj;
      do {
        // .NET exceptions can provide both ExceptionMessage and Message but ExceptionMethod if it
        // exists has a more detailed message.
        message = tmp.ExceptionMessage || tmp.Message;
        tmp = tmp.InnerException;
      } while (tmp);
      // .EntityErrors will only occur as a result of an EntityErrorsException being deliberately thrown on the server
      entityErrors = errObj.Errors || errObj.EntityErrors;
      entityErrors = entityErrors && entityErrors.map(function (e) {
        return {
          errorName: e.ErrorName,
          entityTypeName: MetadataStore.normalizeTypeName(e.EntityTypeName),
          keyValues: e.KeyValues,
          propertyName: e.PropertyName,
          errorMessage: e.ErrorMessage
        };
      });
    }

    if (saveContext && entityErrors) {
      var propNameFn = saveContext.entityManager.metadataStore.namingConvention.serverPropertyNameToClient;
      entityErrors.forEach(function (e) {
        e.propertyName = e.propertyName && propNameFn(e.propertyName);
      });
      err.entityErrors = entityErrors
    }

    err.message = message || "Server side errors encountered - see the entityErrors collection on this object for more detail";
    return err;
  }

  // Put this at the bottom of your http error analysis
  proto._catchNoConnectionError = function (err) {
    if (err.status == 0 && err.message == null) {
      err.message = "HTTP response status 0 and no message.  " +
          "Likely did not or could not reach server. Is the server running?";
    }
  }

  return ctor;

})();

      Download

      Tutorials

      Docs

      Samples

      Questions

      Support


text: WebsocketsSample::Application.config.session_store :cookie_store, key: '_websockets-sample_session'