text:
#ifndef SRC_TRACED_PROBES_FTRACE_FTRACE_PRINT_FILTER_H_
#define SRC_TRACED_PROBES_FTRACE_FTRACE_PRINT_FILTER_H_

#include <string>
#include <vector>

#include "perfetto/ext/base/optional.h"
#include "src/traced/probes/ftrace/proto_translation_table.h"

namespace perfetto {

struct Event;

namespace protos {
namespace gen {
class FtraceConfig_PrintFilter;
}  // namespace gen
}  // namespace protos

class FtracePrintFilter {
 public:
  // Builds a filter from a proto config.
  explicit FtracePrintFilter(const protos::gen::FtraceConfig_PrintFilter&);

  // Returns true if a string is allowed by this filter, false otherwise.
  // The string begins at `start` and terminates after `size` bytes, or at the
  // first '\0' byte, whichever comes first.
  bool IsAllowed(const char* start, size_t size) const;

 private:
  struct Rule {
    std::string prefix;
    bool allow;
  };
  std::vector<Rule> rules_;
};

class FtracePrintFilterConfig {
 public:
  static base::Optional<FtracePrintFilterConfig> Create(
      const protos::gen::FtraceConfig_PrintFilter&,
      ProtoTranslationTable* table);

  uint32_t event_id() const { return event_id_; }

  // Returns true if the "ftrace/print" event (encoded from `start` to `end`)
  // should be allowed.
  //
  // If the event should be allowed, or **if there was a problem parsing it**
  // returns true. If the event should be disallowed (i.e. ignored), returns
  // false.
  bool IsEventInteresting(const uint8_t* start, const uint8_t* end) const;

 private:
  explicit FtracePrintFilterConfig(FtracePrintFilter filter);
  FtracePrintFilter filter_;
  uint32_t event_id_;
  uint16_t event_size_;
  uint16_t buf_field_offset_;
};

}  // namespace perfetto

#endif  // SRC_TRACED_PROBES_FTRACE_FTRACE_PRINT_FILTER_H_


text:
#import "NSObject.h"

@interface VMUHeader : NSObject
{
}

+ (id)headerWithUniverse:(id)arg1 memory:(id)arg2 name:(id)arg3 path:(id)arg4 timestamp:(id)arg5;
+ (id)headerWithMemory:(id)arg1 address:(unsigned long long)arg2 name:(id)arg3 path:(id)arg4 timestamp:(id)arg5;
+ (id)extractMachOHeadersFromHeader:(id)arg1 matchingArchitecture:(id)arg2 considerArchives:(_Bool)arg3;
- (id)signature;
- (_Bool)isArchive;
- (_Bool)isMachO64;
- (_Bool)isMachO32;
- (_Bool)isMachO;
- (_Bool)isFat;

@end

redpajama_set_name: RedPajamaGithub


text:
ES5Harness.registerTest({

    id: "15.4.4.14-9-b-ii-9",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.14/15.4.4.14-9-b-ii-9.js",

    description: "Array.prototype.indexOf - both array element and search element are String, and they have exactly the same sequence of characters",
    test: function testcase() {

        return ["", "ab", "bca", "abc"].indexOf("abc") === 3;
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.indexOf);
    }

});


text:
import os
import re
from dataclasses import dataclass, field
from difflib import Differ
from typing import List

from mkdocs.config import Config
from mkdocs.structure.files import Files
from mkdocs.structure.nav import Link, Navigation, Section

@dataclass(frozen=True)
class NavDatum:
    year: int
    month: int
    title: str
    path: str

@dataclass(frozen=True)
class NavData:
    datums: List[NavDatum] = field(default_factory=list)

def parse_title(path):
    with open(path) as fh:
        for line in fh:
            if (match := re.search("title: (.+)$", line, re.IGNORECASE)) :
                return match.group(1)

def diff(left, right):
    d = Differ()
    result = list(
        d.compare(left.splitlines(keepends=True), right.splitlines(keepends=True))
    )
    return "".join(result)

def build_archive(data: NavData, path: str = "docs/archive.md"):
    """
    Creates the archive.md file based on the data provided.
    """
    line_fmt = "* {year}-{month:02d}: [{title}]({path})"
    lines = ["# Archive"]

    current_year = 0
    for datum in data.datums:

        if datum.year != current_year:
            current_year = datum.year
            lines += ["", f"## {datum.year}"]

        lines.append(
            line_fmt.format(
                year=datum.year, month=datum.month, title=datum.title, path=datum.path
            )
        )

    new_text = "\n".join(lines)

    with open(path) as fh:
        original_text = fh.read()

    if new_text == original_text:
        return

    print("################# Recreating archive.md")
    difference = diff(original_text, new_text)
    print(difference)

    with open(path, "w") as fh:
        fh.write(new_text)

def sorted_nav(nav: Navigation):
    """
    mkdocs-awesome-pages is already being used to "mostly" control the sort
    ordering through `.pages`.  However, it still won't sort the "months" part.
    """
    new_items = []
    year_sections = [y for y in nav.items if type(y) is Section]
    year_sections = sorted(year_sections, key=lambda y: int(y.title), reverse=True)
    years_iter = iter(year_sections)

    for item in nav.items:
        if type(item) is Section:
            new_items.append(next(years_iter))
        else:
            new_items.append(item)

    nav.items = new_items

    pages = sorted(
        [p for p in nav.pages if re.match(r"\d{4}/\d{2}", p.url)],
        key=lambda p: p.url,
        reverse=True,
    )
    pages_iter = iter(pages)

    new_pages = []
    for page in nav.pages:
        if re.match(r"\d{4}/\d{2}", page.url):
            new_pages.append(next(pages_iter))
        else:
            new_pages.append(page)
    nav.pages = new_pages

    return nav

def load_navdata_from_paths(paths: list) -> NavData:
    nav_data = NavData()

    for src_path in paths:
        match = re.search("^docs.*?(?P<year>\d+)/(?P<month>\d+)", src_path)

        d = NavDatum(
            year=int(match.group("year")),
            month=int(match.group("month")),
            title=parse_title(src_path),
            path=src_path.lstrip("docs" + os.path.sep),
        )

        nav_data.datums.append(d)

    nav_data.datums.sort(key=lambda p: (p.year, p.month), reverse=True)

    return nav_data

def on_nav(nav: Navigation, config: Config, files: Files):
    """
    Provide a custom sort method for the posts and add in the `latest` Link.
    """
    paths = [
        os.path.join("docs", p.file.src_path)
        for p in nav.pages
        if re.match(r"^\d+", p.url)
    ]
    nav_data = load_navdata_from_paths(paths)

    build_archive(nav_data)

    latest_link = Link(
        title="Latest post", url=nav_data.datums[0].path.replace(".md", "/")
    )
    nav.items.insert(1, latest_link)

    nav = sorted_nav(nav)

    return nav

def on_files(files, config):
    """Sort the files in reverse order so the "Next" navs work."""
    orig_files = files._files
    page_files = [x for x in orig_files if re.search(r"^\d{4}", x.dest_path)]
    page_files.sort(key=lambda x: x.url, reverse=True)
    page_files_iter = iter(page_files)

    new_files = []
    for page in files._files:
        if re.search(r"^\d{4}", page.dest_path):
            new_files.append(next(page_files_iter))
        else:
            new_files.append(page)

    files._files = new_files
    return files


text:
<?php

namespace Sylius\Bundle\PromotionBundle\DependencyInjection;

use Sylius\Bundle\ResourceBundle\DependencyInjection\AbstractResourceExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * Sylius promotions component extension.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class SyliusPromotionExtension extends AbstractResourceExtension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $config, ContainerBuilder $container)
    {
        $this->configure($config, new Configuration(), $container, self::CONFIGURE_LOADER | self::CONFIGURE_DATABASE | self::CONFIGURE_PARAMETERS | self::CONFIGURE_VALIDATORS);
    }
}


text:
package org.mule.mvel2.util;

import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author Mike Brock <cbrock@redhat.com>
 */
public class LineMapper {
  private char[] expr;

  private ArrayList<Node> lineMapping;
  private Set<Integer> lines;

  public LineMapper(char[] expr) {
    this.expr = expr;
  }

  public LineLookup map() {
    lineMapping = new ArrayList<Node>();
    lines = new TreeSet<Integer>();

    int cursor = 0;
    int start = 0;
    int line = 1;

    for (; cursor < expr.length; cursor++) {
      switch (expr[cursor]) {
        case '\n':
          lines.add(line);
          lineMapping.add(new Node(start, cursor, line++));
          start = cursor + 1;
          break;
      }
    }

    if (cursor > start) {
      lines.add(line);
      lineMapping.add(new Node(start, cursor, line));
    }

    return new LineLookup() {
      public int getLineFromCursor(int cursor) {
        for (Node n : lineMapping) {
          if (n.isInRange(cursor)) {
            return n.getLine();
          }
        }
        return -1;
      }

      public boolean hasLine(int line) {
        return lines.contains(line);
      }
    };
  }

  public static interface LineLookup {
    public int getLineFromCursor(int cursor);
    public boolean hasLine(int line);
  }

  private static class Node implements Comparable<Node> {
    private int cursorStart;
    private int cursorEnd;

    private int line;

    private Node(int cursorStart, int cursorEnd, int line) {
      this.cursorStart = cursorStart;
      this.cursorEnd = cursorEnd;
      this.line = line;
    }

