text:
require 'spec_helper'
require 'cucumber/formatter/spec_helper'
require 'cucumber/formatter/html'
require 'nokogiri'
require 'cucumber/rb_support/rb_language'

module Cucumber
  module Formatter

    describe Html do
      extend SpecHelperDsl
      include SpecHelper

      RSpec::Matchers.define :have_css_node do |css, regexp|
        match do |doc|
          nodes = doc.css(css)
          nodes.detect{ |node| node.text =~ regexp }
        end
      end

      before(:each) do
        @out = StringIO.new
        @formatter = Html.new(step_mother, @out, {})
        step_mother.visitor = @formatter
      end

      it "should not raise an error when visiting a blank feature name" do
        lambda { @formatter.feature_name("Feature", "") }.should_not raise_error
      end

      describe "given a single feature" do
        before(:each) do
          run_defined_feature
          @doc = Nokogiri.HTML(@out.string)
        end

        describe "basic feature" do
          define_feature <<-FEATURE
            Feature: Bananas
              In order to find my inner monkey
              As a human
              I must eat bananas
          FEATURE

          it "should output a main container div" do
            @out.string.should =~ /\<div class="cucumber"\>/
          end
        end

        describe "with a comment" do
          define_feature <<-FEATURE
            # Healthy
            Feature: Foo
          FEATURE

          it { @out.string.should =~ /^\<!DOCTYPE/ }
          it { @out.string.should =~ /\<\/html\>$/ }
          it { @doc.should have_css_node('.feature .comment', /Healthy/) }
        end

        describe "with a tag" do
          define_feature <<-FEATURE
            @foo
            Feature: can't have standalone tag :)
          FEATURE

          it { @doc.should have_css_node('.feature .tag', /foo/) }
        end

        describe "with a narrative" do
          define_feature <<-FEATURE
            Feature: Bananas
              In order to find my inner monkey
              As a human
              I must eat bananas
          FEATURE

          it { @doc.should have_css_node('.feature h2', /Bananas/) }
          it { @doc.should have_css_node('.feature .narrative', /must eat bananas/) }
        end

        describe "with a background" do
          define_feature <<-FEATURE
            Feature: Bananas

            Background:
              Given there are bananas
          FEATURE

          it { @doc.should have_css_node('.feature .background', /there are bananas/) }
        end

        describe "with a scenario" do
          define_feature <<-FEATURE
          Feature: Banana party

            Scenario: Monkey eats banana
              Given there are bananas
          FEATURE

          it { @doc.should have_css_node('.feature h3', /Monkey eats banana/) }
          it { @doc.should have_css_node('.feature .scenario .step', /there are bananas/) }
        end

        describe "with a scenario outline" do
          define_feature <<-FEATURE
          Feature: Fud Pyramid

            Scenario Outline: Monkey eats a balanced diet
              Given there are <Things>

              Examples: Fruit
               | Things  |
               | apples  |
               | bananas |
              Examples: Vegetables
               | Things   |
               | broccoli |
               | carrots  |
          FEATURE

          it { @doc.should have_css_node('.feature .scenario.outline h4', /Fruit/) }
          it { @doc.should have_css_node('.feature .scenario.outline h4', /Vegetables/) }
          it { @doc.css('.feature .scenario.outline h4').length.should == 2}
          it { @doc.should have_css_node('.feature .scenario.outline table', //) }
          it { @doc.should have_css_node('.feature .scenario.outline table td', /carrots/) }
        end

        describe "with a step with a py string" do
          define_feature <<-FEATURE
          Feature: Traveling circus

            Scenario: Monkey goes to town
              Given there is a monkey called:
               """
               foo
               """
          FEATURE

          it { @doc.should have_css_node('.feature .scenario .val', /foo/) }
        end

        describe "with a multiline step arg" do
          define_steps do
            Given(/there are monkeys:/) { |table| }
          end
          define_feature <<-FEATURE
          Feature: Traveling circus

            Scenario: Monkey goes to town
              Given there are monkeys:
               | name |
               | foo  |
               | bar  |
          FEATURE

          it { @doc.should have_css_node('.feature .scenario table td', /foo/) }
          it { @out.string.include?('makeYellow(\'scenario_1\')').should be_false }
        end

        describe "with a table in the background and the scenario" do
          define_feature <<-FEATURE
          Feature: accountant monkey

            Background:
              Given table:
                | a | b |
                | c | d |
            Scenario:
              Given another table:
               | e | f |
               | g | h |
          FEATURE

          it { @doc.css('td').length.should == 8 }
        end

        describe "with a py string in the background and the scenario" do
          define_feature <<-FEATURE
          Feature: py strings

            Background:
              Given stuff:
                """
                foo
                """
            Scenario:
              Given more stuff:
                """
                bar
                """
          FEATURE

          it { @doc.css('.feature .background pre.val').length.should == 1 }
          it { @doc.css('.feature .scenario pre.val').length.should == 1 }
        end

        describe "with a step that fails in the scenario" do
          define_steps do
            Given(/boo/) { raise StandardError, 'eek'.freeze }
          end

          define_feature(<<-FEATURE)
          Feature: Animal Cruelty

            Scenario: Monkey gets a fright
              Given boo
            FEATURE

          it { @doc.should have_css_node('.feature .scenario .step.failed .message', /eek/) }
          it { @doc.should have_css_node('.feature .scenario .step.failed .message', /StandardError/) }
        end

        describe "with a step that fails in the background" do
          define_steps do
            Given(/boo/) { raise 'eek' }
          end

          define_feature(<<-FEATURE)
          Feature: shouting
            Background:
              Given boo
            Scenario:
              Given yay
            FEATURE

          it { @doc.should have_css_node('.feature .background .step.failed', /eek/) }
          it { @out.string.should_not include('makeRed(\'scenario_0\')') }
          it { @out.string.should include('makeRed(\'background_0\')') }
          it { @doc.should_not have_css_node('.feature .scenario .step.failed', //) }
          it { @doc.should have_css_node('.feature .scenario .step.undefined', /yay/) }
          it { @doc.should have_css_node('.feature .background .backtrace', //) }
          it { @doc.should_not have_css_node('.feature .scenario .backtrace', //) }
        end

        describe "with a step that embeds a snapshot" do
          define_steps do
            Given(/snap/) { embed('snapshot.jpeg', 'image/jpeg') }
          end

          define_feature(<<-FEATURE)
          Feature:
            Scenario:
              Given snap
            FEATURE

          it { @doc.css('.embed img').first.attributes['src'].to_s.should == "snapshot.jpeg" }
        end

        describe "with an undefined Given step then an undefined And step" do
          define_feature(<<-FEATURE)
          Feature:
            Scenario:
              Given some undefined step
              And another undefined step
            FEATURE

          it { @doc.css('pre').map { |pre| /^(Given|And)/.match(pre.text)[1] }.should == ["Given", "Given"] }
        end

      end
    end
  end
end


text:
package db.io.operations;

import db.io.core.ConnFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import static com.google.common.base.Preconditions.*;
import static com.google.common.base.Throwables.*;

class QueryRunner implements Query {
    private final SqlStmt stmtFactory = SqlStmt.Default;
    private final ConnFactory connForge;

    QueryRunner(ConnFactory connForge) {
        this.connForge = checkNotNull(connForge);
    }

    @Override public <T> Collection<T> run(Class<T> intf, String sql, Object... args) {
        try (
                Connection conn = connForge.connection();
                PreparedStatement statement = stmtFactory.prepare(conn, sql, args);
                ResultSet rs = statement.executeQuery()
        ) {
            DataSet ds = processResultSet(rs);
            return new ValueFactory(intf, ds).create(intf, ds);

        } catch (SQLException e) {
            throw propagate(e);
        }
    }

    private DataSet processResultSet(ResultSet rs) {
        //
        // TODO - need to memoize the QueryMeta, probably need a query name here to id the query
        //
        return new QueryMeta(rs)
                .newReader()
                .read(rs);
    }
}

redpajama_set_name: RedPajamaGithub


text:
SynerGV 2

SynerGV 2 is a re-write and somewhat functionally changed SynerGV 1
(in my synergv1 repo) Google Voice(tm) app for webOS.

It is implemented partially as a significantly modified version of Alexander Stetsyuk's
outstanding node-google-voice implementation at https://github.com/amper5and/node-google-voice .

The node-google-voice module in this package has gone through extensive changes that
were required to make it operate in the node 0.2 and 0.4 versions available within
webOS.  **note: it does work in the 0.4 version in webOS 3.0.5, it may require additional
work to get it working in webOS 3.0.4 or earlier, which used node 0.2.

There are also several other node.js libraries that are included in this package, most of
which have undergone anywhere from minor to significant modifications to work with the
older version of node, or to hammer them into operating in a specific fashion.

Originally written in 2011-2012 for webOS 3.0.x, SynerGV is one of the most popular Google
Voice(tm) management apps out there, and is the only app ever released on the HP/Palm
App Catalog that implemented Synergy Instant Messaging support.  (Thanks to lack of documentation...)

SynerGV was originally built as an app to allow SMS text messaging from a tablet,
and has been enhanced to support nearly every function of Google Voice.

Plans had been made to create a SynerGV 3, which would have been written in
a combination of standard Javascript using Enyo v2,
as well as platform specific pieces in other languages, such as node.js Javascript,
Android Java, QML, and others, but lack of time on the author's part has made that
an excruciatingly slow project that may not ever see the light of day.

You are welcome to use this code in any fashion that you see fit, just remember
to give credit where credit is due, and follow the LICENSE agreement. Also follow
any license agreements for any modules that are used.

** PLEASE keep in mind that Open Source projects work best for everyone when you
actively contribute!  Pull Requests and Gerrithub Code Review requests are welcome!

Original SynerGV 2 code through the initial commit to this repository is Copyright 2011 - 2014, Eric Blade. All additional code that is not mentioned below, is copyright the author of that code. All contributions to this code are considered to be released under the terms of the LICENSE file here.

The node library "gvhttps" is Copyright 2012-2014, Eric Blade, and falls under the SynerGV license.

The SynerGV icon is Copyright iconshock.com.

The search icon is Copyright Oxygen Team.

Additional graphics and Icons are copyright Asle Hoeg-Mikkelsen.

node-google-voice is copyright Alexander Stetsyuk.

node-googleclientlogin by Segment ( https://github.com/segmentio )

node jsdom is Copyright (c) 2010 Elijah Insua

node request is by Mikeal Rogers ( https://github.com/mikeal )

node websocket-client is Copyright (c) 2010, Peter Griess <pg@std.in>

node xml2js is by Marek Kubica ( https://github.com/Leonidas-from-XIV )

**
This repo is available at gerrithub!  Visit gerrithub.io, and search for the
project "ericblade/synergv2", or simply search "ericblade" for all of my public
source code.

More information about gerrithub is available here:
https://www.youtube.com/watch?v=jeWTvDad6VM

=== To run in Chrome ===

(Windows) Create a new shortcut on your desktop to Chrome.  Edit that shortcut, and add "--disable-web-security" to the Target.
Example: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security

(Unix) run google-chrome --disable-web-security or chromium --disable-web-security (depending on wether you are using chrome or chromium)

(Mac/others) I don't use a Mac, but you should be able to adapt the above instructions.

This might work in Opera, if Opera 20+ supports the --disable-web-security command.

Do NOT use the disable-web-security switch for active browsing!!! Only use it when working with known good files.

Use that shortcut, and load the "index.html" in the repo into your Chrome window, such as:
file:///D:/src/synergv2/app/index-chrome.html

=== Deploying to webOS ===

Update the version number in app/appinfo.json and package/packageinfo.json, then run one of these bat files:
pack.bat -- to create an ipk file
inst.bat -- to create an ipk file and deploy it to a device
dist.bat -- to create an ipk file, deploy it to device, and run the app.

=== Deploying to other systems ===

Don't even think about trying it with this one.  You want "synergv1".  This repo contains a whole ton
of webOS specific code.

=== Potential issues ===
When running it in Chrome, it asks you to run Java.  If I remember correctly, Java is only necessary
if you are attempting to use the built-in Enyo bridge to actually communciate with a live device
that has a luna-service bus.  I don't think this ever actually worked, or if it did, I never figured
out how to get it working.

When running it in Chrome, it may stick at "Loading Accounts..." with a spinner that spins. (what else
did you expect a spinner would do?)  I'm looking into this.  This may have to do with the Java thing,
but I thought we were disabling that, and forcing it to specifically use the "mock" service data files.
If anyone has a solution, please submit a code review/pull request!


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) Sulu GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\ArticleBundle\Admin;

use Sulu\Bundle\AdminBundle\Admin\Admin;
use Sulu\Bundle\AdminBundle\Admin\Navigation\NavigationItem;
use Sulu\Bundle\AdminBundle\Admin\Navigation\NavigationItemCollection;
use Sulu\Bundle\AdminBundle\Admin\View\ToolbarAction;
use Sulu\Bundle\AdminBundle\Admin\View\ViewBuilderFactoryInterface;
use Sulu\Bundle\AdminBundle\Admin\View\ViewCollection;
use Sulu\Bundle\ArticleBundle\Metadata\StructureTagTrait;
use Sulu\Bundle\AutomationBundle\Admin\View\AutomationViewBuilder;
use Sulu\Bundle\PageBundle\Document\BasePageDocument;
use Sulu\Component\Content\Compat\StructureManagerInterface;
use Sulu\Component\Localization\Localization;
use Sulu\Component\Localization\Manager\LocalizationManagerInterface;
use Sulu\Component\Security\Authorization\PermissionTypes;
use Sulu\Component\Security\Authorization\SecurityCheckerInterface;

/**
 * Integrates article-bundle into sulu-admin.
 */
class ArticleAdmin extends Admin
{
    use StructureTagTrait;

    const STRUCTURE_TAG_TYPE = 'sulu_article.type';

    const STRUCTURE_TAG_MULTIPAGE = 'sulu_article.multi_page';

    const SECURITY_CONTEXT = 'sulu.modules.articles';

    const LIST_VIEW = 'sulu_article.list';

    const ADD_FORM_VIEW = 'sulu_article.add_form';

    const EDIT_FORM_VIEW = 'sulu_article.edit_form';

    /**
     * @var ViewBuilderFactoryInterface
     */
    private $viewBuilderFactory;

    /**
     * @var SecurityCheckerInterface
     */
    private $securityChecker;

    /**
     * @var LocalizationManagerInterface
     */
    private $localizationManager;

    /**
     * @var StructureManagerInterface
     */
    private $structureManager;

    /**
     * @var string[]
     */
    private $kernelBundles;

    public function __construct(
        ViewBuilderFactoryInterface $viewBuilderFactory,
        SecurityCheckerInterface $securityChecker,
        LocalizationManagerInterface $localizationManager,
        StructureManagerInterface $structureManager,
        array $kernelBundles
    ) {
        $this->viewBuilderFactory = $viewBuilderFactory;
        $this->securityChecker = $securityChecker;
        $this->localizationManager = $localizationManager;
        $this->structureManager = $structureManager;
        $this->kernelBundles = $kernelBundles;
    }

    /**
     * {@inheritdoc}
     */
    public function configureNavigationItems(NavigationItemCollection $navigationItemCollection): void
    {
        if ($this->securityChecker->hasPermission(self::SECURITY_CONTEXT, 'view')) {
            $articleItem = new NavigationItem('sulu_article.articles');
            $articleItem->setPosition(20);
            $articleItem->setIcon('su-newspaper');
            $articleItem->setView(static::LIST_VIEW);

            $navigationItemCollection->add($articleItem);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function configureViews(ViewCollection $viewCollection): void
    {
        $locales = array_values(
            array_map(
                function(Localization $localization) {
                    return $localization->getLocale();
                },
                $this->localizationManager->getLocalizations()
            )
        );

        $formToolbarActionsWithType = [
            new ToolbarAction('sulu_admin.save_with_publishing'),
            new ToolbarAction('sulu_admin.type'),
            new ToolbarAction('sulu_admin.delete'),
        ];

        $formToolbarActionsWithoutType = [
            new ToolbarAction('sulu_admin.save_with_publishing'),
        ];

        $listToolbarActions = [
            new ToolbarAction('sulu_admin.add'),
            new ToolbarAction('sulu_admin.delete'),
        ];

        $viewCollection->add(
            $this->viewBuilderFactory->createListViewBuilder(static::LIST_VIEW, '/articles/:locale')
                ->setResourceKey('articles')
                ->setListKey('articles')
                ->setTitle('sulu_article.articles')
                ->addListAdapters(['table'])
                ->addLocales($locales)
                ->setDefaultLocale($locales[0])
                ->setAddView(static::ADD_FORM_VIEW)
                ->setEditView(static::EDIT_FORM_VIEW)
                ->addToolbarActions($listToolbarActions)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createResourceTabViewBuilder(static::ADD_FORM_VIEW, '/articles/:locale/add')
                ->setResourceKey('articles')
                ->addLocales($locales)
                ->setBackView(static::LIST_VIEW)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createFormViewBuilder('sulu_article.add_form.details', '/details')
                ->setResourceKey('articles')
                ->setFormKey('article')
                ->setTabTitle('sulu_admin.details')
                ->setEditView(static::EDIT_FORM_VIEW)
                ->addToolbarActions($formToolbarActionsWithType)
                ->setParent(static::ADD_FORM_VIEW)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createResourceTabViewBuilder(static::EDIT_FORM_VIEW, '/articles/:locale/:id')
                ->setResourceKey('articles')
                ->addLocales($locales)
                ->setBackView(static::LIST_VIEW)
                ->setTitleProperty('title')
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createPreviewFormViewBuilder('sulu_article.edit_form.details', '/details')
                ->setResourceKey('articles')
                ->setFormKey('article')
                ->setTabTitle('sulu_admin.details')
                ->setTabPriority(1024)
                ->addToolbarActions($formToolbarActionsWithType)
                ->setParent(static::EDIT_FORM_VIEW)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createPreviewFormViewBuilder('sulu_article.edit_form.seo', '/seo')
                ->setResourceKey('articles')
                ->setFormKey('page_seo')
                ->setTabTitle('sulu_page.seo')
                ->addToolbarActions($formToolbarActionsWithoutType)
                ->setParent(static::EDIT_FORM_VIEW)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createPreviewFormViewBuilder('sulu_article.edit_form.excerpt', '/excerpt')
                ->setResourceKey('articles')
                ->setFormKey('page_excerpt')
                ->setBackView(static::LIST_VIEW)
                ->setTabTitle('sulu_page.excerpt')
                ->addToolbarActions($formToolbarActionsWithoutType)
                ->setParent(static::EDIT_FORM_VIEW)
        );
        $viewCollection->add(
            $this->viewBuilderFactory->createPreviewFormViewBuilder('sulu_article.edit_form.settings', '/settings')
                ->setResourceKey('articles')
                ->setFormKey('article_settings')
                ->setBackView(static::LIST_VIEW)
                ->setTabTitle('sulu_page.settings')
                ->setTabPriority(512)
                ->addToolbarActions($formToolbarActionsWithoutType)
                ->setParent(static::EDIT_FORM_VIEW)
        );

        if (isset($this->kernelBundles['SuluAutomationBundle'])) {
            $viewCollection->add(
                (new AutomationViewBuilder('sulu_article.edit_form.automation', '/automation'))
                    ->setEntityClass(BasePageDocument::class)
                    ->setParent(static::EDIT_FORM_VIEW)
            );
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getSecurityContexts()
    {
        $types = [];
        $securityContext = [];
        foreach ($this->structureManager->getStructures('article') as $key => $structure) {
            $type = $this->getType($structure->getStructure());
            if (!array_key_exists($type, $types)) {
                $types[$type] = [
                    'type' => $structure->getKey(),
                ];
            }
            $securityContext[self::SECURITY_CONTEXT . '_' . $type] = [
                PermissionTypes::VIEW,
                PermissionTypes::ADD,
                PermissionTypes::EDIT,
                PermissionTypes::DELETE,
                PermissionTypes::LIVE,
            ];
        }

        return [
            'Sulu' => [
                'Global' => [
                    self::SECURITY_CONTEXT => [
                        PermissionTypes::VIEW,
                        PermissionTypes::ADD,
                        PermissionTypes::EDIT,
                        PermissionTypes::DELETE,
                        PermissionTypes::LIVE,
                    ],
                ],
                'Article types' => $securityContext,
            ],
        ];
    }
}


text:
Send2URL
========

This app adds an entry to the android share menu.
When you share any content (e.g. a picture from the gallery) with "Send2URL"
it will be uploaded to the configured server URL using a HTTP POST request.

Dependencies
------------
Requires Android SDK 22 or earlier because of `org.apache.http.client`.


text:
<?php

class Images extends CI_MODEL{

	//constructor
	function __construct(){
		parent::__construct();
	}

	//return all images, descending order by post date
	function all(){
		$this->db->order_by("id", "desc");
		$query = $this->db->get('Images');
		return $query->result_array();
	}

	function newest(){
		$this->db->order_by("id","desc");
		$this->db->limit(3);
		$query = $this->db->get('images');
		return $query->result_array();
	}

}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.ObjectModel;
using System.Management.Automation;
using Microsoft.WindowsAzure.Commands.Common.Models;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Model;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Common;

namespace Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS
{
    [Cmdlet(VerbsCommon.New, "AzureVMConfig", DefaultParameterSetName = "ImageName"), OutputType(typeof(PersistentVM))]
    public class NewAzureVMConfigCommand : ServiceManagementBaseCmdlet
    {
        private const string RoleType = "PersistentVMRole";

        [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The virtual machine name.")]
        [ValidateNotNullOrEmpty]
        public string Name
        {
            get;
            set;
        }

        [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Represents the size of the machine.")]
        [ValidateNotNullOrEmpty]
        public string InstanceSize
        {
            get;
            set;
        }

        [Parameter(Position = 2, HelpMessage = "Controls the platform caching behavior of the OS disk.")]
        [ValidateSet("ReadWrite", "ReadOnly", IgnoreCase = true)]
        public string HostCaching
        {
            get;
            set;
        }

        [Parameter(Position = 3, HelpMessage = "The name of the availability set.")]
        [ValidateNotNullOrEmpty]
        public string AvailabilitySetName
        {
            get;
            set;
        }

        [Parameter(Position = 4, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The VM label.")]
        [ValidateNotNullOrEmpty]
        public string Label
        {
            get;
            set;
        }

        [Parameter(Position = 5, Mandatory = true, ParameterSetName = "DiskName", HelpMessage = "Friendly name of the OS disk in the disk repository.")]
        [ValidateNotNullOrEmpty]
        public string DiskName
        {
            get;
            set;
        }

        [Parameter(Position = 5, Mandatory = true, ParameterSetName = "ImageName", HelpMessage = "Reference to a platform stock image or a user image from the image repository.")]
        [ValidateNotNullOrEmpty]
        public string ImageName
        {
            get;
            set;
        }

        [Parameter(Position = 6, Mandatory = false, ParameterSetName = "ImageName", HelpMessage = "Location of the where the VHD should be created. This link refers to a blob in a storage account. If not specified the VHD will be created in the default storage account with the following format :vhds/servicename-vmname-year-month-day-ms")]
        [ValidateNotNullOrEmpty]
        public string MediaLocation
        {
            get;
            set;
        }

        [Parameter(Position = 7, Mandatory = false, ParameterSetName = "ImageName", HelpMessage = "Label of the new disk to be created.")]
        [ValidateNotNullOrEmpty]
        public string DiskLabel
        {
            get;
            set;
        }

        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            ValidateParameters();

            var role = new PersistentVM
            {
                AvailabilitySetName = AvailabilitySetName,
                ConfigurationSets = new Collection<ConfigurationSet>(),
                DataVirtualHardDisks = new Collection<DataVirtualHardDisk>(),
                RoleName = Name,
                RoleSize = InstanceSize,
                RoleType = RoleType,
                Label = Label,
                ProvisionGuestAgent = true
            };

            role.OSVirtualHardDisk = new OSVirtualHardDisk()
            {
                DiskName = DiskName,
                SourceImageName = ImageName,
                MediaLink = string.IsNullOrEmpty(MediaLocation) ? null : new Uri(MediaLocation),
                HostCaching = HostCaching,
                DiskLabel = string.IsNullOrEmpty(DiskLabel) ? null : DiskLabel
            };

            WriteObject(role, true);
        }

        protected void ValidateParameters()
        {
            AzureSubscription currentSubscription = CurrentContext.Subscription;
            if ((currentSubscription == null || string.IsNullOrEmpty(currentSubscription.GetProperty(AzureSubscription.Property.StorageAccount))) && string.IsNullOrEmpty(MediaLocation))
            {
                throw new ArgumentException(Resources.MustSpecifyMediaLocationOrHaveCurrentStorageAccount);
            }

            if (string.IsNullOrEmpty(Label))
            {
                Label = Name;
            }
        }
    }
}


text:
package com.pengrad.telegrambot.checks;

import com.pengrad.telegrambot.model.VideoNote;

import static org.junit.Assert.assertNotNull;

/**
 * Stas Parshin
 * 24 May 2017
 */
public class VideoNoteCheck {

    public static void check(VideoNote videoNote) {
        check(videoNote, false);
    }

    public static void check(VideoNote videoNote, boolean full) {
        assertNotNull(videoNote.fileId());
        assertNotNull(videoNote.fileUniqueId());
        assertNotNull(videoNote.length());
        assertNotNull(videoNote.duration());
        PhotoSizeTest.checkPhotos(videoNote.thumb());
        if (full) {
            assertNotNull(videoNote.fileSize());
        }
    }

}


text:
require 'spec_helper'

describe Praxis::ResourceDefinition do
  subject(:resource_definition) { PeopleResource }

  its(:description) { should eq('People resource') }
  its(:media_type) { should eq(Person) }

  its(:responses) { should eq(Hash.new) }
  its(:version) { should eq('1.0') }

  its(:routing_config) { should be_kind_of(Proc) }

  its(:params) { should be_nil }
  its(:payload) { should be_nil }
  its(:headers) { should be_nil }

  its(:actions) { should have(2).items }

  context '.describe' do
    subject(:describe) { resource_definition.describe }

    its([:description]) { should eq(resource_definition.description) }
    its([:media_type]) { should eq(resource_definition.media_type.name) }

    its([:actions]) { should have(2).items }
  end

  it 'creates ActionDefinitions for actions' do
    index = resource_definition.actions[:index]
    expect(index).to be_kind_of(Praxis::ActionDefinition)
    expect(index.description).to eq("index description")
  end

  context 'setting other values' do
    subject(:resource_definition) { Class.new {include Praxis::ResourceDefinition } }

    let(:some_proc) { Proc.new {} }
    let(:some_hash) { Hash.new }

    it 'accepts a string as media_type' do
      resource_definition.media_type('Something')
      expect(resource_definition.media_type).to be_kind_of(Praxis::SimpleMediaType)
      expect(resource_definition.media_type.identifier).to eq('Something')
    end

    context 'sets responses' do
      before do
        resource_definition.response(:some_response)
      end
      subject(:responses){ resource_definition.responses }
      it { should be_kind_of(Hash) }

    end

    context 'setting params' do
      it 'uses the right default values' do
        resource_definition.params &some_proc

        expect(resource_definition.params[0]).to be(Attributor::Struct)
        expect(resource_definition.params[1]).to eq({})
        expect(resource_definition.params[2]).to be(some_proc)
      end

      it 'accepts specific a type and options' do
        resource_definition.params Person, required: true

        expect(resource_definition.params[0]).to be(Person)
        expect(resource_definition.params[1]).to eq({required: true})
        expect(resource_definition.params[2]).to be(nil)
      end
    end

    context 'setting payload' do
      it 'uses the right default values' do
        resource_definition.payload &some_proc

        expect(resource_definition.payload[0]).to be(Attributor::Struct)
        expect(resource_definition.payload[1]).to eq({})
        expect(resource_definition.payload[2]).to be(some_proc)
      end

      it 'accepts specific a type and options' do
        resource_definition.payload Person, required: true

        expect(resource_definition.payload[0]).to be(Person)
        expect(resource_definition.payload[1]).to eq({required: true})
        expect(resource_definition.payload[2]).to be(nil)
      end

    end

    it "sets headers" do
      resource_definition.headers(some_hash, &some_proc)

      expect(subject.headers[0]).to be(some_hash)
      expect(subject.headers[1]).to be(some_proc)
    end

  end

  context '.use' do
    subject(:resource_definition) { Class.new {include Praxis::ResourceDefinition } }
    it 'raises an error for missing traits' do
      expect { resource_definition.use(:stuff) }.to raise_error(Praxis::Exceptions::InvalidTrait)
    end
    it 'has a spec for actually using a trait'
  end

end


text:
App.Purpose.Store = (function () {
  'use strict';

  return new FluxCrud.Store({
    defaultAttrs: {
      id: null,
      name: '',
      purchaseIds: []
    },

    dispatcher: App.Dispatcher,

    constants: App.Purpose.Constants
  });
})();


text:
#pragma once

#include <cppexpose/reflection/AbstractProperty.h>

#include <gloperate/gloperate_api.h>

namespace gloperate
{

class Stage;

/**
*  @brief
*    Slot type
*/
enum class SlotType
{
    Unknown = 0, ///< Slot of unknown type
    Input,       ///< Slot is input to a stage
    Output       ///< Slot is output of a stage
};

/**
*  @brief
*    Base class for data slots
*
*    To transfer data between stages, each stage can have a number
*    of data slots. Input slots contain the data the stage needs to
*    calculate or produce its output, the produced output data is
*    stored in its output slots. A data slot can either be set directly
*    to a specific value, or it can be connected to another slot. As long
*    as it is connected, it will return the value of the source slot.
*
*    This class should not be instanciated directly. Instead, Input<T> and
*    Output<T> should be used to declare slots for stages.
*/
class GLOPERATE_API AbstractSlot : public cppexpose::AbstractProperty
{
public:
    /**
    *  @brief
    *    Constructor
    */
    AbstractSlot();

    /**
    *  @brief
    *    Constructor
    *
    *  @param[in] options
    *    Options with which the property is initialized
    */
    AbstractSlot(const cppexpose::Variant & options);

    /**
    *  @brief
    *    Destructor
    */
    virtual ~AbstractSlot();

    /**
    *  @brief
    *    Get parent stage
    *
    *  @return
    *    Stage that contains the slot (can be null)
    */
    Stage * parentStage() const;

    /**
    *  @brief
    *    Get qualified name
    *
    *  @return
    *    Name with all parent names, separated by '.'
    */
    std::string qualifiedName() const;

    /**
    *  @brief
    *    Check if slot is dynamic
    *
    *  @return
    *    'true' if slot has been added dynamically, else 'false'
    */
    bool isDynamic() const;

    /**
    *  @brief
    *    Check if slot is required
    *
    *  @return
    *    'true' if slot is required, else 'false'
    *
    *  @see
    *    setRequired
    */
    bool isRequired() const;

    /**
    *  @brief
    *    Set if slot is required
    *
    *  @param[in] required
    *    'true' if slot is required, else 'false'
    *
    *  @remarks
    *    This flag plays a role during the execution of pipelines.
    *    If an output slot is flagged as required, the owning stage
    *    will be activated in order to produce that output. In turn,
    *    the stage will also flag its input slots as required. This
    *    propagates through the entire pipeline and determines
    *    which stages will be executed.
    */
    void setRequired(bool required);

    /**
    *  @brief
    *    Check if slot currently has a feedback connection
    *
    *  @return
    *    'true' if slot has a feedback connection, else 'false'
    *
    *  @remarks
    *    In complex pipelines, stages sometimes have to depend on output
    *    values of stages that are processed later in the pipeline, which
    *    introduces a cyclic dependency between the stages. Therefore,
    *    a slot can be flagged as a feedback connection, indicating that
    *    the connection shall be ignored when calculating the dependency
    *    graph (and order of execution) of the pipeline.
    */
    bool isFeedback() const;

    /**
    *  @brief
    *    Set if slot currently has a feedback connection
    *
    *  @param[in] feedback
    *    'true' if slot has a feedback connection, else 'false'
    *
    *  @see
    *    isFeedback
    */
    void setFeedback(bool feedback);

    /**
    *  @brief
    *    Check if slot is connected to another slot
    *
    *  @return
    *    'true' if slot is connected, else 'false'
    */
    bool isConnected() const;

    /**
    *  @brief
    *    Check if slot is compatible to source slot
    *
    *  @param[in] source
    *    Source slot (can be null)
    *
    *  @return
    *    'true' if slot can be connected to source slot, else 'false'
    *
    *  @remarks
    *    To be compatible, the source slot must use the same data type.
    */
    virtual bool isCompatible(const AbstractSlot * source) const = 0;

    /**
    *  @brief
    *    Connect slot to source slot
    *
    *  @param[in] source
    *    Source slot (can be null)
    *
    *  @return
    *    'true' if slot could be connected, else 'false'
    */
    virtual bool connect(AbstractSlot * source) = 0;

    /**
    *  @brief
    *    Disconnect slot
    */
    virtual void disconnect() = 0;

    /**
    *  @brief
    *    Get currently connected slot
    *
    *  @return
    *    Source slot (can be null)
    */
    virtual const AbstractSlot * source() const = 0;

    /**
    *  @brief
    *    Check if slot has valid data
    *
    *  @return
    *    'true' if data is valid, else 'false'
    *
    *  @remarks
    *    This status is important for the pipeline to work.
    *    If output data is invalid, the pipeline tries to produce
    *    it, otherwise, the pipeline is not run. This function
    *    indicates whether data needs to be updated.
    */
    virtual bool isValid() const = 0;

    /**
    *  @brief
    *    Invalidates data
    *
    *  @remarks
    *    The state will automatically change to valid when a new value is set.
    *
    *  @see
    *    isValid
    *  @see
    *    setValue
    */
    virtual void invalidate() = 0;

    /**
    *  @brief
    *    Check if slot was changed
    *
    *  @return
    *    'true' if data was changed, else 'false'
    *
    *  @remarks
    *    This status helps to improve performance in a pipeline.
    *    It is used to avoid processing of input values that where
    *    processed ealier already.
    */
    virtual bool hasChanged() const = 0;

    /**
    *  @brief
    *    Set the changed flag
    *
    *  @remarks
    *    This marks the input value as changed or unchanged.
    *    The state will automatically change to changed when a new value is set.
    *
    *  @see
    *    hasChanged
    */
    virtual void setChanged(bool hasChanged) = 0;

    /**
    *  @brief
    *    Called when required-flag has been changed
    */
    virtual void onRequiredChanged() = 0;

    /**
    *  @brief
    *    Called when value was invalidated i.e. it was valid and is set to invalid
    */
    virtual void onValueInvalidated() = 0;

    /**
    *  @brief
    *    Check if the Slot is a slot of any type given by the template argument list
    *
    *  @tparam Types
    *    The variadic template parameter list of all types to check
    *
    *  @return
    *    'true' if the slot is of any type given, else 'false'
    */
    template <typename... Types>
    bool isOfAnyType() const;

protected:
    /**
    *  @brief
    *    Initialize input slot
    *
    *  @param[in] slotType
    *    Type or role of the slot (input or output)
    *  @param[in] parent
    *    Parent stage (can be null)
    *  @param[in] ownership
    *    Property ownership
    */
    void initSlot(SlotType slotType, Stage * parent);

protected:
    SlotType m_slotType; ///< Type or role of the slot (input or output)
    bool     m_dynamic;  ///< 'true' if slot has been added dynamically, else 'false'
    bool     m_required; ///< Is the data required?
    bool     m_feedback; ///< Does the slot contain a feedback connection?
};

} // namespace cppexpose

#include <gloperate/pipeline/AbstractSlot.inl>


text:
// Copyright © 2019 Andy Goryachev <andy@goryachev.com>
package goryachev.fx.css;
import goryachev.common.util.CList;
import goryachev.common.util.SB;
import goryachev.fx.internal.CssTools;
import goryachev.fx.internal.FxCssProp;

/**
 * FX CSS Selector.
 */
public class Selector
{
	protected final Selector parent;
	protected final Object[] spec;
	protected final CList<Object> content = new CList();

	public Selector(Selector parent, Object[] spec)
	{
		this.parent = parent;
		this.spec = spec;
	}

	protected void generate(SB sb)
	{
		// TODO
	}

	protected Selector prop(String fxproperty, Object x)
	{
		content.add(x);
		return this;
	}

	public FxStyleSheet getStyleSheet()
	{
		return parent.getStyleSheet();
	}

	public Selector selector(Object ... spec)
	{
		Selector s = new Selector(this, spec);
		content.add(s);
		return s;
	}

	public Selector backgroundColor(Object x) { return prop("-fx-background-color", CssTools.toColor(x)); }
	public Selector backgroundImage(Object x) { return prop("-fx-background-image", CssTools.toValue(x)); }
	public Selector backgroundInsets(Object x) { return prop("-fx-background-insets", CssTools.toValue(x)); }
	public Selector backgroundRadius(Object x) { return prop("-fx-background-radius", CssTools.toValue(x)); }

	/** [ normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 ] */
	public Selector fontWeight(Object x) { return prop("-fx-font-weight", x); }
}


text:
[![Build Status](https://travis-ci.org/melrief/PureCSV.svg?branch=master)](https://travis-ci.org/melrief/PureCSV)

PureCSV is a Scala library for working with the CSV format. The
library gets rid of most of the boilerplate required to work with CSV

```scala
scala> import purecsv.unsafe._
scala> case class Event(ts: Long, msg: String)
scala> val records = CSVReader[Event].readCSVFromString("1,foo\n2,bar")
records: List[Event] = List(Event(1,foo), Event(2,bar))
scala> records.toCSV()
res0: String =
1,"foo"
2,"bar
```

In this example, a case class called `Event` is defined and immediately used to
read to and write from CSV.

## Add the library to your project ##

Add the Sonatype release repository to the resolvers and then add the library to
the project libraryDependencies.

```scala
resolvers += Resolver.sonatypeRepo("releases")

libraryDependencies += "com.github.melrief" %% "purecsv" % "0.0.1"
```

Currently it is only for Scala 2.11.x.

## Use the library ##

### Writing to CSV ###

To convert a value to a CSV String use `toCSV`

```scala
scala> import purecsv.safe._
scala> class Interval(val start: Long, val end: Long)
scala> new Interval(10,20).toCSV()
res1: String = 1,10
scala> Seq(new Interval(1,10),new Interval(11,20)).toCSV("|")
res2: String =
1|10
11|20
```

To write CSV values to a file use `writeCSVToFile` or `writeCSVToFileName`

```scala
scala> import purecsv.unsafe._
scala> class Interval(val start: Long, val end: Long) { override def toString: String = s"Interval($start,$end)" }
scala> Seq(new Interval(1,10),new Interval(11,20)).writeCSVToFileName("/tmp/example.csv")
scala> scala.io.Source.fromFile("/tmp/example.csv").getLines.toList
res0: List[String] = List(1,10, 11,20)
scala> CSVReader[Interval].readCSVFromFile("/tmp/example.csv")
res2: List[Interval] = List(Interval(1,10), Interval(11,20))
```

### Reading from CSV ###

Reading from CSV is a bit different from writing to CSV. There are two different ways to read from CSV Strings, one
safe and the other unsafe. See next paragraph for the difference. Other than that, a `CSVReader` instance should be
used to read data

```scala
scala> import purecsv.unsafe._
scala> class Interval(val start: Long, val end: Long) { override def toString: String = s"Interval($start,$end)" }
scala> CSVReader[Interval].readCSVFromFile("/tmp/example.csv")
res2: List[Interval] = List(Interval(1,10), Interval(11,20))
```

If the source has a header, it is possible to skip it.

```scala
scala> import purecsv.unsafe._
scala> case class Address(name: String, address: String)
scala> Seq(Address("alice","wonderland")).writeCSVToFileName("/tmp/example.csv", header=Some(Seq("name","address")))
scala> scala.io.Source.fromFile("/tmp/example.csv").getLines.toList
res2: List[String] = List(name,address, "alice","wonderland")
scala> CSVReader[Address].readCSVFromFileName("/tmp/example.csv", skipHeader=true)
res1: List[Address] = List(Address(alice,wonderland))
```

### Reading from CSV: Safe vs Unsafe ###

For reading values, the library comes in two flavors: one safe and one unsafe.
Only one should be imported.  The safe flavor captures errors

```scala
scala> import purecsv.safe._
scala> case class Person(name: String, age: Int)
scala> CSVReader[Person].readCSVFromString("alice,1")
res0: List[scala.util.Try[Person]] = List(Success(Person(alice,1)))
scala> CSVReader[Person].readCSVFromString("alice,nan")
res1: List[scala.util.Try[Person]] = List(Failure(java.lang.NumberFormatException: For input string: "nan"))
```

The unsafe flavor, instead, ignores errors

```scala
scala> import purecsv.safe._
scala> case class Person(name: String, age: Int)
scala> CSVReader[Person].readCSVFromString("alice,1")
res0: List[Person] = List(Person(alice,1))
scala> CSVReader[Person].readCSVFromString("alice,nan")
java.lang.NumberFormatException: For input string: "nan"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:492)
  ...
```

The two flavors solve different problems: the safe one helps dealing with inputs that could potentially be not well
formatted or event erroneous while the unsafe flavor reads data that is well formatted, for instance the one created
by this library.

The safe flavor has also another characteristic: it helps the user understanding which records gave errors by collecting
them

```scala
scala> val result = CSVReader[Person].readCSVFromString("alice,1\nbob,nan\ncharlie,2\ndelta,\n")
result: List[scala.util.Try[Person]] = List(Success(Person(alice,1)), Failure(java.lang.NumberFormatException: For input string: "nan"), Success(Person(charlie,2)), Failure(java.lang.NumberFormatException: For input string: ""))
scala> import purecsv.safe.tryutil._
scala> val (successes,failures) = result.getSuccessesAndFailures
successes: List[(Int, Person)] = List((1,Person(alice,1)), (3,Person(charlie,2)))
failures: List[(Int, Throwable)] = List((2,java.lang.NumberFormatException: For input string: "nan"), (4,java.lang.NumberFormatException: For input string: ""))
```

The method `getSuccessesAndFailures` returns a pair where the first element are the successes and the second element
are the failures with associated the record number. From the information above we know that record 1 and 3 were read
successfully while record 2 and 4 were not.

## Extending the library ##

PureCSV has been designed with flexibility and extensibility in mind. It is possible
to add new field types as well as change the way standard types are read
from String. It is also possible to change the way CSV is parsed, right now it
uses [OpencSV](http://opencsv.sourceforge.net/), and, more deeply, it is possible
to work with different raw data than String, such as binary data.

### Add new field types ###

`Boolean`, `Int` and most of the Scala types are field types, meaning that it is
possible to convert their values from/to `String`. To add a new type `A`, you have
to supply a `purecsv.safe.converter.StringConverter[A]`.
You can have a look at the
[defaults string converters](https://github.com/melrief/PureCSV/blob/master/src/main/scala/purecsv/safe/converter/defaults/string/package.scala)
to see how this is done for primitive types.
For completeness, we can do an example showing how to create a `StringConverter`
for non-trivial types, like [ISO 8601 for dates](http://en.wikipedia.org/wiki/ISO_8601).
We want to avoid to reinvent the wheel and thus we are going to use the
[Joda-Time](http://www.joda.org/joda-time/) library that provides the
[Joda DateTime](http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html)
structure where to store datetimes as well as the parsers. We can add our
`StringConverter[DateTime]` in this way

```scala
implicit val dateTimeStringConverter = new StringConverter[DateTime] {
    override def tryFrom(str: String): Try[DateTime] = {
      Try(ISODateTimeFormat.dateTimeParser().parseDateTime(str))
    }

    override def to(dateTime: DateTime): String = {
      ISODateTimeFormat.dateTimeParser().print(dateTime)
    }
  }
```

After importing this converter, PureCSV will be able to read `DateTime` fields.

## How it works ##

The library is based on [Shapeless](https://github.com/milessabin/shapeless) Generic system. Everything that has a
Generic instance can be used with PureCSV. A Generic instance defines a representation for a given type in terms of
[heterogenous lists](https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#heterogenous-lists)
and function to convert from/to that representation

```scala
scala> import shapeless._
scala> case class Foo(i: Int)
scala> :t Generic[Foo]
shapeless.Generic[Foo]{type Repr = shapeless.::[Int,shapeless.HNil]}
scala> Generic[Foo].to(Foo(1))
res4: shapeless.::[Int,shapeless.HNil] = 1 :: HNil
```

Note that also structures that don't have an automatically generated `Generic` instance can be used by manually define
the `Generic`. So given a type

```scala
class Event2(val ts: Long, var msg: String) {
  override def equals(o: Any): Boolean = o match {
    case other:Event2 => (this.ts ## other.ts && this.msg ## other.msg)
    case _ => false
  }
  override def toString: String = s"Event($ts, $msg)"
}
```

One can define the `Generic` instance as

```scala
implicit val fooGeneric = new Generic[Event2] {
  override type Repr = Long :: String :: HNil
  override def from(r: Repr): Event2 = {
    val ts :: msg :: HNil = r
    new Event2(ts, msg)
  }
  override def to(t: Event2): Repr = t.ts :: t.msg :: HNil
}
```

and then use that structure with PureCSV

```scala
scala> val conv = RawFieldsConverter[Event2]
```

## License ##

[Apache License v2](https://www.apache.org/licenses/LICENSE-2.0)

## Special Thanks ##

To the [Shapeless](https://github.com/milessabin/shapeless) developers for their amazing library.


text:
enum of3dPrimitiveType {
	OF_3D_PRIMITIVE_PLANE,
    OF_3D_PRIMITIVE_SPHERE,
    OF_3D_PRIMITIVE_ICO_SPHERE,
	OF_3D_PRIMITIVE_BOX,
	OF_3D_PRIMITIVE_CONE,
    OF_3D_PRIMITIVE_CYLINDER,
    OF_3D_PRIMITIVE_BOX_WIREFRAME
};

//----------------------------------------------------------
static of3dPrimitive& getCached3dPrimitive( of3dPrimitiveType type ) {
    switch (type) {
        case OF_3D_PRIMITIVE_PLANE:{
        	static ofPlanePrimitive * plane = new ofPlanePrimitive(1.0f, 1.0f, 6, 4);
        	return *plane;
        }break;
        case OF_3D_PRIMITIVE_SPHERE:{
        	static ofSpherePrimitive * sphere = new ofSpherePrimitive(1.0f, 20);
        	return *sphere;
        }break;
        case OF_3D_PRIMITIVE_ICO_SPHERE:{
        	static ofIcoSpherePrimitive * icosphere = new ofIcoSpherePrimitive(1.0f, 2);
        	return *icosphere;
        }break;
        case OF_3D_PRIMITIVE_BOX:{
        	static ofBoxPrimitive * box = new  ofBoxPrimitive( 1.f, 1.f, 1.f );
        	return *box;
        }break;
        case OF_3D_PRIMITIVE_CONE:{
        	static ofConePrimitive * cone = new ofConePrimitive( 1.f, 1.f, 9, 3, 2 );
        	return *cone;
        }break;
        case OF_3D_PRIMITIVE_CYLINDER:{
        	static ofCylinderPrimitive * cylinder = new ofCylinderPrimitive(1.f, 1.f, 8, 4, 2, true);
        	return *cylinder;
        }break;
            // special case for rendering with lines, so the triangles are not visible //
        case OF_3D_PRIMITIVE_BOX_WIREFRAME: {
            static ofBoxPrimitive * boxWireframe = new ofBoxPrimitive( 1.f, 1.f, 1.f );
            static bool initialized = false;
            ofMesh* boxWireframeMesh = boxWireframe->getMeshPtr();

            if(!initialized){
				boxWireframeMesh->clear();
				boxWireframeMesh->setMode( OF_PRIMITIVE_LINES );

				boxWireframeMesh->addVertex(ofVec3f(-.5, -.5, -.5));
				boxWireframeMesh->addVertex(ofVec3f(.5, -.5, -.5));
				boxWireframeMesh->addVertex(ofVec3f(.5, .5, -.5));
				boxWireframeMesh->addVertex(ofVec3f(-.5, .5, -.5));

				boxWireframeMesh->addVertex(ofVec3f(-.5, -.5, .5));
				boxWireframeMesh->addVertex(ofVec3f(.5, -.5, .5));
				boxWireframeMesh->addVertex(ofVec3f(.5, .5, .5));
				boxWireframeMesh->addVertex(ofVec3f(-.5, .5, .5));

				// front face
				boxWireframeMesh->addIndex(0);
				boxWireframeMesh->addIndex(1);

				boxWireframeMesh->addIndex(1);
				boxWireframeMesh->addIndex(2);

				boxWireframeMesh->addIndex(2);
				boxWireframeMesh->addIndex(3);

				boxWireframeMesh->addIndex(3);
				boxWireframeMesh->addIndex(0);

				// back face
				boxWireframeMesh->addIndex(4);
				boxWireframeMesh->addIndex(5);

				boxWireframeMesh->addIndex(5);
				boxWireframeMesh->addIndex(6);

				boxWireframeMesh->addIndex(6);
				boxWireframeMesh->addIndex(7);

				boxWireframeMesh->addIndex(7);
				boxWireframeMesh->addIndex(4);

				boxWireframeMesh->addIndex(0);
				boxWireframeMesh->addIndex(4);

				boxWireframeMesh->addIndex(1);
				boxWireframeMesh->addIndex(5);

				boxWireframeMesh->addIndex(2);
				boxWireframeMesh->addIndex(6);

				boxWireframeMesh->addIndex(3);
				boxWireframeMesh->addIndex(7);
				initialized = true;
            }

            return * boxWireframe;
        }break;
        default:{
        	static of3dPrimitive * primitive = new of3dPrimitive;
        	return * primitive;
        }break;
    }
}

//----------------------------------------------------------
static void renderCached3dPrimitive( ofMesh& model ) {
    if(ofGetFill() == OF_FILLED) {
    	model.draw(OF_MESH_FILL);
    } else {
        model.draw(OF_MESH_WIREFRAME);
    }
}

// Plane //
//----------------------------------------------------------
void ofSetPlaneResolution( int columns, int rows ) {
    ((ofPlanePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_PLANE)).setResolution(columns, rows);
}

// returns columns as x value of vector and rows as y value
//----------------------------------------------------------
ofVec2f ofGetPlaneResolution() {
    ofPlanePrimitive& plane = ((ofPlanePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_PLANE));
    return plane.getResolution();
}

//----------------------------------------------------------
void ofDrawPlane(float x, float y, float width, float height) {
    ofDrawPlane( x, y, 0, width, height);
}

//----------------------------------------------------------
void ofDrawPlane(float x, float y, float z, float width, float height) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(width,height,1);
	m.translate(x,y,z);
    ofMesh & plane = getCached3dPrimitive( OF_3D_PRIMITIVE_PLANE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( plane );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawPlane(ofPoint& position, float width, float height) {
    ofDrawPlane(position.x,position.y,position.z,width, height);
}

//----------------------------------------------------------
void ofDrawPlane( float width, float height ) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(width,height,1);
    ofMesh & plane = getCached3dPrimitive( OF_3D_PRIMITIVE_PLANE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( plane );
    ofPopMatrix();
}

// UV SPHERE //
//----------------------------------------------------------
void ofSetSphereResolution(int res) {
    if(ofGetSphereResolution() != res) {
        ((ofSpherePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_SPHERE)).setResolution(res);
    }
}

//---------------------------------------------------------
int ofGetSphereResolution() {
    return ((ofSpherePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_SPHERE)).getResolution();
}

//----------------------------------------------------------
void ofDrawSphere(float x, float y, float z, float radius) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,radius,radius);
	m.translate(x,y,z);
	ofMesh& sphere = getCached3dPrimitive( OF_3D_PRIMITIVE_SPHERE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( sphere );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawSphere(float x, float y, float radius) {
    ofDrawSphere(x, y, 0, radius);
}

//----------------------------------------------------------
void ofDrawSphere(const ofPoint& position, float radius) {
    ofDrawSphere(position.x,position.y,position.z,radius);
}

//----------------------------------------------------------
void ofDrawSphere(float radius) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,radius,radius);
	ofMesh& sphere = getCached3dPrimitive( OF_3D_PRIMITIVE_SPHERE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( sphere );
    ofPopMatrix();
}

// Deprecated methods - for compatability with previous versions of OF //
//----------------------------------------------------------
void ofSphere(float x, float y, float z, float radius) {
    ofDrawSphere(x, y, z, radius);
}

//----------------------------------------------------------
void ofSphere(float x, float y, float radius) {
    ofDrawSphere(x, y, 0, radius);
}

//----------------------------------------------------------
void ofSphere(const ofPoint& position, float radius) {
    ofDrawSphere(position.x,position.y,position.z,radius);
}

//----------------------------------------------------------
void ofSphere(float radius) {
    ofDrawSphere(radius);
}

// ICO SPHERE //
//----------------------------------------------------------
void ofSetIcoSphereResolution( int res ) {
    if(ofGetIcoSphereResolution() != res) {
        ((ofIcoSpherePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_ICO_SPHERE)).setResolution(res);
    }
}

//----------------------------------------------------------
int ofGetIcoSphereResolution() {
    return ((ofIcoSpherePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_ICO_SPHERE)).getResolution();
}

//----------------------------------------------------------
void ofDrawIcoSphere(float x, float y, float z, float radius) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,radius,radius);
	m.translate(x,y,z);
	ofMesh& sphere = getCached3dPrimitive( OF_3D_PRIMITIVE_ICO_SPHERE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( sphere );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawIcoSphere(float x, float y, float radius) {
    ofDrawIcoSphere(x, y, 0, radius);
}

//----------------------------------------------------------
void ofDrawIcoSphere(const ofPoint& position, float radius) {
    ofDrawIcoSphere(position.x,position.y,position.z,radius);
}

//----------------------------------------------------------
void ofDrawIcoSphere(float radius) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,radius,radius);
	ofMesh& sphere = getCached3dPrimitive( OF_3D_PRIMITIVE_ICO_SPHERE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( sphere );
    ofPopMatrix();
}

// Cylinder //
//----------------------------------------------------------
void ofSetCylinderResolution( int radiusSegments, int heightSegments, int capSegments ) {
    if(ofGetCylinderResolution() != ofVec3f( radiusSegments, heightSegments, capSegments )) {
        ((ofCylinderPrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_CYLINDER)).setResolution(radiusSegments, heightSegments, capSegments);
    }
}

//----------------------------------------------------------
ofVec3f ofGetCylinderResolution() {
    return ((ofCylinderPrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_CYLINDER)).getResolution();
}

//----------------------------------------------------------
void ofDrawCylinder(float x, float y, float radius, float height) {
    ofDrawCylinder( x, y, 0, radius, height );
}

//----------------------------------------------------------
void ofDrawCylinder(float x, float y, float z, float radius, float height) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,height,radius);
	m.translate(x,y,z);
	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_CYLINDER ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( mesh );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawCylinder(const ofPoint& position, float radius, float height) {
    ofDrawCylinder( position.x, position.y, position.z, radius, height );
}

//----------------------------------------------------------
void ofDrawCylinder(float radius, float height) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,height,radius);
	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_CYLINDER ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( mesh );
    ofPopMatrix();
}

// CONE //
//----------------------------------------------------------
void ofSetConeResolution( int radiusSegments, int heightSegments, int capSegments) {
    if(ofGetConeResolution() != ofVec3f( radiusSegments, heightSegments, capSegments )) {
        ((ofConePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_CONE)).setResolution(radiusSegments, heightSegments, capSegments);
    }
}

//----------------------------------------------------------
ofVec3f ofGetConeResolution() {
    return ((ofConePrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_CONE)).getResolution();
}

//----------------------------------------------------------
void ofDrawCone(float x, float y, float z, float radius, float height) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,height,radius);
	m.translate(x,y,z);
	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_CONE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( mesh );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawCone(float x, float y, float radius, float height) {
	ofDrawCone( x, y, 0, radius, height );
}

//----------------------------------------------------------
void ofDrawCone(const ofPoint& position, float radius, float height) {
	ofDrawCone( position.x, position.y, position.z, radius, height );
}

//----------------------------------------------------------
void ofDrawCone(float radius, float height) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(radius,height,radius);
	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_CONE ).getMesh();
    ofPushMatrix();
    ofMultMatrix(m);
    renderCached3dPrimitive( mesh );
    ofPopMatrix();
}

//----------------------------------------------------------
void ofCone(float x, float y, float z, float radius, float height) {
    ofDrawCone(x, y, z, radius, height);
}

//----------------------------------------------------------
void ofCone(float x, float y, float radius, float height) {
    ofDrawCone( x, y, 0, radius, height );
}

//----------------------------------------------------------
void ofCone(const ofPoint& position, float radius, float height) {
    ofDrawCone( position.x, position.y, position.z, radius, height );
}

//----------------------------------------------------------
void ofCone(float radius, float height) {
    ofDrawCone(radius, height );
}

// BOX //
//----------------------------------------------------------
void ofSetBoxResolution( int res ) {
    ofSetBoxResolution(res, res, res);
}

//----------------------------------------------------------
void ofSetBoxResolution( int resWidth, int resHeight, int resDepth ) {
    if(ofGetBoxResolution() != ofVec3f( resWidth, resHeight, resDepth )) {
        ((ofBoxPrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_BOX)).setResolution(resWidth, resHeight, resDepth);
    }
}

//----------------------------------------------------------
ofVec3f ofGetBoxResolution() {
    return ((ofBoxPrimitive&)getCached3dPrimitive(OF_3D_PRIMITIVE_BOX)).getResolution();
}

//----------------------------------------------------------
void ofDrawBox( float x, float y, float z, float width, float height, float depth) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(width,height,depth);
	m.translate(x,y,z);

    ofPushMatrix();
    ofMultMatrix(m);
    if(ofGetFill() == OF_FILLED) {
    	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_BOX ).getMesh();
        renderCached3dPrimitive( mesh );
    } else {
        ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_BOX_WIREFRAME ).getMesh();
        renderCached3dPrimitive( mesh );
    }
    ofPopMatrix();
}

//----------------------------------------------------------
void ofDrawBox(float x, float y, float z, float size) {
	ofDrawBox( x, y, z, size, size, size );
}

//----------------------------------------------------------
void ofDrawBox(const ofPoint& position, float width, float height, float depth) {
	ofDrawBox( position.x, position.y, position.z, width, height, depth );
}

//----------------------------------------------------------
void ofDrawBox(const ofPoint& position, float size) {
	ofDrawBox( position.x, position.y, position.z, size, size, size );
}

//----------------------------------------------------------
void ofDrawBox(float size) {
	ofDrawBox( size, size, size );
}

//----------------------------------------------------------
void ofDrawBox( float width, float height, float depth ) {
	static ofMatrix4x4 m;
	m.makeScaleMatrix(width,height,depth);
    ofPushMatrix();
    ofMultMatrix(m);
    if(ofGetFill() == OF_FILLED) {
    	ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_BOX ).getMesh();
        renderCached3dPrimitive( mesh );
    } else {
        ofMesh& mesh = getCached3dPrimitive( OF_3D_PRIMITIVE_BOX_WIREFRAME ).getMesh();
        renderCached3dPrimitive( mesh );
    }
    ofPopMatrix();
}

// deprecated methods //
//----------------------------------------------------------
void ofBox( float x, float y, float z, float width, float height, float depth) {
    ofDrawBox(x,y,z,width,height,depth);
}

//----------------------------------------------------------
void ofBox(float x, float y, float z, float size) {
    ofDrawBox( x, y, z, size, size, size );
}

//----------------------------------------------------------
void ofBox(const ofPoint& position, float width, float height, float depth) {
    ofDrawBox( position.x, position.y, position.z, width, height, depth );
}

//----------------------------------------------------------
void ofBox(const ofPoint& position, float size) {
    ofDrawBox( position.x, position.y, position.z, size, size, size );
}

//----------------------------------------------------------
void ofBox(float size) {
    ofDrawBox( size, size, size );
}

//----------------------------------------------------------
void ofBox( float width, float height, float depth ) {
    ofDrawBox(width,height,depth);
}


text:
package lingua.lexikon
package compiled
package fst

import scodec.bits._

import scala.annotation.tailrec

/** A compiled and compacted representation of a p-subsequential Fst in a format inspired by the HFST
 *  runtime format (http://www.ling.helsinki.fi/~klinden/pubs/fsmnlp2009runtime.pdf).
 *  The fact that we know the Fst is p-subsequential allows us for several assumptions:
 *   - at most one transition per input character in a given state
 *   - no epsilon-transitions
 *  Each transition may output several values, so the table of transitions looks a bit different than
 *  the one in HFST runtime format.
 *
 *  Initial state is always at index 0 in the transition index array.
 *
 *
 *  @author Lucas Satabin
 */
case class CompiledPSubFst(alphabet: Vector[Char], outputs: Vector[Out], tia: ByteVector, ta: Vector[PSubTransition], oa: Vector[Set[Seq[Int]]]) extends CompiledFst {

  private val alphabetMap =
    alphabet.zipWithIndex.toMap

  /** Size of a state in bytes */
  private val stateSize =
    5 + 6 * alphabet.size

  /** Lookup for the word in this Fst and returns the ordered sequence of outputs if it is found. */
  def lookup(word: String): Set[AnnotatedLemma] = {

    @tailrec
    def step(idx: Int, state: Int, acc: List[Int]): Set[AnnotatedLemma] =
      if (state >= 0) {
        val isFinal = tia(state) == 1
        if (idx >= word.size) {
          if (isFinal) {
            val outs = oa(tia.slice(state + 1, state + 5).toInt())
            if (outs.isEmpty) {
              val (root, anns) =
                acc.foldLeft((new StringBuilder, Set.empty[Annotation])) {
                  case ((root, anns), i) => outputs(i) match {
                    case CharOut(c)    => (root.append(c), anns)
                    case a: Annotation => (root, anns + a)
                  }
                }
              Set(AnnotatedLemma(root.toString.reverse, anns))
            } else {
              val res =
                for (out <- outs) yield {
                  val (root, anns) =
                    (out ++ acc).foldLeft((new StringBuilder, Set.empty[Annotation])) {
                      case ((root, anns), i) => outputs(i) match {
                        case CharOut(c)    => (root.append(c), anns)
                        case a: Annotation => (root, anns + a)
                      }
                    }
                  AnnotatedLemma(root.toString.reverse, anns)
                }
              res
            }
          } else {
            Set.empty
          }
        } else {
          val stateVector = tia.slice(state + 5, state + stateSize)
          val c = word(idx)
          val cidx = alphabetMap(c) * 6
          val ti = stateVector.slice(cidx, cidx + 6).toLong()
          ti match {
            case TransitionIndex(`c`, trans) =>
              // there exists a transition for the read symbol, collect the output and goto target
              val PSubTransition(_, out, target) = ta(trans)
              val acc1 = out.foldLeft(acc) {
                case (acc, -1) => alphabetMap(c) :: acc
                case (acc, n)  => n :: acc
              }
              step(idx + 1, target, acc1)
            case _ =>
              Set.empty
          }
        }
      } else {
        Set.empty
      }

    step(0, 0, Nil)
  }

}

object CompiledPSubFst {
  def apply(fst: CompiledFst): Option[CompiledPSubFst] = fst match {
    case fst @ CompiledPSubFst(_, _, _, _, _) => Some(fst)
    case _                                    => None
  }
}


text:
:wrench: hello world in Golang.

[![GoDoc](https://godoc.org/github.com/moul/golang-boilerplate?status.svg)](https://godoc.org/github.com/moul/golang-boilerplate)
[![Build Status](https://github.com/genzj/goTApaper/actions/workflows/build.yml/badge.svg)](https://github.com/genzj/goTApaper/actions/workflows/build.yml)

## Usage

```console
$ hello
Hello world !
```

## Install

```console
$ go get github.com/moul/golang-boilerplate/cmd/...
```

## Run with docker

```console
$ docker run moul/golang-boilerplate
Hello world !
```

## License

MIT

## Credit

* App icon is made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/).
* Systray icon [Sheet of Paper icon](https://icons8.com/icons/set/sheet-of-paper--v1) is made by [Icons8](https://icons8.com).


text:
import { Link } from 'gatsby';
import React, { memo } from 'react';

import ThemeSwitch from '~/components/ThemeSwitch';

import { Circle, Container, Title, TitleWrapper } from './styles';

interface Props {
  title: string;
  resetFilter?: () => void;
}

const Header = ({ title, resetFilter }: Props) => {
  return (
    <Container>
      <TitleWrapper>
        <Circle />
        <Title>
          <Link to={'/'} onClick={resetFilter}>{title}</Link>
        </Title>
      </TitleWrapper>
      <ThemeSwitch />
    </Container>
  );
};

export default memo(Header);


text:
{{ playerBar.songPlayer.currentSong.name }}

{{ playerBar.songPlayer.currentSong.name }} - {{ playerBar.songPlayer.currentAlbum.artist }}

{{ playerBar.songPlayer.currentAlbum.artist }}

                        <seek-bar value="{{ playerBar.songPlayer.currentTime }}" max="{{ playerBar.songPlayer.currentSong.length }}" on-change="playerBar.songPlayer.setCurrentTime(value)"></seek-bar>

 {{ playerBar.songPlayer.currentTime | timecode }}

{{ playerBar.songPlayer.currentSong.length | timecode }}

                    <seek-bar value="{{ playerBar.songPlayer.volume }}" max="100" on-change="playerBar.songPlayer.setVolume(value)"></seek-bar>


text:
if (wialon && typeof wianoti_loaded === 'undefined'){
	// console.log("Wialon Notifications: page side loaded");
	wianoti_loaded = true;

	var wianoti_interval = setInterval( function () {
		if( typeof WebCMS != 'undefined' && (WebCMS.init_finished || WebCMS.init_batch_finished) ){
			var resources = wialon.core.Session.getInstance().getItems("avl_unit");
			var res_arr = new Array();
			if(resources) {
				for (var i = 0; i < resources.length; i++) {
					var res = resources[i];
					res.addListener("messageRegistered", function(event){
						var item = event.getTarget();
						var msg = event.getData();
						if (!item || !msg) {
							return;
						}
						if (msg.tp == "ud" || msg.tp == "unm" || (msg.tp == "xx" && ((msg.f & 0xFF00) == 0x0900))){
							if(msg.p.text || msg.p.SOS || msg.p.image) {
								window.postMessage({
									type:'wialon_message',
									msg_type: (msg.p.text?'text':(msg.p.SOS?'sos':(msg.p.image?'image':''))),
									message:msg,
									name: item.getName()
								},'*');
							}
						}
					}, this);
					res_arr.push(res.getId());
				}
				window.postMessage({
					type:'wialon_message',
					msg_type: "system",
					message: "ok"
				},'*');
			}
			clearInterval(wianoti_interval);
		}
	} , 1000);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 14(5): 358 (1916)

#### Original name
Meliola piperina Syd. & P. Syd.

### Remarks
null


text:
import axios from 'axios';
import {reqhost} from './api'

export const getFutureWeather = params => axios.get(`${reqhost}/weather/future`, { params });

export const getNowWeather = params => axios.get(`${reqhost}/weather/now`, { params });


text:
#if !defined(BOOST_SPIRIT_ITERATOR_MAIN_HPP)
#define BOOST_SPIRIT_ITERATOR_MAIN_HPP

#include <boost/spirit/version.hpp>

///////////////////////////////////////////////////////////////////////////////
//
//  Master header for Spirit.Iterators
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/spirit/iterator/file_iterator.hpp>
#include <boost/spirit/iterator/fixed_size_queue.hpp>
#include <boost/spirit/iterator/position_iterator.hpp>
#include <boost/spirit/iterator/multi_pass.hpp>

#endif // !defined(BOOST_SPIRIT_ITERATOR_MAIN_HPP)


text:
export default {

  /**
   * cross browser addEvent
   * @param {string}   event The event to add
   * @param {Function} fn    [description]
   */
  add (element, event, fn) {
    // check if element is a compoenent
    element = element.root || element

    // avoid memory overhead of new anonymous functions for every event handler that's installed
    // by using local functions
    function listenHandler (e) {
      var ret = fn.apply(this, arguments)
      if (ret === false) {
        e.stopPropagation()
        e.preventDefault()
      }
      return (ret)
    }

    function attachHandler () {
      // set the this pointer same as addEventListener when fn is called
      // and make sure the event is passed to the fn also so that works the same too
      var ret = fn.call(element, window.event)
      if (ret === false) {
        window.event.returnValue = false
        window.event.cancelBubble = true
      }
      return (ret)
    }

    if (element.addEventListener) {
      element.addEventListener(event, listenHandler, false)
    } else {
      element.attachEvent('on' + event, attachHandler)
    }

    return this
  },

  /**
   * cross browser removeEvent
   * @param  {string}   event The event to remove
   * @param  {Function} fn    [description]
   * @return {Object}         [description]
   */
  remove (element, event, fn) {
    element = element.root || element

    if (element.removeEventListener) {
      element.removeEventListener(event, fn, false)
    } else if (element.detachEvent) {
      element.detachEvent('on' + event, element[fn.toString() + event])
      element[fn.toString() + event] = null
    } else {
      element['on' + event] = function () {}
    }

    return this
  }
}


text:
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import forms
from horizon import workflows

from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.aggregates import constants

class SetAggregateInfoAction(workflows.Action):
    name = forms.CharField(label=_("Name"),
                           max_length=255)

    availability_zone = forms.CharField(label=_("Availability Zone"),
                                        max_length=255)

    class Meta:
        name = _("Host Aggregate Info")
        help_text = _("From here you can create a new "
                      "host aggregate to organize instances.")
        slug = "set_aggregate_info"

    def clean(self):
        cleaned_data = super(SetAggregateInfoAction, self).clean()
        name = cleaned_data.get('name')

        try:
            aggregates = api.nova.aggregate_details_list(self.request)
        except Exception:
            msg = _('Unable to get host aggregate list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        if aggregates is not None:
            for aggregate in aggregates:
                if aggregate.name.lower() == name.lower():
                    raise forms.ValidationError(
                        _('The name "%s" is already used by '
                          'another host aggregate.')
                        % name
                    )
        return cleaned_data

class SetAggregateInfoStep(workflows.Step):
    action_class = SetAggregateInfoAction
    contributes = ("availability_zone",
                   "name")

class AddHostsToAggregateAction(workflows.MembershipAction):
    def __init__(self, request, *args, **kwargs):
        super(AddHostsToAggregateAction, self).__init__(request,
                                                        *args,
                                                        **kwargs)
        err_msg = _('Unable to get the available hosts')

        default_role_field_name = self.get_default_role_field_name()
        self.fields[default_role_field_name] = forms.CharField(required=False)
        self.fields[default_role_field_name].initial = 'member'

        field_name = self.get_member_field_name('member')
        self.fields[field_name] = forms.MultipleChoiceField(required=False)

        hosts = []
        try:
            hosts = api.nova.host_list(request)
        except Exception:
            exceptions.handle(request, err_msg)

        host_names = []
        for host in hosts:
            if host.host_name not in host_names and host.service == u'compute':
                host_names.append(host.host_name)
        host_names.sort()

        self.fields[field_name].choices = \
            [(host_name, host_name) for host_name in host_names]

    class Meta:
        name = _("Manage Hosts within Aggregate")
        slug = "add_host_to_aggregate"

class ManageAggregateHostsAction(workflows.MembershipAction):
    def __init__(self, request, *args, **kwargs):
        super(ManageAggregateHostsAction, self).__init__(request,
                                                         *args,
                                                         **kwargs)
        err_msg = _('Unable to get the available hosts')

        default_role_field_name = self.get_default_role_field_name()
        self.fields[default_role_field_name] = forms.CharField(required=False)
        self.fields[default_role_field_name].initial = 'member'

        field_name = self.get_member_field_name('member')
        self.fields[field_name] = forms.MultipleChoiceField(required=False)

        aggregate_id = self.initial['id']
        aggregate = api.nova.aggregate_get(request, aggregate_id)
        current_aggregate_hosts = aggregate.hosts

        hosts = []
        try:
            hosts = api.nova.host_list(request)
        except Exception:
            exceptions.handle(request, err_msg)

        host_names = []
        for host in hosts:
            if host.host_name not in host_names and host.service == u'compute':
                host_names.append(host.host_name)
        host_names.sort()

        self.fields[field_name].choices = \
            [(host_name, host_name) for host_name in host_names]

        self.fields[field_name].initial = current_aggregate_hosts

    class Meta:
        name = _("Manage Hosts within Aggregate")

class AddHostsToAggregateStep(workflows.UpdateMembersStep):
    action_class = AddHostsToAggregateAction
    help_text = _("You can add hosts to this aggregate. One host can be added "
                  "to one or more aggregate. You can also add the hosts later "
                  "by editing the aggregate.")
    available_list_title = _("All available hosts")
    members_list_title = _("Selected hosts")
    no_available_text = _("No hosts found.")
    no_members_text = _("No host selected.")
    show_roles = False
    contributes = ("hosts_aggregate",)

    def contribute(self, data, context):
        if data:
            member_field_name = self.get_member_field_name('member')
            context['hosts_aggregate'] = data.get(member_field_name, [])
        return context

class ManageAggregateHostsStep(workflows.UpdateMembersStep):
    action_class = ManageAggregateHostsAction
    help_text = _("You can add hosts to this aggregate, as well as remove "
                  "hosts from it.")
    available_list_title = _("All Available Hosts")
    members_list_title = _("Selected Hosts")
    no_available_text = _("No Hosts found.")
    no_members_text = _("No Host selected.")
    show_roles = False
    depends_on = ("id",)
    contributes = ("hosts_aggregate",)

    def contribute(self, data, context):
        if data:
            member_field_name = self.get_member_field_name('member')
            context['hosts_aggregate'] = data.get(member_field_name, [])
        return context

class CreateAggregateWorkflow(workflows.Workflow):
    slug = "create_aggregate"
    name = _("Create Host Aggregate")
    finalize_button_name = _("Create Host Aggregate")
    success_message = _('Created new host aggregate "%s".')
    failure_message = _('Unable to create host aggregate "%s".')
    success_url = constants.AGGREGATES_INDEX_URL
    default_steps = (SetAggregateInfoStep, AddHostsToAggregateStep)

    def handle(self, request, context):
        try:
            self.object = \
                api.nova.aggregate_create(
                    request,
                    name=context['name'],
                    availability_zone=context['availability_zone'])
        except Exception:
            exceptions.handle(request, _('Unable to create host aggregate.'))
            return False

        context_hosts_aggregate = context['hosts_aggregate']
        for host in context_hosts_aggregate:
            try:
                api.nova.add_host_to_aggregate(request, self.object.id, host)
            except Exception:
                exceptions.handle(
                    request, _('Error adding Hosts to the aggregate.'))
                return False

        return True

class ManageAggregateHostsWorkflow(workflows.Workflow):
    slug = "manage_hosts_aggregate"
    name = _("Add/Remove Hosts to Aggregate")
    finalize_button_name = _("Save")
    success_message = _('The Aggregate was updated.')
    failure_message = _('Unable to update the aggregate.')
    success_url = constants.AGGREGATES_INDEX_URL
    default_steps = (ManageAggregateHostsStep, )

    def handle(self, request, context):
        aggregate_id = context['id']
        aggregate = api.nova.aggregate_get(request, aggregate_id)
        current_aggregate_hosts = set(aggregate.hosts)
        context_hosts_aggregate = set(context['hosts_aggregate'])
        removed_hosts = current_aggregate_hosts - context_hosts_aggregate
        added_hosts = context_hosts_aggregate - current_aggregate_hosts
        try:
            for host in removed_hosts:
                api.nova.remove_host_from_aggregate(request,
                                                    aggregate_id,
                                                    host)
            for host in added_hosts:
                api.nova.add_host_to_aggregate(request, aggregate_id, host)
        except Exception:
            exceptions.handle(
                request, _('Error when adding or removing hosts.'))
            return False
        return True


text:
<?php
/**
 * @author   Viacheslav Nogin
 * @created  25.11.12 09:29
 */

/**
 * @namespace
 */
namespace Application;

use Application\Categories;
use Bluz\Controller\Controller;
use Bluz\Controller\Mapper\Crud;

/**
 * @accept HTML
 * @accept JSON
 * @privilege Management
 *
 * @param $parentId
 * @return mixed
 * @throws \Bluz\Application\Exception\ForbiddenException
 * @throws \Bluz\Application\Exception\NotImplementedException
 */
return function ($parentId = null) {
    /**
     * @var Controller $this
     */
    $this->assign('parentId', $parentId);

    $crud = new Crud();

    $crud->setCrud(Categories\Crud::getInstance());

    $crud->get('system', 'crud/get');
    $crud->post('system', 'crud/post');
    $crud->put('system', 'crud/put');
    $crud->delete('system', 'crud/delete');

    return $crud->run();
};


text:
namespace clotho {
namespace cuda {

struct curand_gen_base {
    curandGenerator_t gen;

    curand_gen_base( curandGenerator_t g ) : gen(g) {}

    virtual ~curand_gen_base() {}
};

}   // namespace cuda
}   // namespace clotho

#endif  // CURAND_GEN_BASE_HPP_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.zhaoliang</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>test2</artifactId>

    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>${pom.basedir}/src/main/resources</directory>
                <includes>
                    <include>*.properties</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>properties-maven-plugin</artifactId>
                <version>1.0.0</version>
                <executions>
                    <execution>
                        <id>default-cli</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>read-project-properties</goal>
                        </goals>
                        <configuration>
                            <files>
                                <file>${pom.basedir}/dev/jdbc.properties</file>
                            </files>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
//
//  KDS_RequestHelper.h
//  YHNetWorkDemo
//
//  Created by yehot on 15/11/17.
//  Copyright © 2015年 yehot. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "KDS_BaseRequest.h"

//自定义log
FOUNDATION_EXPORT void KDSNetLog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2);

/**
 *  网络库的公用方法工具类
 */
@interface KDS_RequestHelper : NSObject

/**
 *  将 dict 拼接到 url 后,以 ?key1=value1&key2=value2... 形式追加 (自动判断有无「?」)
 *
 *  @param component 全局统一追加的请求参数
 *  @param originUrl 初始url
 *
 *  @return 拼接后的url
 */
+ (NSString *)appendComponentDict:(NSDictionary *)component toOriginUrl:(NSString *)originUrl;

///字符串MD5加密
+ (NSString *)md5StringFromString:(NSString *)string;

///校验JSON格式
+ (BOOL)checkJSON:(id)json withValidator:(id)validator;

///  app 版本号
+ (NSString *)appVersionString;

@end

//  TODO:考虑是否不用这种写法
#pragma mark - KDS_BaseRequest Categoty
/**
 *  KDS_BaseRequest的私有Categoty(不对外直接暴露此Categoty)
 */
@interface KDS_BaseRequest (RequestAccessory)

//  TODO: 方法根据功能重新命名
/**
 *  hook 方法,在KDS_BaseRequest请求开始前(调用star)会被调用
 *  @remark 内部调用 requestWillStart:
 */
- (void)kds_toggleAccessoryWillStartCallBack;
/**
 *  hook 方法,在KDS_BaseRequest结束前(收到请求response)会被调用
 *  @remark 内部调用 requestWillStop:
 */
- (void)kds_toggleAccessoryWillStopCallBack;
/**
 *  hook 方法,在KDS_BaseRequest请求结束后(请求response call back 后)会被调用
 *  @remark 内部调用 requestDidStop:
 */
- (void)kds_toggleAccessoryDidStopCallBack;

@end


text: Mis programas Python para el curso de Intel Galileo