    public int getLine() {
      return line;
    }

    public boolean isInRange(int cursor) {
      return cursor >= cursorStart && cursor <= cursorEnd;
    }

    public int compareTo(Node node) {
      if (node.cursorStart >= cursorEnd) {
        return 1;
      } else if (node.cursorEnd < cursorStart) {
        return -1;
      } else {
        return 0;
      }
    }
  }
}


text:
import boto3
import sure  # noqa # pylint: disable=unused-import

from moto import mock_appsync

schema = """type Mutation {
    putPost(id: ID!, title: String!): Post
}

"My custom post type"
type Post {
    id: ID!
    title: String!
}

type Query {
    singlePost(id: ID!): Post
}

schema {
    query: Query
    mutation: Mutation

}"""

@mock_appsync
def test_start_schema_creation():
    client = boto3.client("appsync", region_name="us-east-2")
    api_id = client.create_graphql_api(name="api1", authenticationType="API_KEY")[
        "graphqlApi"
    ]["apiId"]

    resp = client.start_schema_creation(apiId=api_id, definition=b"sth")

    resp.should.have.key("status").equals("PROCESSING")

@mock_appsync
def test_get_schema_creation_status():
    client = boto3.client("appsync", region_name="eu-west-1")
    api_id = client.create_graphql_api(name="api1", authenticationType="API_KEY")[
        "graphqlApi"
    ]["apiId"]

    client.start_schema_creation(apiId=api_id, definition=schema.encode("utf-8"))
    resp = client.get_schema_creation_status(apiId=api_id)

    resp.should.have.key("status").equals("SUCCESS")
    resp.shouldnt.have.key("details")

@mock_appsync
def test_get_schema_creation_status_invalid():
    client = boto3.client("appsync", region_name="eu-west-1")
    api_id = client.create_graphql_api(name="api1", authenticationType="API_KEY")[
        "graphqlApi"
    ]["apiId"]

    client.start_schema_creation(apiId=api_id, definition=b"sth")
    resp = client.get_schema_creation_status(apiId=api_id)

    resp.should.have.key("status").equals("FAILED")
    resp.should.have.key("details").match("Syntax Error")

@mock_appsync
def test_get_type_from_schema():
    client = boto3.client("appsync", region_name="us-east-2")

    api_id = client.create_graphql_api(name="api1", authenticationType="API_KEY")[
        "graphqlApi"
    ]["apiId"]

    client.start_schema_creation(apiId=api_id, definition=schema.encode("utf-8"))
    resp = client.get_type(apiId=api_id, typeName="Post", format="SDL")

    resp.should.have.key("type")
    graphql_type = resp["type"]
    graphql_type.should.have.key("name").equals("Post")
    graphql_type.should.have.key("description").equals("My custom post type")
    graphql_type.should.have.key("arn").equals("arn:aws:appsync:graphql_type/Post")
    graphql_type.should.have.key("definition").equals("NotYetImplemented")
    graphql_type.should.have.key("format").equals("SDL")

    query_type = client.get_type(apiId=api_id, typeName="Query", format="SDL")["type"]
    query_type.should.have.key("name").equals("Query")
    query_type.shouldnt.have.key("description")


text:
puts "What's your first name? "
first_name = gets.chomp
puts "What's your middle name? "
middle_name = gets.chomp
puts "What's your last name? "
last_name = gets.chomp
puts "Well hello there, #{first_name} #{middle_name} #{last_name}"

puts "What is your favorite number? "
fav_num = gets.chomp.to_i
fav_num += 1
puts "I think #{fav_num} is a bigger, better number, don't you?"

=begin

##How do you define a local variable?

Local variables start with a lower case letter or an underscore.  Unlike global or instance variables
which have a "nil" value before initialization, local variable do not; therefore, if you try to use or
access a local variable before a value has been assigned, you will get an "undefined local variable or
method" error.  So, it is good practice to declare a local variable's value when you create it.  For
example my_var = 4

##How do you define a method?

Methods are wrapped between a 'def' and an 'end'.  For example:

def my_method_name(args)
	#do something
end

The key word 'def' tells the compiler that you are creating a method. Above, the method will be named
'my_method_name'. Methods can accept arguments if you want to pass data into the method.  Using an
'*' before the last arg name will allow you to a have variable number of arguments passed into the
method.  The key word 'end' lets the compiler know that is the end of the method body.  The last value
before the 'end' keyword will be returned regardless of whether you explicitly use the keyword 'return'

##What is the difference between a local variable and a method?

Variables hold data, such as strings, integers, booleans, and floats.  Methods are like functions: they
perform an action.  Methods can be written to perform calculations on data, or to print out data or
messages.

##How do you run a ruby program from the command line?

type: ruby program_name.rb

##How do you run an RSpec file from the command line?

type: rspec rspec_filename.rb

##What was confusing about this material? What made sense?

This has all been very easy review for me a this point.

##Release 4.3.1 and 4.3.2

https://github.com/SilverFox70/phase-0/blob/master/week-4/address/my_solution.rb

https://github.com/SilverFox70/phase-0/blob/master/week-4/math/my_solution.rb

=end


text:
(function() {
  'use strict';
  var app;

  app = angular.module("Chutter");

  app.controller("commentsPageCtrl", [
    "$scope", "Comments", "Post", "Page", "PostService", "$mdBottomSheet", "CommentResource", "MediaPlayer", "$stateParams", function($scope, Comments, Post, Page, PostService, $mdBottomSheet, CommentResource, MediaPlayer, $stateParams) {
      this.page = Page;
      this.post = Post;
      if ($stateParams.network) {
        this.applicationSectionNamespace = "network_frontpage";
      } else {
        this.applicationSectionNamespace = "frontpage";
      }
      this.postService = PostService;
      this.comments = Comments;
      this.resource = CommentResource;
      this.mediaPlayer = MediaPlayer;
      return this;
    }
  ]);

  app.controller("commentListCtrl", [
    "$scope", "$mdBottomSheet", "CommentResource", "MediaPlayer", "$rootScope", "$state", function($scope, $mdBottomSheet, CommentResource, MediaPlayer, $rootScope, $state) {
      this.post = $scope.ctrl.post;
      this.comments = $scope.ctrl.comments;
      this.user = $rootScope.user;
      this.resource = CommentResource;
      this.mediaPlayer = MediaPlayer;
      this.children = function(comment) {
        comment.loadingChildren = true;
        return CommentResource.children({
          id: comment.id
        }).$promise.then(function(data) {
          comment.loadingChildren = false;
          if (_.isEmpty(comment.children)) {
            comment.compileElementForFirstChild();
            return comment.children = data;
          } else {
            return comment.children = data.concat(comment.children);
          }
        });
      };
      this.reply = function(parentComment) {
        if ($scope.user && $scope.user.id) {
          return $mdBottomSheet.show({
            templateUrl: '/partials/shared/comments/replyPanel.html',
            controller: "replyCtrl",
            disableParentScroll: true,
            locals: {
              post: this.post,
              parentComment: parentComment,
              comments: this.comments
            },
            preserveScope: true,
            parent: angular.element(document.body),
            clickOutsideToClose: true
          });
        } else {
          return $state.go("register.welcome");
        }
      };
      this.edit = function(comment) {
        return $mdBottomSheet.show({
          templateUrl: '/partials/shared/comments/editPanel.html',
          disableParentScroll: true,
          locals: {
            comment: comment
          },
          preserveScope: true,
          parent: angular.element(document.body),
          clickOutsideToClose: true
        });
      };
      this.updateVote = function(comment, vote) {
        var delta;
        comment.vote = parseInt(comment.vote) || 0;
        comment.points = parseInt(comment.points) || 0;
        if (comment.vote === vote) {
          vote = 0;
        }
        delta = vote - comment.vote;
        comment.vote = vote;
        comment.points += delta;
        return CommentResource.vote({
          id: comment.id,
          vote: vote
        });
      };
      return this;
    }
  ]);

}).call(this);


text:
<?php

/**
 * Swaggy Jenkins
 * PHP version 7.4
 *
 * @package OpenAPIServer
 * @author  OpenAPI Generator team
 * @link    https://github.com/openapitools/openapi-generator
 */

/**
 * Jenkins API clients generated from Swagger / Open API specification
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 * Generated by: https://github.com/openapitools/openapi-generator.git
 */

/**
 * NOTE: This class is auto generated by the openapi generator program.
 * https://github.com/openapitools/openapi-generator
 * Please update the test case below to test the model.
 */
namespace OpenAPIServer\Model;

use PHPUnit\Framework\TestCase;
use OpenAPIServer\Model\FreeStyleBuild;

/**
 * FreeStyleBuildTest Class Doc Comment
 *
 * @package OpenAPIServer\Model
 * @author  OpenAPI Generator team
 * @link    https://github.com/openapitools/openapi-generator
 *
 * @coversDefaultClass \OpenAPIServer\Model\FreeStyleBuild
 */
class FreeStyleBuildTest extends TestCase
{

    /**
     * Setup before running any test cases
     */
    public static function setUpBeforeClass(): void
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp(): void
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown(): void
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass(): void
    {
    }

    /**
     * Test "FreeStyleBuild"
     */
    public function testFreeStyleBuild()
    {
        $testFreeStyleBuild = new FreeStyleBuild();
        $namespacedClassname = FreeStyleBuild::getModelsNamespace() . '\\FreeStyleBuild';
        $this->assertSame('\\' . FreeStyleBuild::class, $namespacedClassname);
        $this->assertTrue(
            class_exists($namespacedClassname),
            sprintf('Assertion failed that "%s" class exists', $namespacedClassname)
        );
        $this->markTestIncomplete(
            'Test of "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "class"
     */
    public function testPropertyClass()
    {
        $this->markTestIncomplete(
            'Test of "class" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "number"
     */
    public function testPropertyNumber()
    {
        $this->markTestIncomplete(
            'Test of "number" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "url"
     */
    public function testPropertyUrl()
    {
        $this->markTestIncomplete(
            'Test of "url" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "actions"
     */
    public function testPropertyActions()
    {
        $this->markTestIncomplete(
            'Test of "actions" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "building"
     */
    public function testPropertyBuilding()
    {
        $this->markTestIncomplete(
            'Test of "building" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "description"
     */
    public function testPropertyDescription()
    {
        $this->markTestIncomplete(
            'Test of "description" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "displayName"
     */
    public function testPropertyDisplayName()
    {
        $this->markTestIncomplete(
            'Test of "displayName" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "duration"
     */
    public function testPropertyDuration()
    {
        $this->markTestIncomplete(
            'Test of "duration" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "estimatedDuration"
     */
    public function testPropertyEstimatedDuration()
    {
        $this->markTestIncomplete(
            'Test of "estimatedDuration" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "executor"
     */
    public function testPropertyExecutor()
    {
        $this->markTestIncomplete(
            'Test of "executor" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "fullDisplayName"
     */
    public function testPropertyFullDisplayName()
    {
        $this->markTestIncomplete(
            'Test of "fullDisplayName" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "id"
     */
    public function testPropertyId()
    {
        $this->markTestIncomplete(
            'Test of "id" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "keepLog"
     */
    public function testPropertyKeepLog()
    {
        $this->markTestIncomplete(
            'Test of "keepLog" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "queueId"
     */
    public function testPropertyQueueId()
    {
        $this->markTestIncomplete(
            'Test of "queueId" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "result"
     */
    public function testPropertyResult()
    {
        $this->markTestIncomplete(
            'Test of "result" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "timestamp"
     */
    public function testPropertyTimestamp()
    {
        $this->markTestIncomplete(
            'Test of "timestamp" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "builtOn"
     */
    public function testPropertyBuiltOn()
    {
        $this->markTestIncomplete(
            'Test of "builtOn" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test attribute "changeSet"
     */
    public function testPropertyChangeSet()
    {
        $this->markTestIncomplete(
            'Test of "changeSet" property in "FreeStyleBuild" model has not been implemented yet.'
        );
    }

    /**
     * Test getOpenApiSchema static method
     * @covers ::getOpenApiSchema
     */
    public function testGetOpenApiSchema()
    {
        $schemaArr = FreeStyleBuild::getOpenApiSchema();
        $this->assertIsArray($schemaArr);
    }
}


text:
require('../public/colorbox.css');
require('jquery-colorbox/jquery.colorbox-min');


text:
layout: post
title: step daddy
titleinfo: pornvd
desc: Watch step daddy. Pornhub is the ultimate xxx porn and sex site.
---

step daddy

Watch step daddy. Pornhub is the ultimate xxx porn and sex site.


text:
package com.commercetools.sunrise.framework.reverserouters.myaccount.mydetails;

import com.commercetools.sunrise.framework.reverserouters.LocalizedReverseRouter;
import com.google.inject.ImplementedBy;
import play.mvc.Call;

@ImplementedBy(DefaultMyPersonalDetailsReverseRouter.class)
public interface MyPersonalDetailsReverseRouter extends SimpleMyPersonalDetailsReverseRouter, LocalizedReverseRouter {

    default Call myPersonalDetailsPageCall() {
        return myPersonalDetailsPageCall(locale().toLanguageTag());
    }

    default Call myPersonalDetailsProcessCall() {
        return myPersonalDetailsProcessCall(locale().toLanguageTag());
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
016
017package net.ljcomputing.core.domain;
018
019import java.util.UUID;
020
021/**
022 * Abstract implementation of a domain class.
023 *
024 * @author James G. Willmore
025 *
026 */
027public abstract class AbstractDomain implements Node {
028
029        /** The Constant serialVersionUID. */
030        private static final long serialVersionUID = -5596912472711861850L;
031
032        /** The uuid. */
033        protected UUID uuid;
034
035        /*
036         * (non-Javadoc)
037         *
038         * @see net.ljcomputing.ecsr.domain.Domain#getUuid()
039         */
040        public UUID getUuid() {
041                return uuid;
042        }
043
044        /*
045         * (non-Javadoc)
046         *
047         * @see net.ljcomputing.ecsr.domain.Domain#setUuid(java.util.UUID)
048         */
049        public void setUuid(UUID uuid) {
050                this.uuid = uuid;
051        }
052
053        /*
054         * (non-Javadoc)
055         *
056         * @see net.ljcomputing.ecsr.domain.Domain#createUuid()
057         */
058        public void createUuid() {
059                this.uuid = UUID.randomUUID();
060        }
061
062        /* (non-Javadoc)
063         * @see java.lang.Object#toString()
064         */
065        @Override
066        public String toString() {
067                return "AbstractDomain [uuid=" + uuid + "]";
068        }
069}


text:
"use strict"

const config = require('config')
const cookieParser = require('cookie-parser')
const mongodb = require('mongodb')
const supertest = require('supertest')

const coursesDB = require('../../db/courses')
const rolesDB = require('../../db/roles')
const usersDB = require('../../../users/db')

describe('POST /courses/courses/:id/subjects', function () {
  let app
  let agent

  const user1 = {
    email: 'user1@user1',
    password: 'user1'
  }
  let userId1

  const user2 = {
    email: 'user2@user2',
    password: 'user2'
  }
  let userId2

  const course1 = {
    title: 'Course1',
    'i-am-author': true,
    author: user1.email
  }
  let courseId1

  const subject1 = {
    title: 'Subject1',
    author: user1.email
  }

  before(function() {
    const mongoHost = config.db.host || 'localhost'
    const mongoPort = config.db.port || '27017'
    const dbName = config.db.name || 'testero-testing'
    const mongoUrl = 'mongodb://' + mongoHost + ':' + mongoPort + '/' + dbName

    return mongodb.MongoClient.connect(mongoUrl, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
      .then(client => {
        const db = client.db(dbName)

        /**
         * @typedef {Object} Settings
         * @property {mongodb.Db} settings.mongoDBConnection
         * @type {Settings} settings
         */
        const settings = {
          mongoDBConnection: db
        }

        coursesDB.setup(settings)
        rolesDB.setup(settings)
        usersDB.setup(settings)

        app = require('../../../../app')(settings)
        app.use(cookieParser())

        agent = supertest.agent(app)

        return coursesDB.clear()
          .then(() => {
            return usersDB.clearUsers()
          })
          .then(() => {
            return usersDB.registerUser(user1)
          })
          .then(data => {
            userId1 = data.id
            return usersDB.registerUser(user2)
          })
          .then(data => {
            userId2 = data.id
          })
      })
  })

  context('Зарегистрирован некий курс', function() {
    before(function() {
      return coursesDB.add(course1)
        .then(data => {
          courseId1 = data.id;
      });
    });

    it('Пользователь не авторизован: отказ', function() {
	return agent
            .post('/courses/courses/' + course1.id + '/subjects')
            .send(subject1)
            .set('X-Requested-With', 'XMLHttpRequest')
            .expect('Content-Type', /application\/json/)
            .expect(200)
            .then(res => {
		res.body.should.have.property('status')
		res.body.status.should.equal(false, res.body.msg);
		res.body.should.not.have.property('subject');
            });
    });

    it('Пользователь авторизован, но не преподаватель: отказ', function() {
      return agent
        .post('/users/users/' + userId1 + '/auth')
        .send({password: user1.password})
        .set('X-Requested-With', 'XMLHttpRequest')
        .expect('Content-Type', /application\/json/)
        .expect(200)
        .then(res => {
          res.body.status.should.equal(true, res.body.msg);

          return agent
            .post('/courses/courses/' + courseId1 + '/subjects')
            .send(subject1)
            .set('X-Requested-With', 'XMLHttpRequest')
            .expect('Content-Type', /application\/json/)
            .expect(200)
            .then(res => {
              res.body.status.should.equal(false, res.body.msg);
              res.body.should.not.have.property('subject');
            });
        });
    });

    it('Пользователь авторизован и является преподавателем: успех.', function() {
      return rolesDB.assignRole(userId1, 'teacher')
        .then(() => {
          return agent
            .post('/courses/courses/' + courseId1 + '/subjects')
            .send(subject1)
            .set('X-Requested-With', 'XMLHttpRequest')
            .expect('Content-Type', /application\/json/)
            .expect(200)
            .then(res => {
              res.body.status.should.equal(true, res.body.msg);
              res.body.should.have.property('subject');
            })
        })
    })

    it('Не задана тема: отказ', function() {
      return agent
        .post('/courses/courses/' + courseId1 + '/subjects')
        .send({})
        .set('X-Requested-With', 'XMLHttpRequest')
        .expect('Content-Type', /application\/json/)
        .expect(200)
        .then(res => {
          res.body.status.should.equal(false, res.body.msg)
        });
    });

    it('Пользователь преподаватель, но не автор курса: отказ', function() {
      return agent
        .delete('/users/users/' + userId1 + '/auth')
        .set('X-Requested-With', 'XMLHttpRequest')
        .expect('Content-Type', /application\/json/)
        .expect(200)
        .then(res => {
          res.body.status.should.equal(true, res.body.msg);

          return rolesDB.assignRole(userId2, 'teacher')
            .then(() => {
              return agent
                .post('/users/users/' + userId2 + '/auth')
                .send({password: user2.password})
                .set('X-Requested-With', 'XMLHttpRequest')
                .expect('Content-Type', /application\/json/)
                .expect(200)
                .then(res => {
                  res.body.status.should.equal(true, res.body.msg);

                  return agent
                    .post('/courses/courses/' + courseId1 + '/subjects')
                    .send(subject1)
                    .set('X-Requested-With', 'XMLHttpRequest')
                    .expect('Content-Type', /application\/json/)
                    .expect(200)
                    .then(res => {
                      res.body.status.should.equal(false, res.body.msg);
                      res.body.should.not.have.property('subject');
                    });
                })
            })
        })
    })
  });

  context('Нет ни одного курса', function() {
    before(function() {
      return coursesDB.clear()
    })

    it('Попытка добавить к несуществующему курсу тему', function() {
      return agent
        .post('/courses/courses/719825791875/subjects')
        .send(subject1)
        .set('X-Requested-With', 'XMLHttpRequest')
        .expect('Content-Type', /application\/json/)
        .expect(200)
        .then(res => {
          res.body.status.should.equal(false, res.body.msg);
          res.body.should.not.have.property('subject');
        });
    });
  })

  after(function() {
    return usersDB.clearUsers()
  })
})


text:
<Type Name="IDataSource" FullName="Xamarin.Forms.Pages.IDataSource">
  <TypeSignature Language="C#" Value="public interface IDataSource" />
  <TypeSignature Language="ILAsm" Value=".class public interface auto ansi abstract IDataSource" />
  <AssemblyInfo>
    <AssemblyName>Xamarin.Forms.Pages</AssemblyName>
    <AssemblyVersion>1.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Interfaces />
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="Data">
      <MemberSignature Language="C#" Value="public System.Collections.Generic.IReadOnlyList<Xamarin.Forms.Pages.IDataItem> Data { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class System.Collections.Generic.IReadOnlyList`1<class Xamarin.Forms.Pages.IDataItem> Data" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Collections.Generic.IReadOnlyList<Xamarin.Forms.Pages.IDataItem></ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="IsLoading">
      <MemberSignature Language="C#" Value="public bool IsLoading { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance bool IsLoading" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Item">
      <MemberSignature Language="C#" Value="public object this[string key] { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance object Item(string)" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Object</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="key" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="key">To be added.</param>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="MaskedKeys">
      <MemberSignature Language="C#" Value="public System.Collections.Generic.IEnumerable<string> MaskedKeys { get; }" />
      <MemberSignature Language="ILAsm" Value=".property instance class System.Collections.Generic.IEnumerable`1<string> MaskedKeys" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Collections.Generic.IEnumerable<System.String></ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="MaskKey">
      <MemberSignature Language="C#" Value="public void MaskKey (string key);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void MaskKey(string key) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="key" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="key">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="UnmaskKey">
      <MemberSignature Language="C#" Value="public void UnmaskKey (string key);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig newslot virtual instance void UnmaskKey(string key) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>1.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="key" Type="System.String" />
      </Parameters>
      <Docs>
        <param name="key">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
<?php

namespace App\Console\Commands;

use App\Models\Site;
use App\Models\Page;
use App\Models\User;
use App\Models\LocalAPIClient;
use Illuminate\Console\Command;
use App\Models\Definitions\Block;
use Illuminate\Validation\ValidationException;

class FindLinks extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'astro:findlinks
								{--site-id=}
								{--search=}
								{--published}
								';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Find links in the given site which match the given link.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		$site = Site::find(intval($this->option('site-id')));
		$linkToSearch = $this->option('search');
		$linkToSearch = ltrim($linkToSearch, 'http://');
		$linkToSearch = ltrim($linkToSearch, 'https://');
		$published = $this->option('published');

		// check we have a site
		if (!$site) {
			$this->error("Site not found. Please specify the --site-id of the site you would like to search.");
			return;
		}

		// check we have a link
		if (empty($linkToSearch)) {
			$this->error("You need to specify the link you would like to find using --search= option.");
			return;
		}

		// search within the contents of each page
		$version = $published ? Page::STATE_PUBLISHED : Page::STATE_DRAFT;
		$urlsCount = 0;
		foreach ($site->pages($version)->get() as $page) {
			foreach ($page->revision->blocks as $regionName => $sections) {
				foreach ($sections as $sectionName => $section) {
					foreach ($section['blocks'] as $block) {
						$blockDefinitionId = "{$block['definition_name']}-v{$block['definition_version']}";
						$definition = Block::fromDefinitionFile(Block::locateDefinition($blockDefinitionId));
						$blockUrls = $this->findURLsInBlock($definition->fields, $block['fields'], $linkToSearch);
						if (!empty($blockUrls)) {
							$this->comment("Found matching URL" . (count($blockUrls) > 1 ? 's': ''). " in: {$page->full_path} - {$page->revision->title} \n region: {$regionName} \n section: {$section['name']} \n block: $blockDefinitionId");
							foreach ($blockUrls as $url) {
								$this->info(" - {$url}");
							}
							$urlsCount += count($blockUrls);
						}
					}
				}
			}
		}

		// search within the site's menu
		$menuVersion = $published ? 'menu_published' : 'menu_draft';
		if (isset($site->options[$menuVersion])) {
			$menuItems = $published ? $site->options[$menuVersion]['links'] : $site->options[$menuVersion];
			foreach ($menuItems as $menuItem) {
				if (strpos($menuItem['url'], $linkToSearch) !== false) {
					$this->comment("Found matching URL in menu item: {$menuItem['text']}");
					$this->info(" - {$menuItem['url']}");
					$urlsCount += 1;
				}
			}
		}

		// final words
		if (empty($urlsCount)) {
			$this->comment("No URLs found matching '{$linkToSearch}'");
		} else {
			$this->comment("Found a total of {$urlsCount} URL" . ($urlsCount > 1 ? 's': ''));
		}
	}

	/**
	 * Finds urls matching the given $search in a given block
	 * @param $fields - the definition of the block
	 * @param $data - the block's data
	 * @param $search - the piece of text to search for
	 */
	public function findURLsInBlock($fields, $data, $search)
	{
		$urls = [];
		foreach ($fields as $field) {
			$value = !empty($data[$field['name']]) ? $data[$field['name']] : null;
			if ($value) {
				switch ($field['type']) {
					case 'group':
						$urls = array_merge($urls, $this->findURLsInBlock($field['fields'], $value, $search));
						break;
					case 'collection':
						foreach ($value as $item) {
							$urls = array_merge($urls, $this->findURLsInBlock($field['fields'], $item, $search));
						}
						break;
					default:
						if (is_array($value)) {
							$value = print_r($value, true);
						}
						if (preg_match_all('/(http|https):\/\/[^\s\'"]+/', $value, $matches)) {
							foreach ($matches[0] as $match) {
								if (strpos($match, $search) !== false) {
									$urls[] = $match;
								}
							}
						}
						break;
				}
			}
		}
		return $urls;
	}
}


text:
package org.araqne.logdb.cep.script;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.araqne.api.Script;
import org.araqne.api.ScriptArgument;
import org.araqne.api.ScriptContext;
import org.araqne.api.ScriptUsage;
import org.araqne.logdb.cep.EventClock;
import org.araqne.logdb.cep.EventClockItem;
import org.araqne.logdb.cep.EventContextService;
import org.araqne.logdb.cep.EventContextStorage;
import org.araqne.logdb.cep.EventKey;

public class CepScript implements Script {
	private ScriptContext context;

	private EventContextService eventContextService;

	public CepScript(EventContextService eventContextService) {
		this.eventContextService = eventContextService;
	}

	@Override
	public void setScriptContext(ScriptContext context) {
		this.context = context;
	}

	@ScriptUsage(description = "set clock time manually", arguments = {
			@ScriptArgument(name = "host", type = "string", description = "clock host"),
			@ScriptArgument(name = "time", type = "string", description = "yyyyMMddHHmmss format") })
	public void setClock(String[] args) {
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String host = args[0];
		Date d = df.parse(args[1], new ParsePosition(0));
		if (d == null) {
			context.println("invalid time, follow yyyyMMddHHmmss format");
			return;
		}

		EventContextStorage storage = getEventStorage();
		EventClock<? extends EventClockItem> clock = storage.getClock(host);
		if (clock == null) {
			context.println("clock not found");
			return;
		}

		clock.setTime(d.getTime(), true);
		context.println("set");
	}

	public void clearContexts(String[] args) {
		EventContextStorage storage = getEventStorage();
		storage.clearContexts();
		context.println("completed");
	}

	public void clearClocks(String[] args) {
		EventContextStorage storage = getEventStorage();
		storage.clearClocks();
		context.println("completed");
	}

	@ScriptUsage(description = "print external clocks", arguments = {
			@ScriptArgument(name = "host", type = "string", description = "clock host"),
			@ScriptArgument(name = "queue type", type = "string", description = "expire or timeout") })
	public void clockQueue(String[] args) {
		String host = args[0];
		String queueType = args[1];

		EventContextStorage storage = getEventStorage();
		EventClock<? extends EventClockItem> clock = storage.getClock(host);
		if (clock == null) {
			context.println("clock not found");
			return;
		}

		if (!queueType.equals("timeout") && !queueType.equals("expire")) {
			context.println("invalid queue type");
			return;
		}

		context.println("Event Clock Queue (" + queueType + ")");
		context.println("---------------------------");

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		if (queueType.equals("timeout")) {
			for (EventClockItem item : clock.getTimeoutContexts()) {
				context.println("timeout [" + df.format(item.getTimeoutTime()) + "] " + item.getKey());
			}

		} else if (queueType.equals("expire")) {
			for (EventClockItem item : clock.getExpireContexts()) {
				context.println("expire [" + df.format(item.getExpireTime()) + "] " + item.getKey());
			}
		}
	}

	@ScriptUsage(description = "print external clocks", arguments = {
			@ScriptArgument(name = "offset", type = "int", description = "offset", optional = true),
			@ScriptArgument(name = "limit", type = "int", description = "limit", optional = true) })
	public void clocks(String[] args) {
		int offset = 0;
		int limit = 100;

		if (args.length > 0)
			offset = Integer.parseInt(args[0]);

		if (args.length > 1)
			limit = Integer.parseInt(args[1]);

		context.println("Event Clocks");
		context.println("-----------------");

		EventContextStorage storage = getEventStorage();
		List<String> hosts = new ArrayList<String>(storage.getHosts());
		List<String> page = hosts.subList(Math.min(offset, hosts.size()), Math.min(offset + limit, hosts.size()));

		for (String host : page) {
			EventClock<? extends EventClockItem> clock = storage.getClock(host);
			context.println(clock);
		}

		context.println("total " + hosts.size() + " clocks");
	}

	@ScriptUsage(description = "print contexts", arguments = {
			@ScriptArgument(name = "offset", type = "int", description = "offset", optional = true),
			@ScriptArgument(name = "limit", type = "int", description = "limit", optional = true) })
	public void contexts(String[] args) {
		int offset = 0;
		int limit = 100;

		if (args.length > 0)
			offset = Integer.parseInt(args[0]);

		if (args.length > 1)
			limit = Integer.parseInt(args[1]);

		context.println("Event Contexts");
		context.println("-----------------");

		EventContextStorage storage = getEventStorage();
		Iterator<EventKey> itr = storage.getContextKeys();
		int size = 0;
		while (itr.hasNext()) {
			EventKey key = itr.next();

			if (size < offset) {
				size++;
				continue;
			}

			if (limit + offset > size)
				context.println(key);

			size++;
		}

		context.println("total " + size + " contexts");
	}

	private EventContextStorage getEventStorage() {
		return eventContextService.getDefaultStorage();
	}
}


text:
from django.shortcuts import render,render_to_response,redirect
from django.views.generic import ListView,DetailView
from django.contrib.auth import authenticate, login,logout
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.db.models import Q
from .forms import *
from .models import *
import datetime
# Create your views here.

class IndexView(DetailView):
	def get(self,request):
		context_dict = {}
		_posts = Post.objects.all()[:10]
		context_dict['posts'] = _posts
		return render(request,'index.tpl',context_dict)

class Blog(DetailView):
	def get(self,request):
		render(request,'blog_template.tpl')

class SignUpView(DetailView):
	def get(self,request):
		form = UserForm()
		return render(request,'users/signup.tpl',{'form':form})

	def post(sefl,request):
		form = UserForm(request.POST)
		if form.is_valid():
			user = form.save(commit=False)
			user.set_password(user.password)
			user.save()
			return HttpResponseRedirect(reverse('login'))
		return render(request,'users/signup.tpl',{'form':form})

class LoginView(DetailView):
	def get(self,request):
		print request.user
		error = None
		if 'error' in request.session:
			print request.session['error']
			error = request.session['error']
			del request.session['error']
		return render(request,'users/login.tpl',{'error':error})

	def post(self,request):
		error = None
		email = request.POST['username']
		password = request.POST['password']
		try:
			_U = User.objects.get(email=email)
			user = authenticate(username=_U.username, password=password)
			if user:
				if user.is_active:
					login(request,user)
					return HttpResponseRedirect(reverse('welcome'))
				else:
					request.session['error'] = "Sorry your account is disabled"
			else:
				request.session['error'] = "Password inccorect"
		except User.DoesNotExist:
				request.session['error'] = "Email does not exists"
		return HttpResponseRedirect(reverse('login'))

class LogOutView(DetailView):
	def get(self,request,next='/'):
			if request.user.is_authenticated():
				logout(request)
			return redirect(next)

class WelComeView(DetailView):
	@method_decorator(login_required(login_url='/login'))
	def get(self,request):
		return render(request,'welcome.tpl')

class PostView(DetailView):
	@method_decorator(login_required(login_url='/login'))
	def get(self,request):
		context_dict = {}
		form = PostForm()

		context_dict['form'] = form

		return render(request,'newpost_template.tpl',context_dict)

	@method_decorator(login_required(login_url='/login'))
	def post(self,request):
		context_dict = {}

		form = PostForm(request.POST)
		# import ipdb; ipdb.set_trace()
		if form.is_valid():
			post = form.save(commit=False)
			post.author_id = request.user
			post.permalink = post.title
			post.publication_date = datetime.datetime.now()

			if 'tag_id' in request.POST['tag_id']:
				post.tag_id = Tag.objects.filter(
					Q(name__in=map(lambda x : x.lower(),request.POST['tag_id'].split())))
			post.save()
			return HttpResponseRedirect(reverse('index'))
		context_dict['form'] = form

		return render(request,'newpost_template.tpl',context_dict)

class CommentView(DetailView):

	def get(self,request,permalink):
		context_dict = {}
		try:
			post = Post.objects.get(permalink=permalink)
			form = CommentForm()
			context_dict['post'] = post
			context_dict['form'] = form

			return render(request,'entry_template.tpl',context_dict)
		except Post.DoesNotExist:
			return HttpResponseRedirect(reverse('404'))

	def post(self,request,permalink):
		form = CommentForm(request.POST)
		if form.is_valid():
			comment = form.save()
			post = Post.objects.get(permalink=permalink)
			post.comment_id.add(comment)
			post.save()
		return self.get(request,permalink)


text:
package com.example.swipebackactivity.app;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;

import com.example.swipebackactivity.R;
import com.example.swipebackactivity.SwipeBackLayout;
import com.example.swipebackactivity.Utils;

public class SwipeBackActivityHelper {
    private Activity mActivity;

    private SwipeBackLayout mSwipeBackLayout;

    public SwipeBackActivityHelper(Activity activity) {
        mActivity = activity;
    }

    public void onActivityCreate() {
        mActivity.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mSwipeBackLayout = (SwipeBackLayout) LayoutInflater.from(mActivity).inflate(
                R.layout.swipeback_layout, null);
        mSwipeBackLayout.addSwipeListener(new SwipeBackLayout.SwipeListener() {
            @Override
            public void onScrollStateChange(int state, float scrollPercent) {
            }

            @Override
            public void onEdgeTouch(int edgeFlag) {
                Utils.convertActivityToTranslucent(mActivity);
            }

            @Override
            public void onScrollOverThreshold() {

            }
        });
    }

    public void onPostCreate() {
        mSwipeBackLayout.attachToActivity(mActivity);
    }

    public View findViewById(int id) {
        if (mSwipeBackLayout != null) {
            return mSwipeBackLayout.findViewById(id);
        }
        return null;
    }

    public SwipeBackLayout getSwipeBackLayout() {
        return mSwipeBackLayout;
    }
}


text:
package org.apache.solr.common.util;

import java.util.Collections;
import java.util.Set;

import java.util.concurrent.TimeUnit;

import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetryUtil {
  private static final Logger log = LoggerFactory.getLogger(RetryUtil.class);

  public static interface RetryCmd {
    public void execute() throws Throwable;
  }

  public static interface BooleanRetryCmd {
    public boolean execute();
  }

  public static void retryOnThrowable(Class clazz, long timeoutms, long intervalms, RetryCmd cmd) throws Throwable {
    retryOnThrowable(Collections.singleton(clazz), timeoutms, intervalms, cmd);
  }

  public static void retryOnThrowable(Set<Class> classes, long timeoutms, long intervalms, RetryCmd cmd) throws Throwable {
    long timeout = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeoutms, TimeUnit.MILLISECONDS);
    while (true) {
      try {
        cmd.execute();
      } catch (Throwable t) {
        if (isInstanceOf(classes, t) && System.nanoTime() < timeout) {
          log.info("Retry due to Throwable, " + t.getClass().getName() + " " + t.getMessage());
          Thread.sleep(intervalms);
          continue;
        }
        throw t;
      }
      // success
      break;
    }
  }

  private static boolean isInstanceOf(Set<Class> classes, Throwable t) {
    for (Class c : classes) {
      if (c.isInstance(t)) {
        return true;
      }
    }
    return false;
  }

  public static void retryOnBoolean(long timeoutms, long intervalms, BooleanRetryCmd cmd) {
    long timeout = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeoutms, TimeUnit.MILLISECONDS);
    while (true) {
      boolean resp = cmd.execute();
      if (!resp && System.nanoTime() < timeout) {
        continue;
      } else if (System.nanoTime() >= timeout) {
        throw new SolrException(ErrorCode.SERVER_ERROR, "Timed out while retrying operation");
      }

      // success
      break;
    }
  }

}


text:
/* jshint node: true */
'use strict';

var path = require('path');

// default reload css extensions
var styleExtensions = ['css', 'scss', 'sass', 'less', 'styl'];
var reloadCssPattern = new RegExp('\.(' + styleExtensions.join('|') + ')$');

var noop = function(){};

module.exports = function StylesReloader(options){
  var options = options;
  var fsWatcher = options.watcher;
  var ui = options.ui;
  var _isRunning = false;
  var lsProxy = options.ssl ? require('https') : require('http');

  // build app style pattern
  var appStylePath = path.join(options.project.root, 'app', 'styles', '*');
  var appStylePattern = new RegExp('^' + appStylePath);
  var appStyleResource = options.project.pkg.name + '.css';

  // livereload hostname
  var liveReloadHostname = [
    (options.ssl ? 'https://' :'http://'),
    (options.liveReloadHost || options.host || 'localhost'),
    ':',
    options.liveReloadPort
  ].join('');

  function shouldReload(filePath){
    return filePath.match(reloadCssPattern);
  };

  function getReloadResource(filePath){
    return filePath.match(appStylePattern) ? appStyleResource : 'vendor.css';
  };

  function fileDidChange(results){
    var filePath = results.filePath || '';

    // notify livereload server if needed
    if (shouldReload(filePath)){
      var reloadResource = getReloadResource(filePath);
      ui.writeLine('Reloading ' + reloadResource + ' only');
      lsProxy.get(liveReloadHostname + '/changed?files=' + reloadResource)
          .on('error', noop);
    }
  };

  function mergeReloadFilters(){
    options.project.liveReloadFilterPatterns.push(reloadCssPattern);
  };

  return {

    run: function(){
      if (!options.liveReload) {
        ui.writeLine('StylesReloader is disabled');
        return;
      }

      if (this.isRunning()){
        return;
      }

      ui.writeLine('StylesReloader watches ' + styleExtensions.join('|'));
      if (fsWatcher) {
        mergeReloadFilters();
        fsWatcher.on('change', fileDidChange.bind(this));
        _isRunning = !_isRunning;
      }
    },

    isRunning: function(){
      return _isRunning;
    }
  };
};


text:
<?php

namespace Aws\S3\Exception;

/**
 * The specified method is not allowed against this resource.
 */
class MethodNotAllowedException extends S3Exception {}


text: <link rel="shortcut icon" href="/img/favicon.ico" type="image/x-icon" />


text:
package com.sonova.difian.communication.chat;

public interface ChatManagerCallback
{
    void chatManagerStateChanged();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       					   http://www.springframework.org/schema/beans/spring-beans.xsd
       					   http://mybatis.org/schema/mybatis-spring
       					   http://mybatis.org/schema/mybatis-spring.xsd
       					   http://www.springframework.org/schema/context
       					   http://www.springframework.org/schema/context/spring-context.xsd
       					   http://www.springframework.org/schema/tx
       					   http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- 加载资源文件: 数据库连接文件 -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:/properties/jdbc.properties"/>
	</bean>
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${driver}"/>
		<property name="url" value="${url}"/>
		<property name="username" value="${username}"/>
		<property name="password" value="${password}"/>

	</bean>
	<!-- 配置 mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<!-- 扫描entity -->
		<property name="typeAliasesPackage" value="com.starjobs.pojo"/>
		<!-- 注册mapper.xm -->
	<!-- 	<property name="mapperLocations" value="classpath*:/mapper/*.xml"/> -->
	<property name="configLocation" value="classpath:spring-mybatis/mybatis-config.xml" />
	</bean>

	<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
	<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.starjobs.mapper"/>
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
	</bean>

	<!-- 添加事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!-- 采用注解方式管理事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>


text:
@interface CMAAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


text:
	errorMessage = '';

	function validateDeleteFaq(id) {
		areYouSure = confirm("Are you sure?");
		if (areYouSure) {
			document.editFaqForm.faqToDelete.value = id;
			document.editFaqForm.submit();
		}
	}

	function validateUpdateFaqs() {
		errorMessage = '';
		if (document.getElementById('question_add').value && !document.getElementById('answer_add').value) errorMessage += "Please specify an answer.\n";
		if (document.getElementById('answer_add').value && !document.getElementById('question_add').value) errorMessage += "Please specify a question.\n";
		if (errorMessage) alert(errorMessage);
		else document.editFaqForm.submit();
	}

	function validateDeleteFaqSection(id) {
		areYouSure = confirm("Are you sure?");
		if (areYouSure) {
			document.editFaqSectionForm.faqSectionToDelete.value = id;
			document.editFaqSectionForm.submit();
		}
	}


text:
> Allow parsing of `export default from`.

## Installation

```sh
npm install --save-dev @babel/plugin-syntax-export-default-from
```

## Usage

### Via `.babelrc` (Recommended)

**.babelrc**

```json
{
  "plugins": ["@babel/plugin-syntax-export-default-from"]
}
```

### Via CLI

```sh
babel --plugins @babel/plugin-syntax-export-default-from script.js
```

### Via Node API

```javascript
require("@babel/core").transform("code", {
  plugins: ["@babel/plugin-syntax-export-default-from"]
});
```


text:
bdir = java.lang.System.getProperty( "jbundler.basedir" )
jfile = java.lang.System.getProperty( "jbundler.jarfile" )
gfile = java.lang.System.getProperty( "jbundler.gemfile" )
jworkdir = java.lang.System.getProperty( "jbundler.workdir" )

basedir( bdir )
if basedir != bdir
  # older maven-tools needs this
  self.instance_variable_set( :@basedir, bdir )
end

( 0..(java.lang.System.getProperty( "jbundler.jars.size" ).to_i - 1) ).each do |i|
  coord = java.lang.System.getProperty( "jbundler.jars.#{i}" )
  dependency_artifact( Maven::Tools::Artifact.from_coordinate( coord.to_s ) )
end

jarfile( jfile )

build do
  directory = jworkdir
end

properties( 'project.build.sourceEncoding' => 'utf-8',
            'tesla.dump.readOnly' => true,
            'tesla.dump.pom' => 'tree.pom.xml' )

plugin( :dependency, '2.8',
        :includeTypes => 'jar',
        :outputAbsoluteArtifactFilename => true,
        :outputFile => java.lang.System.getProperty( "jbundler.outputFile" ) )


text:
require 'spec_helper'

describe ApiController do

end


text:
package org.basex.core.locks;

import java.util.*;

import org.basex.util.*;
import org.basex.util.list.*;

/**
 * List with strings that serve as lock keys.
 *
 * @author BaseX Team 2005-22, BSD License
 * @author Christian Gruen
 */
public final class LockList implements Iterable<String> {
  /** Local locks. */
  private final StringList list = new StringList(0);
  /** Global locking flag. */
  private boolean global;

  /**
   * Adds a local lock if no global lock has been added.
   * @param lock lock to be added
   * @return self reference
   */
  public LockList add(final String lock) {
    if(!global) list.addUnique(lock);
    return this;
  }

  /**
   * Indicates if local locks exist.
   * @return result of check
   */
  public boolean local() {
    return !list.isEmpty();
  }

  /**
   * Sets a global lock. All existing and following local locks will be ignored.
   */
  public void addGlobal() {
    global = true;
    list.reset();
  }

  /**
   * Resets the lock list.
   */
  public void reset() {
    global = false;
    list.reset();
  }

  /**
   * Indicates if a global lock exists.
   * @return result of check
   */
  public boolean global() {
    return global;
  }

  /**
   * Indicates if any lock exists.
   * @return result of check
   */
  public boolean locking() {
    return global() || local();
  }

  /**
   * Adds another lock list. A global lock will be adopted.
   * @param locks lock list
   */
  public void add(final LockList locks) {
    if(!global) {
      if(locks.global) {
        addGlobal();
      } else {
        for(final String lock : locks.list) list.addUnique(lock);
      }
    }
  }

  /**
   * Removes all locks from the specified list.
   * @param locks lock list
   */
  public void remove(final LockList locks) {
    list.removeAll(locks.list);
  }

  /**
   * Returns the element at the specified position.
   * @param index element index
   * @return element
   */
  public String get(final int index) {
    return list.get(index);
  }

  /**
   * Checks if the specified lock is found in the list.
   * @param lock lock to be found
   * @return result of check
   */
  public boolean contains(final String lock) {
    return list.contains(lock);
  }

  /**
   * Returns the number of local locks.
   * @return number of local locks
   */
  public int size() {
    return list.size();
  }

  /**
   * Finishes the lock list.
   * Locks of type {@link Locking#COLLECTION} and {@link Locking#CONTEXT} will be replaced with the
   * name of the current database, if it exists, or deleted otherwise.
   * The resulting list will be sorted, and duplicates will be removed.
   * @param name name of currently opened database
   */
  public void finish(final String name) {
    for(int l = 0; l < list.size(); l++) {
      final String lock = list.get(l);
      if(Strings.eq(lock, Locking.COLLECTION, Locking.CONTEXT)) {
        if(name != null) list.set(l, name);
        else list.remove(l--);
      }
    }
    list.sort();
  }

  @Override
  public Iterator<String> iterator() {
    return list.iterator();
  }

  @Override
  public String toString() {
    return global ? "(global)" : list.isEmpty() ? "(none)" : String.join(",", list.toArray());
  }
}


text:
<?php
/***********************************************************
  ..

  Reference:
  http://agiletoolkit.org/doc/ref

==ATK4===================================================
   This file is part of Agile Toolkit 4
    http://agiletoolkit.org/

   (c) 2008-2013 Agile Toolkit Limited <info@agiletoolkit.org>
   Distributed under Affero General Public License v3 and
   commercial license.

   See LICENSE or LICENSE_COM for more information
=====================================================ATK4=*/
class HtmlElement extends View_HtmlElement {}


text:
/**
 * Handles opening of and synchronization with the reveal.js
 * notes window.
 *
 * Handshake process:
 * 1. This window posts 'connect' to notes window
 *    - Includes URL of presentation to show
 * 2. Notes window responds with 'connected' when it is available
 * 3. This window proceeds to send the current presentation state
 *    to the notes window
 */
var RevealNotes = (function() {

  var notesPopup = null;

  function openNotes( notesFilePath ) {

    if (notesPopup && !notesPopup.closed) {
      notesPopup.focus();
      return;
    }

    if( !notesFilePath ) {
      var jsFileLocation = document.querySelector('script[src$="notes.js"]').src;  // this js file path
      jsFileLocation = jsFileLocation.replace(/notes\.js(\?.*)?$/, '');   // the js folder path
      notesFilePath = jsFileLocation + 'notes.html';
    }

    notesPopup = window.open( notesFilePath, 'reveal.js - Notes', 'width=1100,height=700' );

    if( !notesPopup ) {
      alert( 'Speaker view popup failed to open. Please make sure popups are allowed and reopen the speaker view.' );
      return;
    }

    /**
     * Connect to the notes window through a postmessage handshake.
     * Using postmessage enables us to work in situations where the
     * origins differ, such as a presentation being opened from the
     * file system.
     */
    function connect() {
      // Keep trying to connect until we get a 'connected' message back
      var connectInterval = setInterval( function() {
        notesPopup.postMessage( JSON.stringify( {
          namespace: 'reveal-notes',
          type: 'connect',
          url: window.location.protocol + '//' + window.location.host + window.location.pathname + window.location.search,
          state: Reveal.getState()
        } ), '*' );
      }, 500 );

      window.addEventListener( 'message', function( event ) {
        var data = JSON.parse( event.data );
        if( data && data.namespace === 'reveal-notes' && data.type === 'connected' ) {
          clearInterval( connectInterval );
          onConnected();
        }
        if( data && data.namespace === 'reveal-notes' && data.type === 'call' ) {
          callRevealApi( data.methodName, data.arguments, data.callId );
        }
      } );
    }

    /**
     * Calls the specified Reveal.js method with the provided argument
     * and then pushes the result to the notes frame.
     */
    function callRevealApi( methodName, methodArguments, callId ) {

      var result = Reveal[methodName].apply( Reveal, methodArguments );
      notesPopup.postMessage( JSON.stringify( {
        namespace: 'reveal-notes',
        type: 'return',
        result: result,
        callId: callId
      } ), '*' );

    }

    /**
     * Posts the current slide data to the notes window
     */
    function post( event ) {

      var slideElement = Reveal.getCurrentSlide(),
        notesElement = slideElement.querySelector( 'aside.notes' ),
        fragmentElement = slideElement.querySelector( '.current-fragment' );

      var messageData = {
        namespace: 'reveal-notes',
        type: 'state',
        notes: '',
        markdown: false,
        whitespace: 'normal',
        state: Reveal.getState()
      };

      // Look for notes defined in a slide attribute
      if( slideElement.hasAttribute( 'data-notes' ) ) {
        messageData.notes = slideElement.getAttribute( 'data-notes' );
        messageData.whitespace = 'pre-wrap';
      }

      // Look for notes defined in a fragment
      if( fragmentElement ) {
        var fragmentNotes = fragmentElement.querySelector( 'aside.notes' );
        if( fragmentNotes ) {
          notesElement = fragmentNotes;
        }
        else if( fragmentElement.hasAttribute( 'data-notes' ) ) {
          messageData.notes = fragmentElement.getAttribute( 'data-notes' );
          messageData.whitespace = 'pre-wrap';

          // In case there are slide notes
          notesElement = null;
        }
      }

      // Look for notes defined in an aside element
      if( notesElement ) {
        messageData.notes = notesElement.innerHTML;
        messageData.markdown = typeof notesElement.getAttribute( 'data-markdown' ) === 'string';
      }

      notesPopup.postMessage( JSON.stringify( messageData ), '*' );

    }

    /**
     * Called once we have established a connection to the notes
     * window.
     */
    function onConnected() {

      // Monitor events that trigger a change in state
      Reveal.addEventListener( 'slidechanged', post );
      Reveal.addEventListener( 'fragmentshown', post );
      Reveal.addEventListener( 'fragmenthidden', post );
      Reveal.addEventListener( 'overviewhidden', post );
      Reveal.addEventListener( 'overviewshown', post );
      Reveal.addEventListener( 'paused', post );
      Reveal.addEventListener( 'resumed', post );

      // Post the initial state
      post();

    }

    connect();

  }

  return {
    init: function() {

      if( !/receiver/i.test( window.location.search ) ) {

        // If the there's a 'notes' query set, open directly
        if( window.location.search.match( /(\?|\&)notes/gi ) !== null ) {
          openNotes();
        }

        // Open the notes when the 's' key is hit
        Reveal.addKeyBinding({keyCode: 83, key: 'S', description: 'Speaker notes view'}, function() {
          openNotes();
        } );

      }

    },

    open: openNotes
  };

})();

Reveal.registerPlugin( 'notes', RevealNotes );


text:
/*global module require exports*/
(function(){"use strict";
	exports.util = require('./util');
	exports.Widget = require('./Widget');
	exports.App = require('./App');
}).call(this);


text:
It just a bayes classifier using python.
It is very convenient to code using Python for science calculation(than c++ =-=)

### test data
I use some data from UCI dataset.

It can be donwloaded from [UCI dataset] (https://archive.ics.uci.edu/ml/datasets/Census+Income).

After download it,put them into a file named dataset so that program can read data from it.

Havefun !

## decision tree

## iris dataset for classification

just use deep learning for classification three classes of flowers from iris dataset
and you can get a proper result(accuracy:29/30) from testing, Before using code
well ,some thing you should konw list below.

 - loss function: using cross entropy loss function to calculate the difference probability distribution between the prediction and the real label

 - classifier: using softmax function to get the probability of each class

 - optimizier: using MSGD algorithm with momentum and learning rate decaying

 - training and testing dataset: 150 in all , 120 for training and the left for testing

 - activation function: ReLU function (I have tried to use tanh but the result was not great)

 - hidden units: The constrution of the neural network can be setted what as you like

## mnist dataset
The project mainly is used for handling image dataset,by using CNN neural network .
The nerual network(can also called by deep learning) has many layers that common used in this field.So you can learn many necessary tricks from the project if you want to be a data scientist(=-=)

The project has something you should know first listed below:

 - inference:the function aims to construte a graph layer by layer

 - layer: There are some layers like conv_layer , ReLU_layer , fully_connected_layer, maxpooling and softmax_layer and so on . You can know more from the code.

 - load data:Due to using MSGD ,you should get the samples by min_batch ,using next_batch() function to get data to feed the network for convenience

 - others:others in the project are like iris project. so omit them here

## Others:
If have others things to upload here ,I will add their information immediately


text:
<!DOCTYPE html>

        <title>TimePicker demos</title>
        <link href="/vendor/bootstrap/docs/assets/css/bootstrap.css" type="text/css" rel="stylesheet" />
        <link href="css/timepicker.css" type="text/css" rel="stylesheet" />

TimePicker demo

Simple

A timepicker instantiated with no options

                <input type="text" id="time1"/>

Custom intervals

A timepicker instantiated with 10 minute intervals

                <input type="text" id="time2"/>


text:
from ethel.wrappers.perlcritic import parse_perlcritic
from ethel.utils import run_command, cd
import os

def perlcritic(dsc, analysis):
    run_command(["dpkg-source", "-x", dsc, "source"])
    with cd('source'):
        out, err, ret = run_command([
            'perlcritic', '--brutal', '.', '--verbose',
            '%f:%l:%c %s    %p    %m\n'
        ])
        if ret == 1:
            raise Exception("Perlcritic had an internal error")

        failed = ret == 2
        for issue in parse_perlcritic(out.splitlines()):
            analysis.results.append(issue)

        return (analysis, out, failed)

def version():
    out, err, ret = run_command([ 'perlcritic', '--version' ])
    #TODO : check ret for perlcritic installation
    return ('perlcritic', out.strip())


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Kühner & Romagnesi, Fl. Analyt. Champ. Supér. (Paris) 457 (1953)

#### Original name
Russula puellaris var. intensior Cooke

### Remarks
null


text:
using Arch.CFramework.Utility;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace Arch.CFramework.Utility.Test
{
    ///
    ///This is a test class for CodeTimerTest and is intended
    ///to contain all CodeTimerTest Unit Tests
    ///
    [TestClass()]
    public class CodeTimerTest
    {
        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }
        ///
        ///A test for Time
        ///
        [TestMethod()]
        public void TimeTest()
        {
            //显示测试方法执行时间
            string name = "测试方法执行时间";
            //执行5次
            int iteration = 5;
            //准备计算方法Calculate
            CodeTimer.ActionDelegate action = Calculate;
            //计算Calculate执行5次的时间
            string actual = CodeTimer.Time(name, iteration, action);
            Assert.IsTrue(true, actual);
        }
        //示例方法
        public static void Calculate()
        {
            for (int i = 0; i < 100; i++)
                System.Threading.Thread.Sleep(10);
        }
    }
}
/*
---------计算结果---------
测试方法执行时间
Time Elapsed:	5,371ms
CPU Cycles:	0
Gen 0: 		0
Gen 1: 		0
Gen 2: 		0
*/


text:
package com.vaadin.tests.components.abstractcomponent;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.VaadinClasses;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.Component;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.LegacyWindow;

public class AllComponentTooltipTest extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        GridLayout layout = new GridLayout(5, 5);
        setContent(layout);
        for (Class<? extends Component> cls : VaadinClasses.getComponents()) {
            try {
                AbstractComponent c = (AbstractComponent) cls.newInstance();
                if (c instanceof LegacyWindow) {
                    continue;
                }

                c.setId(cls.getName());
                c.setCaption(cls.getName());
                c.setDescription(cls.getName());
                c.setWidth("100px");
                c.setHeight("100px");
                layout.addComponent(c);
                System.out.println("Added " + cls.getName());
            } catch (Exception e) {
                System.err.println("Could not instatiate " + cls.getName());
            }
        }
    }

    @Override
    protected String getTestDescription() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Integer getTicketNumber() {
        // TODO Auto-generated method stub
        return null;
    }

}


text:
package org.kaleidofoundry.core.store;

import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map.Entry;

import javax.ejb.Stateless;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.annotation.XmlElementWrapper;

import org.kaleidofoundry.core.store.model.FileStoreEntry;
import org.kaleidofoundry.core.store.model.ResourceHandlerEntity;
import org.kaleidofoundry.core.util.locale.LocaleFactory;

@Stateless(mappedName = "ejb/fs/manager")
@Path("/fs/")
public class FileStoreController {

   /** injected and used to handle security context */
   @Context
   SecurityContext securityContext;

   /** injected and used to handle URIs */
   @Context
   UriInfo uriInfo;

   /**
    * @return get the list of registered file store
    */
   @GET
   @XmlElementWrapper(name = "fs")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public List<FileStoreEntry> getStores() {
	List<FileStoreEntry> stores = new ArrayList<FileStoreEntry>();
	for (Entry<String, FileStore> storeEntry : FileStoreFactory.getRegistry().entrySet()) {
	   stores.add(new FileStoreEntry(storeEntry.getKey(), storeEntry.getValue().getBaseUri()));
	}
	return stores;
   }

   /**
    * fetch the content of a resource
    *
    * @param store
    * @param resource
    * @return resource content, with the right charset, mime type ....
    * @throws FileStoreNotFoundException
    * @throws ResourceNotFoundException
    * @throws ResourceException
    */
   @GET
   @Path("{store}/content/{resource}")
   @Produces(MediaType.APPLICATION_OCTET_STREAM)
   public Response getResourceContent(final @PathParam("store") String store, final @PathParam("resource") String resource) throws FileStoreNotFoundException,
	   ResourceNotFoundException, ResourceException {

	ResourceHandler rs = findFileStore(store).get(resource);
	return Response.ok(rs.getBytes()).type(rs.getMimeType()).location(URI.create(rs.getUri())).lastModified(new Date(rs.getLastModified()))
		.header(HttpHeaders.CONTENT_TYPE, rs.getMimeType() + "; " + rs.getCharset())
		// .cacheControl(CacheControl.valueOf(value))
		// .expires(date)
		.status(Status.OK).build();
   }

   /**
    * fetch the meta information of a resource
    *
    * @param store
    * @param resource
    * @return the resource meta info
    * @throws FileStoreNotFoundException
    * @throws ResourceNotFoundException
    * @throws ResourceException
    */
   @GET
   @Path("{store}/meta/{resource}")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public ResourceHandlerEntity getResourceMetaInfo(final @PathParam("store") String store, final @PathParam("resource") String resource)
	   throws FileStoreNotFoundException, ResourceNotFoundException, ResourceException {
	return toResourceHandlerEntity(findFileStore(store).get(resource));
   }

   /**
    * remove a resource
    *
    * @param store
    * @param resource
    * @throws FileStoreNotFoundException
    * @throws ResourceNotFoundException
    * @throws ResourceException
    */
   @DELETE
   @Path("{store}/{resource}")
   public void removeResource(final @PathParam("store") String store, final @PathParam("resource") String resource) throws FileStoreNotFoundException,
	   ResourceNotFoundException, ResourceException {
	findFileStore(store).remove(resource);
   }

   /**
    * find the store in the registry
    *
    * @param storeName
    * @return
    * @throws FileStoreNotFoundException
    */
   static FileStore findFileStore(String storeName) throws FileStoreNotFoundException {
	if (!FileStoreFactory.getRegistry().keySet().contains(storeName)) {
	   throw new FileStoreNotFoundException(storeName);
	} else {
	   return FileStoreFactory.getRegistry().get(storeName);
	}
   }

   /**
    * converter
    *
    * @param res
    * @return
    */
   static ResourceHandlerEntity toResourceHandlerEntity(ResourceHandler res) {
	Calendar calendar = new GregorianCalendar(LocaleFactory.getDefaultFactory().getCurrentLocale());
	calendar.setTimeInMillis(res.getLastModified());

	ResourceHandlerEntity facade = new ResourceHandlerEntity();
	facade.setUri(res.getUri());
	facade.setPath(res.getPath());
	facade.setMimeType(res.getMimeType());
	facade.setCharset(res.getCharset());
	facade.setSize(res.getLength());
	facade.setUpdatedDate(calendar.getTime());
	facade.setCreationDate(calendar.getTime());
	return facade;
   }
}


text:
const babel = require('babel-core');
const content = `
var React = require('react');

type FooProps = {
  a_number: number,
}

export default class extends React.Component<FooProps> {
}
`;

it('class-single-type-anon-test', () => {
  const res = babel.transform(content, {
    babelrc: false,
    presets: ['@babel/env', '@babel/react', '@babel/flow'],
    plugins: [
      '@babel/syntax-flow',
      require('../'),
      "@babel/plugin-proposal-class-properties"
    ],
  }).code;
  expect(res).toMatchSnapshot();
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ceské Houby 4-5: 677 (1922)

#### Original name
Polyporus fomentarius var. lineatus Velen.

### Remarks
null


text:
using System;

namespace Abp.Web.Models
{
    /// <summary>
    /// This class is used to create standard responses for AJAX requests.
    /// </summary>
    [Serializable]
    public class AjaxResponse<TResult>: AjaxResponseBase
    {
        /// <summary>
        /// The actual result object of AJAX request.
        /// It is set if <see cref="AjaxResponseBase.Success"/> is true.
        /// </summary>
        public TResult Result { get; set; }

        /// <summary>
        /// Creates an <see cref="AjaxResponse"/> object with <see cref="Result"/> specified.
        /// <see cref="AjaxResponseBase.Success"/> is set as true.
        /// </summary>
        /// <param name="result">The actual result object of AJAX request</param>
        public AjaxResponse(TResult result)
        {
            Result = result;
            Success = true;
        }

        /// <summary>
        /// Creates an <see cref="AjaxResponse"/> object.
        /// <see cref="AjaxResponseBase.Success"/> is set as true.
        /// </summary>
        public AjaxResponse()
        {
            Success = true;
        }

        /// <summary>
        /// Creates an <see cref="AjaxResponse"/> object with <see cref="AjaxResponseBase.Success"/> specified.
        /// </summary>
        /// <param name="success">Indicates success status of the result</param>
        public AjaxResponse(bool success)
        {
            Success = success;
        }

        /// <summary>
        /// Creates an <see cref="AjaxResponse"/> object with <see cref="AjaxResponseBase.Error"/> specified.
        /// <see cref="AjaxResponseBase.Success"/> is set as false.
        /// </summary>
        /// <param name="error">Error details</param>
        /// <param name="unAuthorizedRequest">Used to indicate that the current user has no privilege to perform this request</param>
        public AjaxResponse(ErrorInfo error, bool unAuthorizedRequest = false)
        {
            Error = error;
            UnAuthorizedRequest = unAuthorizedRequest;
            Success = false;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
	<testsuite tests="2" failures="0" time="0.050" name="package/name">
		<properties>
			<property name="go.version" value="1.0"></property>
		</properties>
		<testcase classname="name" name="TestOne" time="0.020"></testcase>
		<testcase classname="name" name="TestTwo" time="0.030"></testcase>
	</testsuite>
</testsuites>