text:
package androidx.appcompat.app;

import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;

public class NightModeLateOnCreateActivity extends NightModeActivity {

    @Override
    public void onCreate(Bundle bundle) {
        // Disable night mode so that AppCompat attempts to re-apply during onCreate().
        disableAutomaticNightMode(getApplicationContext());

        super.onCreate(bundle);
    }

    private static void setNightMode(boolean enabled, Context context) {
        Configuration conf = context.getResources().getConfiguration();
        int mode = enabled ? Configuration.UI_MODE_NIGHT_YES : Configuration.UI_MODE_NIGHT_NO;
        conf.uiMode = mode | (conf.uiMode & ~Configuration.UI_MODE_NIGHT_MASK);

        // updateConfiguration is required to make the configuration change stick.
        // updateConfiguration must be called before any use of the actual Resources.
        context.getResources().updateConfiguration(conf,
                context.getResources().getDisplayMetrics());
    }

    /**
     * Ensure a context does not use night mode if the system setting enables night mode.
     *
     * <p>This must be called before a Context's Resources are used for the first time. {@code
     * Activity.onCreate} is a great place to call {@code disableAutomaticNightMode(this)}
     */
    public static void disableAutomaticNightMode(Context context) {
        setNightMode(false, context);
    }
}


text:
package com.architjn.materialicons.launchers;

import android.content.Context;
import android.content.Intent;

import com.architjn.materialicons.R;

public class SoloLauncher {
    public SoloLauncher(Context context) {
        Intent soloApply = context.getPackageManager().getLaunchIntentForPackage("home.solo.launcher.free");
        Intent solo = new Intent("home.solo.launcher.free.APPLY_THEME");
        solo.putExtra("EXTRA_PACKAGENAME", context.getPackageName());
        solo.putExtra("EXTRA_THEMENAME", context.getString(R.string.theme_title));
        context.sendBroadcast(solo);
        context.startActivity(soloApply);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace dioptre {
namespace physics {
namespace bullet {

DebugDrawer::DebugDrawer() : debugMode_(0) {
  graphics_ =
      dioptre::Locator::getInstance<dioptre::graphics::GraphicsInterface>(
          dioptre::Module::M_GRAPHICS);
}

void DebugDrawer::drawLine(const btVector3 &from, const btVector3 &to,
                           const btVector3 &color) {
  // TODO(tobscher) don't use magic numbers
  auto debug = (dioptre::graphics::Debug *)graphics_->getLayer(2);

  if (debug) {
    debug->addLine(glm::vec3(from.x(), from.y(), from.z()),
                   glm::vec3(to.x(), to.y(), to.z()));
  } else {
    std::cout << "DebugDrawer -  Error: "
              << "No debug drawer attached." << std::endl;
  }
}

void DebugDrawer::drawContactPoint(const btVector3 &PointOnB,
                                   const btVector3 &normalOnB,
                                   btScalar distance, int lifeTime,
                                   const btVector3 &color) {}

void DebugDrawer::reportErrorWarning(const char *warningString) {
  std::cout << "DebugDrawer - Error: " << warningString << std::endl;
}

void DebugDrawer::draw3dText(const btVector3 &location,
                             const char *textString) {}

} // bullet
} // physics
} // dioptre


text:
class TeamEventsController < ApplicationController
  def index
    @team   = find_team
    @events = events_index(find_team.events)
  end

  private

  def find_team
    Team.friendly.find(params[:team_id]).decorate
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" ><!-- 是否共用一个插补器 -->

    <translate
        android:duration="@android:integer/config_longAnimTime"
        android:fromYDelta="100%"
        android:interpolator="@interpolator/decelerate_quint"
        android:toYDelta="0" />

    <alpha
        android:duration="@android:integer/config_longAnimTime"
        android:fromAlpha="0.5"
        android:interpolator="@interpolator/decelerate_cubic"
        android:toAlpha="1.0" />

</set>


text:
package org.springframework.cloud.security.oauth2.client;

import java.net.URI;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateFactory;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;

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

/**
 * @author Dave Syer
 *
 */
public class OAuth2LoadBalancerClientAutoConfigurationTests {

	private ConfigurableApplicationContext context;

	@Rule
	public ExpectedException expected = ExpectedException.none();

	@After
	public void close() {
		if (this.context != null) {
			this.context.close();
		}
	}

	@Test
	public void userInfoNotLoadBalanced() {
		this.context = new SpringApplicationBuilder(ClientConfiguration.class)
				.properties("spring.config.name=test", "server.port=0", "spring.cloud.gateway.enabled=false",
						"security.oauth2.resource.userInfoUri:https://example.com")
				.run();

		assertThat(this.context.containsBean("loadBalancedUserInfoRestTemplateCustomizer")).isFalse();
		assertThat(this.context.containsBean("retryLoadBalancedUserInfoRestTemplateCustomizer")).isFalse();
	}

	@Test
	public void userInfoLoadBalancedNoRetry() throws Exception {
		this.context = new SpringApplicationBuilder(ClientConfiguration.class)
				.properties("spring.config.name=test", "server.port=0", "spring.cloud.gateway.enabled=false",
						"security.oauth2.resource.userInfoUri:https://nosuchservice",
						"security.oauth2.resource.loadBalanced=true")
				.run();

		assertThat(this.context.containsBean("loadBalancedUserInfoRestTemplateCustomizer")).isTrue();
		assertThat(this.context.containsBean("retryLoadBalancedUserInfoRestTemplateCustomizer")).isFalse();

		OAuth2RestTemplate template = this.context.getBean(UserInfoRestTemplateFactory.class).getUserInfoRestTemplate();
		ClientHttpRequest request = template.getRequestFactory().createRequest(new URI("https://nosuchservice"),
				HttpMethod.GET);
		expected.expectMessage("No instances available for nosuchservice");
		request.execute();
	}

	@EnableAutoConfiguration
	@Configuration(proxyBeanMethods = false)
	@EnableOAuth2Sso
	protected static class ClientConfiguration {

	}

}


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

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Uses of Interface com.leevilehtonen.cookagram.repository.RoleRepository (cook-a-gram 0.0.1-SNAPSHOT
        API)</title>
    <meta name="date" content="2017-08-17">
    <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of
        Interface
com.leevilehtonen.cookagram.repository.RoleRepository

No usage of com.leevilehtonen.cookagram.repository.RoleRepository

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

    Copyright © 2017 Pivotal Software, Inc.. All rights reserved.


text: Code from my algorithms course.


text:
var CACHE_NAME = 'sw-ex';
var CACHE_VERSION = 1;

var filesToCache = [
  './',
  './VAADIN/themes/mytheme/styles.css?v=8.1.5',
  './VAADIN/js/app.js',
  './VAADIN/images/logo.png'
];

self.oninstall = function(event) {
  event.waitUntil(
    self.skipWaiting().then(
      caches.open(CACHE_NAME + '-v' + CACHE_VERSION).then(function(cache) {
        return cache.addAll(filesToCache);
      })
    )
  );
};

self.onactivate = function(event) {
  event.waitUntil(
    self.clients.claim().then(function() {
      var currentCacheName = CACHE_NAME + '-v' + CACHE_VERSION;
      return caches.keys().then(function(cacheNames) {
        return Promise.all(
          cacheNames.map(function(cacheName) {
            if (cacheName.indexOf(CACHE_NAME) == -1) {
              return;
            }

            if (cacheName != currentCacheName) {
              return caches.delete(cacheName);
            }
          })
        );
      });
    })
  );
};

self.onfetch = function(event) {
  var request = event.request;
  event.respondWith(
    caches.match(request).then(function(response) {
      if (response) {
        return response;
      }

      return fetch(request).then(function(response) {
        var responseToCache = response.clone();
        caches.open(CACHE_NAME + '-v' + CACHE_VERSION).then(
          function(cache) {
            cache.put(request, responseToCache).catch(function(err) {
              console.warn(request.url + ': ' + err.message);
            });
          });
        return response;
      });
    })
  );
};

// Communicate via MessageChannel.
self.addEventListener('message', function(event) {
  console.log(`Received message from main thread: ${event.data}`);
  event.ports[0].postMessage(`Got message! Sending direct message back - "${event.data}"`);
});

// Broadcast via postMessage.
function sendMessage(message) {
  self.clients.matchAll().then(function(clients) {
    clients.map(function(client) {
      return client.postMessage(message);
    })
  });
}


text:
package de.unidue.ltl.evaluation.measures.categorial;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import de.unidue.ltl.evaluation.core.EvaluationData;
import de.unidue.ltl.evaluation.measures.categorial.Recall;
import de.unidue.ltl.evaluation.testing.TestUtils;

public class RecallTest {

	@Test
	public void recallTest(){
		EvaluationData<String> data = new EvaluationData<>(TestUtils.getExampleCategorial());
		assertEquals(0.6, new Recall<>(data).getRecallForLabel("A"), 0.001);
        assertEquals(0.833, new Recall<>(data).getRecallForLabel("B"), 0.001);
        assertEquals(0.625, new Recall<>(data).getRecallForLabel("C"), 0.001);
        assertEquals(0.686, new Recall<>(data).getMacroRecall(), 0.001);
	}

}


text:
package com.ogaclejapan.qiitanium.domain.core;

public abstract class Entity {

  public final String id;

  protected Entity(String id) {
    this.id = id;
  }

  @Override
  public boolean equals(final Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    Entity entity = (Entity) o;

    if (!id.equals(entity.id)) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return id.hashCode();
  }

}


text:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: './src/js/index-dev.js',

  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[chunkhash].js',
    chunkFilename: '[id].bundle.js'
  },

  devtool: 'cheap-source-map',

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: [path.join(__dirname, 'js', 'src')],
        exclude: [path.join(__dirname, 'node_modules')],
        use: {
          loader: 'babel-loader'
        }
      },
    ]
  },

  plugins: [
    new CleanWebpackPlugin(['dist'], {
      root: __dirname,
      exclude: ['favicon.ico'],
      verbose: true
    }),
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/templates/index.html'),
      hash: true,
      filename: 'index.html',
    }),
    new CopyWebpackPlugin([
      { from: 'assets', to: 'assets' }
    ]),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    })
  ],

  devServer: {
    host: 'localhost',
    port: 8080,
    inline: true, // live reloading
    stats: {
      colors: true,
      reasons: true,
      modules: false
    }
  },

  performance: {
    hints: false
  }
};


text:
require 'spec_helper'

describe RabbitJobs::Configuration do
  around(:each) do |example|
    old_config = RJ.instance_variable_get '@configuration'
    RJ.instance_variable_set '@configuration', nil
    example.run
    RJ.instance_variable_set '@configuration', old_config
  end

  it 'builds configuration from configure block' do
    RabbitJobs.configure do |c|
      c.disable_error_log

      c.server 'amqp://somehost.lan'

      c.queue 'durable_queue', durable: true,  auto_delete: false, manual_ack: true, arguments: { 'x-ha-policy' => 'all' }
      c.queue 'fast_queue',    durable: false, auto_delete: true,  manual_ack: false
    end

    RabbitJobs.config.to_hash.should == {
      error_log: false,
      server: 'amqp://somehost.lan',
      queues: {
        jobs: {
          auto_delete: false,
          exclusive: false,
          durable: true,
          manual_ack: true
        },
        durable_queue: {
          auto_delete: false,
          exclusive: false,
          durable: true,
          manual_ack: true,
          arguments: { 'x-ha-policy' => 'all' }
        },
        fast_queue: {
          auto_delete: true,
          exclusive: false,
          durable: false,
          manual_ack: false
        }
      }
    }
  end

  it 'builds configuration from yaml' do
    RabbitJobs.config.load_file(File.expand_path('../../fixtures/config.yml', __FILE__))

    RabbitJobs.config.to_hash.should == {
      server: 'amqp://example.com/vhost',
      queues: {
        durable_queue: {
          durable: true,
          exclusive: false,
          auto_delete: false,
          manual_ack: true,
          arguments: { 'x-ha-policy' => 'all' }
        },
        fast_queue: {
          durable: false,
          exclusive: false,
          auto_delete: true,
          manual_ack: false
        }
      }
    }
  end

  it 'use default value for #server' do
    RabbitJobs.config.to_hash.should == {
      error_log: true,
      server: 'amqp://localhost',
      queues: {
        jobs: {
          auto_delete: false,
          exclusive: false,
          durable: true,
          manual_ack: true
        }
      }
    }
  end

  it 'returns settings on some methods' do
    RabbitJobs.config.error_log.should eq true
    RabbitJobs.config.server.should eq 'amqp://localhost'
    RabbitJobs.config.routing_keys.should eq [:jobs]
  end
end


text:
select
	extract(month from c_date)
from
	alltypes
group by
	extract(month from c_date)
order by
	extract(month from c_date);


text:
package cz.tomkren.typewars;

import cz.tomkren.helpers.AB;

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

public class TypeVar implements Type {

    private final int id;

    public TypeVar(int id) {
        this.id = id;
    }

    @Override
    public Type applyMiniSub(int varId, Type type) {
        return id == varId ? type : this;
    }
    @Override
    public Type applySub(Sub sub) {
        Type t = sub.get(id);
        return t == null ? this : t;
    }

    @Override
    public AB<Type, Integer> freshenVars(int nextVarId, Sub newVars) {
        TypeVar newVar = (TypeVar) newVars.get(id);
        if (newVar == null) {
            newVar = new TypeVar(nextVarId);
            newVars.add(id,newVar);
            nextVarId++;
        }
        return new AB<>(newVar,nextVarId);
    }

    @Override
    public void getVarIds(Set<Integer> ret) {
        ret.add(id);
    }

    @Override
    public String toString() {
        return "x"+id;
    }

    public int getId() {
        return id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TypeVar typeVar = (TypeVar) o;

        if (id != typeVar.id) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id;
    }
}


text:
			<a href="<?php echo plugins_url( '../images/slider-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/slider-logo.png' , __FILE__ ); ?>">

Wordpress Slider

Huge-IT slider is an awesome WordPress slider plugin with a lot of nice features. Just install and build sliders in a few minutes.

Huge-IT Slider is a quick and easy way to add custom sliders to the WordPress websites (both to templates and posts/pages). The slider allows having unlimited amount of images with their titles and descriptions.

			View Plugin

			<a href="<?php echo plugins_url( '../images/potfolio-gallery-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/potfolio-gallery-logo.png' , __FILE__ ); ?>">

Wordpress Portfolio/Gallery

Portfolio Gallery is perfect for using for creating various portfolios or gallery within various views. The product allows adding descriptions and titles for each portfolio gallery. It is rather useful whever using with various pages and posts, as well as within custom location.

			View Plugin

			<a href="<?php echo plugins_url( '../images/lightbox-logo.jpg' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/lightbox-logo.jpg' , __FILE__ ); ?>">

Wordpress Lightbox

Lightbox is a perfect tool for viewing photos. It is created especially for simplification of using, permits you to view larger version of images and giving an interesting design. With the help of slideshow and various styles, betray a unique image to your website.

			View Plugin

			<a href="<?php echo plugins_url( '../images/video-gallery-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/video-gallery-logo.png' , __FILE__ ); ?>">

Wordpress Video Gallery

Video Gallery plugin was created and specifically designed to show your video files in unusual splendid ways. It has 5 good-looking views. Each are made in different taste so that you can choose any of them, according to the style of your website.

			View Plugin

			<a href="<?php echo plugins_url( '../images/share-buttons-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/share-buttons-logo.png' , __FILE__ ); ?>">

Wordpress Share Buttons

Social network is one of the popular places where people get information about everything in the world. Adding social share buttons into your blog or website page is very necessary and useful element for "socialization" of the project.

			View Plugin

			<a href="<?php echo plugins_url( '../images/google-maps-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/google-maps-logo.png' , __FILE__ ); ?>">

Wordpress Google Map

Huge-IT Google Map. One more perfect tool from Huge-IT. Improved Google Map, where we have our special contribution. Most simple and effective tool for rapid creation of individual Google Map in posts and pages.

			View Plugin

			<a href="<?php echo plugins_url( '../images/colorbox-logo.png' , __FILE__ ); ?>" rel="content"><img src="<?php echo plugins_url( '../images/colorbox-logo.png' , __FILE__ ); ?>">

Wordpress Colorbox

Huge-It Colorbox is the most spellbinding plugin in WordPress that implement Lightbox-effect look of the images and videos (when you click on the thumbnail of the image/video it nicely opens and increases in the same window with a beautiful effect).

			View Plugin


text:
php-callable-spy
================

PHP Callable Spy

Example:

    // Closure to be spied on
    $fn = function ($a, $b) {
        return $a + $b;
    };

    // Replace closure with a spy
    $fn = new \Callable\Spy($fn);

    echo $fn(5, 3); // Output: 8 (through spy proxy)

    // Gets last call made through spy proxy
    $lastCall = $fn->getLastCall();

    $timestamp = $lastCall->getDate();          // Timestamp of call
    $stackTrace = $lastCall->getStackTrace();   // Full stack-trace of call

    print_r($lastCall->getArgs());      // Output: [5, 3]
    print_r($lastCall->getResult());    // Output: 8

For more examples, have a look in the examples folder above!
Also, there are a lot more examples as tests in the test folder.


text:
package com.vzome.api;

import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Properties;

import com.vzome.core.commands.Command;
import com.vzome.core.editor.DocumentModel;
import com.vzome.core.editor.FieldApplication;
import com.vzome.core.editor.FieldApplication.SymmetryPerspective;
import com.vzome.core.exporters.Exporter3d;
import com.vzome.core.math.Polyhedron;
import com.vzome.core.render.Colors;
import com.vzome.core.render.Shapes;

public class Application
{
	private final com.vzome.core.editor.Application delegate;

	public Application()
	{
		this( new Command.FailureChannel() {

            @Override
			public void reportFailure( Command.Failure f )
			{
				f .printStackTrace();
			}
		}, null );
	}

	public Application( Command.FailureChannel failures )
	{
	    this( failures, null );
	}

	public Application( Command.FailureChannel failures, Properties props )
	{
		// TODO cleaner abstraction to wrap FailureChannel
	    this .delegate = new com.vzome.core.editor.Application( true, failures, props );
	}

	public Document loadDocument( InputStream bytes ) throws Exception
	{
		DocumentModel docDelegate = this .delegate .loadDocument( bytes );
		docDelegate .finishLoading( false, false );
		return new Document( docDelegate );
    }

    public Polyhedron getBallShape()
    {
        return getBallShape( "golden", "icosahedral", "default" );
    }

    public Polyhedron getBallShape( String fieldName, String symmetryName, String style )
    {
		FieldApplication fieldApp = this .delegate .getDocumentKind( fieldName );
		SymmetryPerspective symmPer = fieldApp .getSymmetryPerspective( symmetryName );
		for ( Shapes shapes : symmPer .getGeometries() ) {
			if ( shapes .getName() .equals( style ) )
				return shapes .getConnectorShape();
		}
		return null;
	}

	public Colors getColors()
	{
		return this .delegate .getColors();
	}

	public static void main( String[] args )
	{
        String format = "pov";
        if ( args.length > 0 )
            format = args[ 0 ];
        String urlStr = "http://vzome.com/models/2007/07-Jul/affine120-bop/purpleBlueOrange-affine120cell.vZome";
        if ( args.length > 1 )
            urlStr = args[ 1 ];
		Application app = new Application();
		try {
			InputStream bytes = new URL( urlStr ) .openStream();
			Document model = app .loadDocument( bytes );
            Exporter exporter = app .getExporter( format );
            exporter .doExport( model, new PrintWriter( System.out ), 1080, 1920 );
		} catch ( Exception e ) {
			e.printStackTrace();
		}

	}

    public Exporter getExporter( String format )
    {
        Exporter3d privateExp = this .delegate .getExporter( format );
        return new Exporter( privateExp );
    }

	public com.vzome.core.editor.Application getDelegate()
	{
		return this .delegate;
	}

	public Document createDocument( String fieldName )
	{
		DocumentModel docDelegate = this .delegate .createDocument( fieldName );
		return new Document( docDelegate );
	}
}


text:
.button {
	display: inline-block;
	vertical-align: middle;
	margin: 0;
	padding: 0;
	font: bold 13px "Helvetica Neue", Helvetica, Arial, clean, sans-serif !important;
	text-decoration: none !important;
	text-shadow: 1px 1px 2px rgba(0,0,0,0.20);
	background: none;
	border: none;
	white-space: nowrap;
	cursor: pointer;
	user-select: none;
	-moz-user-select: none;

	/* Fix extra width padding in IE */
	_width: 0;
	overflow: visible;
}

.button span {
	display: block;						/* Prevents :active from working in IE--oh well! */
	height: 24px;
	padding-right: 12px;
	background-repeat: no-repeat;
	background-position: right top;
}

.button span span {
	padding-right: 0;
	padding-left: 12px;
	line-height: 24px;
	background-position: left top;
}

.button span span span {
	padding-left: 21px;
	background-image: none;
	background-repeat: no-repeat;
	background-position: left center;
	/* IE6 still requires a PNG transparency fix */
	/* _background-image: none;		Or just hide icons from the undeserving IE6 */
	/* _padding-left: 0;					Or just hide icons from the undeserving IE6 */
}

.button span span span.after {
	padding-left: 0px;
	padding-right: 21px;
	background-position: right center;
	/* IE6 still requires a PNG transparency fix */
	/* _padding-right: 0;					Or just hide icons from the undeserving IE6 */
}

.button.sexyicononly span span span {
	padding-left: 16px;
}

.button.sexyicononly span span span.after {
	padding-left: 0px;
	padding-right: 16px;
}

.button[disabled],
.button[disabled]:hover,
.button[disabled]:focus,
.button[disabled]:active,
.button.disabled,
.button.disabled:hover,
.button.disabled:focus,
.button.disabled:active {
	color: #333 !important;
	cursor: inherit;
	text-shadow: none;
	opacity: 0.33;
}

.button:hover span,
.button:focus span {
	background-position: 100% -24px;
}

.button:hover span span,
.button:focus span span {
	background-position: 0% -24px;
}

.button:active span {
	background-position: 100% -48px;
}

.button:active span span {
	background-position: 0% -48px;
}

.button[disabled] span,
.button.disabled span {
	background-position: 100% -72px;
}

.button[disabled] span span,
.button.disabled span span {
	background-position: 0% -72px;
}

.button:hover span span span,
.button:focus span span span,
.button:active span span span,
.button[disabled] span span span,
.button.disabled span span span {
	background-position: left center;
}

.button:hover span span span.after,
.button:focus span span span.after,
.button:active span span span.after,
.button[disabled] span span span.after,
.button.disabled span span span.after {
	background-position: right center;
}

/*
 * Simple Skin Buttons
 */

.button.simple {
	position: relative;
	padding: 5px 10px 5px;
	font: inherit;
	font-size: 13px !important;
	font-style: normal !important;
	font-weight: bold !important;
	color: #fff !important;
	line-height: 1;
	background-image: url(images/skins/simple/awesome-overlay-sprite.png);
	background-repeat: repeat-x;
	background-position: 0 0;

	/* Special effects */
	text-shadow: 0 -1px 1px rgba(0,0,0,0.25), -2px 0 1px rgba(0,0,0,0.25);
	border-radius: 5px;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
	-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.5);

	/* IE only stuff */
	border-bottom: 1px solid transparent\9;
	_background-image: none;

	/* Cross browser inline block hack - http://blog.mozilla.com/webdev/2009/02/20/cross-browser-inline-block/ */
	display: -moz-inline-stack;
	display: inline-block;
	vertical-align: middle;
	*display: inline !important;
	position: relative;

	/* Force hasLayout in IE */
	zoom: 1;

	/* Disable text selection (Firefox only)*/
	-moz-user-select: none;
}

.button.simple::selection {
	background: transparent;
}

.button.simple:hover,
.button.simple:focus {
	background-position: 0 -50px;
	color: #fff !important;
}

.button.simple:active {
	background-position: 0 -100px;
	-moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.7);
	/* Unfortunately, Safari doesn't support inset yet */
	-webkit-box-shadow: none;

	/* IE only stuff */
	border-bottom: 0\9;
	border-top: 1px solid #666\9;
}

.button.simple[disabled],
.button.simple.disabled {
	background-position: 0 -150px;
	color: #333 !important;
	text-shadow: none;
}

.button.simple[disabled]:hover,
.button.simple[disabled]:focus,
.button.simple[disabled]:active,
.button.simple.disabled:hover,
.button.simple.disabled:focus,
.button.simple.disabled:active {
	-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
	-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
}

.button.simple span {
	height: auto;
	padding-left: 24px;
	padding-right: 0;
	background-position: left center;
	background-repeat: no-repeat;
	/* IE6 still requires a PNG transparency fix */
	/* _padding-left: 0;		Or just hide icons from the undeserving IE6 */
}

.button.simple span.after {
	padding-left: 0;
	padding-right: 24px;
	background-position: right center;
	/* IE6 still requires a PNG transparency fix */
	/* _padding-right: 0;		Or just hide icons from the undeserving IE6 */
}

.button.simple.sexyicononly span {
	height: 16px;
	padding-left: 16px;
}

.button.simple.sexyicononly span.after {
	padding-left: 0px;
	padding-right: 16px;
}

/* Simple button colors */
.button.simple					{ background-color: #333; }		/* Default */

/* Simple button sizes */

.button.simple                    { /* default */ }
.button.simple:active             { padding: 6px 10px 4px; }
.button.simple[disabled]:active,
.button.simple.disabled:active 	            { padding: 5px 10px 5px; }

.button span.ok				{ background-image: url(../images/icons/silk/tick.png) !important; }
.button span.cancel			{ background-image: url(../images/icons/silk/cross.png) !important; }
.button span.go			{ background-image: url(../images/icons/silk/arrow_right.png) !important; }
.button span.add		{ background-image: url(../images/icons/silk/add.png) !important; }
.button span.delete		{ background-image: url(../images/icons/silk/delete.png) !important; }

.button.simple:hover {
	background-color:	#181818;
}


text:
#include "dataserver/common/map_enum.h"
#include "dataserver/common/compact_map.h"
#include "dataserver/system/page_map.h"
#include "dataserver/bpool/page_bpool.h"

namespace sdl { namespace db {

class database_PageMapping : noncopyable {
    using page_bpool = bpool::page_bpool;
public:
    database_PageMapping(const std::string & fname, database_cfg const &);
    ~database_PageMapping();
    database_cfg const & cfg() const {
        return m_cfg;
    }
    bool use_page_bpool() const {
        return m_pool.get() != nullptr;
    }
    page_bpool * pool() const { // can be nullptr
        return m_pool.get();
    }
    page_bpool const * cpool() const { // can be nullptr
        return m_pool.get();
    }
    PageMapping const & pmap() const {
        SDL_ASSERT(m_pmap && !m_pool);
        return * m_pmap.get();
    }
    bool is_open() const;
    size_t page_count() const;
    std::thread::id init_thread_id() const;
private:
    database_cfg const m_cfg;
    std::unique_ptr<bpool::page_bpool> m_pool;
    std::unique_ptr<PageMapping const> m_pmap;
};

class database::shared_data final : public database_PageMapping {
    using map_sysalloc = compact_map<schobj_id, shared_sysallocunits>;
    using map_datapage = compact_map<schobj_id, shared_page_head_access>;
    using map_index = compact_map<schobj_id, pgroot_pgfirst>;
    using map_primary = compact_map<schobj_id, shared_primary_key>;
    using map_cluster = compact_map<schobj_id, shared_cluster_index>;
    using map_spatial_tree = compact_map<schobj_id, spatial_tree_idx>;
    struct data_type {
        shared_usertables usertable;
        shared_usertables internal;
        shared_datatables datatable;
        map_enum_1<map_sysalloc, dataType> sysalloc;
        map_enum_2<map_datapage, dataType, pageType> datapage; // not preloaded in init_database()
        map_enum_1<map_index, pageType> index;
        map_primary primary;
        map_cluster cluster;
        map_spatial_tree spatial_tree;
        data_type()
            : usertable(std::make_shared<vector_shared_usertable>())
            , internal(std::make_shared<vector_shared_usertable>())
            , datatable(std::make_shared<vector_shared_datatable>())
        {}
    };
public:
    bool initialized = false;
    const std::string filename;
    shared_data(const std::string & fname, database_cfg const & cfg)
        : database_PageMapping(fname, cfg)
        , filename(fname)
    {}
    shared_usertables & usertable() { // get/set shared_ptr only
        return m_data.usertable;
    }
    shared_usertables & internal() {
        return m_data.internal;
    }
    shared_datatables & datatable() {
        return m_data.datatable;
    }
    bool empty_usertable() {
        lock_guard lock(m_mutex);
        return m_data.usertable->empty();
    }
    bool empty_internal() {
        lock_guard lock(m_mutex);
        return m_data.internal->empty();
    }
    bool empty_datatable() {
        lock_guard lock(m_mutex);
        return m_data.datatable->empty();
    }
    std::pair<shared_sysallocunits, bool>
    find_sysalloc(schobj_id const id, dataType::type const data_type) {
        lock_guard lock(m_mutex);
        if (auto found = m_data.sysalloc.find(id, data_type)) {
            return { *found, true };
        }
        return{};
    }
    void set_sysalloc(schobj_id const id, dataType::type const data_type,
                      shared_sysallocunits const & value) {
        lock_guard lock(m_mutex);
        m_data.sysalloc(id, data_type) = value;
    }
    std::pair<shared_page_head_access, bool>
    find_datapage(schobj_id const id, dataType::type const data_type, pageType::type const page_type) {
        lock_guard lock(m_mutex);
        if (auto found = m_data.datapage.find(id, data_type, page_type)) {
            return { *found, true };
        }
        return{};
    }
    void set_datapage(schobj_id const id,
                      dataType::type const data_type,
                      pageType::type const page_type,
                      shared_page_head_access const & value) {
        lock_guard lock(m_mutex);
        m_data.datapage(id, data_type, page_type) = value;
    }
    std::pair<pgroot_pgfirst, bool> load_pg_index(schobj_id const id, pageType::type const page_type) {
        lock_guard lock(m_mutex);
        if (auto found = m_data.index.find(id, page_type)) {
            return { *found, true };
        }
        return{};
    }
    void set_pg_index(schobj_id const id, pageType::type const page_type, pgroot_pgfirst const & value) {
        lock_guard lock(m_mutex);
        m_data.index(id, page_type) = value;
    }
    std::pair<shared_primary_key, bool> get_primary_key(schobj_id const table_id) {
        lock_guard lock(m_mutex);
        auto const found = m_data.primary.find(table_id);
        if (found != m_data.primary.end()) {
            return { found->second, true };
        }
        return{};
    }
    void set_primary_key(schobj_id const table_id, shared_primary_key const & value) {
        lock_guard lock(m_mutex);
        m_data.primary[table_id] = value;
    }
    std::pair<shared_cluster_index, bool> get_cluster_index(schobj_id const id) {
        lock_guard lock(m_mutex);
        auto const found = m_data.cluster.find(id);
        if (found != m_data.cluster.end()) {
            return { found->second, true };
        }
        return{};
    }
    void set_cluster_index(schobj_id const id, shared_cluster_index const & value) {
        lock_guard lock(m_mutex);
        m_data.cluster[id] = value;
    }
    std::pair<spatial_tree_idx, bool> find_spatial_tree(schobj_id const table_id) {
        lock_guard lock(m_mutex);
        auto const found = m_data.spatial_tree.find(table_id);
        if (found != m_data.spatial_tree.end()) {
            return { found->second, true };
        }
        return{};
    }
    void set_spatial_tree(schobj_id const table_id, spatial_tree_idx const & value) {
        lock_guard lock(m_mutex);
        m_data.spatial_tree[table_id] = value;
    }
private:
    data_type const & const_data() const { return m_data; }
    data_type & data() { return m_data; }
    using lock_guard = std::lock_guard<std::mutex>;
    std::mutex m_mutex;
    data_type m_data; //FIXME: preload all and use read-only ?
};

} // db
} // sdl

#endif // __SDL_SYSTEM_DATABASE_IMPL_H__


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:duration="0"/>

    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="0"
        android:valueTo="180"
        android:propertyName="rotationY"
        android:interpolator="@anim/px_anticipate_overshoot_interpolator"
        android:duration="@integer/px_card_flip_time_full"/>

    <!-- Half-way through the rotation (see startOffset), set the alpha to 0 and restore the rotation. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:startOffset="@integer/px_card_flip_time_half"
        android:duration="1"/>

    <objectAnimator
        android:valueFrom="180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:startOffset="@integer/px_card_flip_time_full"
        android:duration="1"/>
</set>


text:
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using DotVVM.Framework.Compilation.Parser;
using DotVVM.Framework.Compilation.Parser.Dothtml.Parser;
using DotVVM.Framework.Compilation.Parser.Binding.Parser;
using DotVVM.Framework.Utils;
using DotVVM.Framework.Compilation.ControlTree;

namespace DotVVM.Framework.Compilation.Directives
{
    public class ServiceDirectiveCompiler : DirectiveCompiler<IAbstractServiceInjectDirective, ImmutableList<InjectedServiceExtensionParameter>>
    {
        private readonly ImmutableList<NamespaceImport> imports;

        public override string DirectiveName => ParserConstants.ServiceInjectDirective;

        public ServiceDirectiveCompiler(IReadOnlyDictionary<string, IReadOnlyList<DothtmlDirectiveNode>> directiveNodesByName, IAbstractTreeBuilder treeBuilder, ImmutableList<NamespaceImport> imports)
            : base(directiveNodesByName, treeBuilder)
        {
            this.imports = imports;
        }

        protected override IAbstractServiceInjectDirective Resolve(DothtmlDirectiveNode directiveNode)
        {
            var valueSyntaxRoot = ParseDirective(directiveNode, parser => parser.ReadImportDirectiveValue());

            if (valueSyntaxRoot is BinaryOperatorBindingParserNode assignment)
            {
                var name = assignment.FirstExpression as SimpleNameBindingParserNode;
                if (name == null)
                {
                    directiveNode.AddError($"Identifier expected on the left side of the assignment.");
                    name = new SimpleNameBindingParserNode("service");
                }
                var type = assignment.SecondExpression;
                return TreeBuilder.BuildServiceInjectDirective(directiveNode, name, type, imports);
            }
            else
            {
                directiveNode.AddError($"Assignment operation expected - the correct form is `@{ParserConstants.ServiceInjectDirective} myStringService = ISomeService<string>`");
                return TreeBuilder.BuildServiceInjectDirective(directiveNode, new SimpleNameBindingParserNode("service"), valueSyntaxRoot, imports);
            }
        }

        protected override ImmutableList<InjectedServiceExtensionParameter> CreateArtefact(IReadOnlyList<IAbstractServiceInjectDirective> directives) =>
            directives
            .Where(d => d.Type != null)
            .Select(d => new InjectedServiceExtensionParameter(d.NameSyntax.Name, d.Type!))
            .ToImmutableList();
    }

}


text:
/*
****************************************************************************************************************************
* DiLib v2.0 (dilib.dimutu.com)
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must
* not claim that you wrote the original software. If you use this
* software in a product, an acknowledgment in the product documentation
* would be appreciated.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
* 4. Third party open source "TinyXML" is used in this program, and for more information please see its own terms of use.
*******************************************************************************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DiTree
{
    public static class DiXMLElements
    {
        public const string XMLELEMENT_DILIB = "DiLIB";
        public const string XMLELEMENT_DILIB_VERSION = "version"; //file version

        public const string XMLELEMENT_TREEROOT = "TreeRoot"; //main xml header

        //configuration details
        public const string XMLELEMENT_CONFIG = "DiConfig"; //diconfig xml tag
        public const string XMLELEMENT_DEBUGID = "DebugID"; //configuration attribute diconfig

        public const string XMLELEMENT_HEADERFILELIST = "HeaderFiles";//all header file parent tag
        public const string XMLELEMENT_HEADERFIECOUNT = "Count";//header files attribute - count
        public const string XMLELEMENT_HEADERFILE = "File";//header file tag
        public const string XMLELEMENT_HEADERFILENAME = "Name"; //header file attribute - name

        //custom enumerations for return types
        public const string XMLELEMENT_CUSTOMRETURNENUMS = "CustomReturn";//all return type enum parent tag
        public const string XMLELEMENT_CUSTOMRETURNENUM_COUNT = "Count";//enum type attribute - count
        public const string XMLELEMENT_CUSTOMENUM = "ReturnType";//return enum tag
        public const string XMLELEMENT_CUSTOMENUM_NAME = "Enum"; //return enum attribute - name

        //data table
        public const string XMLELEMENT_ENUMLIST = "Enums"; //enums parent tag
        public const string XMLELEMENT_ENUMCOUNT = "Count"; //enums attribute count

        public const string XMLELEMENT_ENUM = "Enum"; //child element tag of Enums
        public const string XMLELEMENT_ENUMID = "ID"; //enum attribute
        public const string XMLELEMENT_ISTEMPLATE = "IsTemplate";//enum attribute
        public const string XMLELEMENT_CLASSTYPE = "ClassTypeID"; //enum attribute
        public const string XMLELEMENT_CLASSNAME = "ClassName"; //enum attribute
        public const string XMLELEMENT_TEMPLATECLASS = "TemplateClassName"; //enum attribute
        public const string XMLELEMENT_SCRIPTFILE = "ScriptFile"; //enum attribute

        //xml tags for the tree xml
        public const string XMLELEMENT_ROOTNODES = "RootNodes"; //all tree roots tag
        public const string XMLELEMENT_ROOTNODE_COUNT = "ChildCount"; //attribute

        public const string XMLELEMENT_ROOT = "RootNode"; //single tree root tag
        public const string XMLELEMENT_ROOTTEMPLATECLASS = "TemplateClassName"; //root node attribute
        public const string XMLELEMENT_ROOTDEBUGID = "RootDebugID"; //root node attribute - debug name or tab name

        public const string XMLELEMENT_NODE = "Node"; //individual tree node tag
        public const string XMLELEMENT_NODEENUMID = "EnumID"; //node attribute - enum id matching to data table
        public const string XMLELEMENT_NODETYPE = "TypeID"; //node attribute - class type
        public const string XMLELEMENT_NODECLASSNAME = "ClassName"; //node attribute - class name
        public const string XMLELEMENT_NODESCRIPT_FILE = "LuaScript"; //node attribute - script file
        public const string XMLELEMENT_NODEFILTERTASK = "Task"; //filter node attribute - child task enum id
        public const string XMLELEMENT_NODETIMER_INTERVAL = "TimerInterval"; //filter node attribute -
        public const string XMLELEMENT_NODECHILDCOUNT = "ChildCount"; //node attribute - if any children tasks in and will have the same of this
        public const string XMLELEMENT_NODEDEBUGID = "TaskDebugID"; //node attribute - debug identifier
        public const string XMLELEMENT_NODEREPEAT = "Repeat"; //filter node attribute
        public const string XMLELEMENT_NODEMAXREPEATS = "MaxRunCycle"; //filter node attribute
        public const string XMLELEMENT_NODETASKTRUE = "TaskTrue"; //condition node attribute - enum id of the task
        public const string XMLELEMENT_NODETASKFALSE = "TaskFalse";//condition node attribute - enum id of the task
        public const string XMLELEMENT_NODEBREAKPOINT = "Breakpoint"; //has a breakpoint
        public const string XMLELEMENT_NODEARGS = "TaskArgs"; //additional arguments passing to C++
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _08.Pokemon_Trainer
{
    public class Pokemon
    {
        public string name;
        public string element;
        public int health;

        public Pokemon(string name, string element, int health)
        {
            this.name = name;
            this.element = element;
            this.health = health;
        }
    }
}


text:
<?php
header('Content-type: application/json');
$reference = date("YmdHis");
$legend = $_POST['legend'];
$legend = str_replace('data:image/png;base64,', '', $legend);
$legend = str_replace(' ', '+', $legend);
$datalegend = base64_decode($legend);
$srclegend = '/var/www/htdocs/prints/legend-' . $reference .".png";
file_put_contents($srclegend, $datalegend);
$map = $_POST['map'];
$map = str_replace('data:image/png;base64,', '', $map);
$map = str_replace(' ', '+', $map);
$datamap = base64_decode($map);
$srcmap = '/var/www/htdocs/prints/map-' . $reference .".png";
if (file_put_contents($srcmap, $datamap)) {
    echo '{"success":true, "job":'.json_encode($reference).'}';
}
else //Sinon (la fonction renvoie FALSE).
{
   echo '{"success":false, "message": "erreur"}';
}
?>


text:
package io.dazraf.vertx.futures.processors;

import java.util.function.Function;

import io.dazraf.vertx.futures.Futures;
import io.vertx.core.Future;

/**
 * A unit that processes the state of a {@link Futures} chain; returning another {@link Future}
 * @param <T1> the type expected from the {@link Futures} chain
 * @param <T2> the type emitted as a {@link Future} from the processor
 */
@FunctionalInterface
public interface FutureProcessor<T1, T2> extends Function<Future<T1>, Future<T2>> {
}


text:
<?php

namespace PHPCI;

use PHPCI\Model\Build;

/**
 * PHPCI Plugin Interface - Used by all build plugins.
 *
 * @author   Dan Cryer <dan@block8.co.uk>
 */
interface ZeroConfigPlugin
{
    public static function canExecute($stage, Builder $builder, Build $build);
}


text:
package org.apache.yoko.util.cmsf;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import javax.rmi.CORBA.Util;

public enum RepIds {
    ;

    public interface Query {
        public Query suffix(String suffix);
        public Query codebase(String codebase);
        public Class<?> toClass();
        public String toClassName();
    }

    private static final class QueryImpl implements Query {
        public final String repid;
        public final String suffix;
        public final String codebase;

        private QueryImpl(String repid) {
            this(Objects.requireNonNull(repid), "", null);
        }

        private QueryImpl(String repid, String suffix, String codebase) {
            this.repid = repid;
            this.suffix = suffix;
            this.codebase = codebase;
        }

        @Override
        public QueryImpl suffix(String suffix) {
            return new QueryImpl(repid, Objects.requireNonNull(suffix), codebase);
        }

        @Override
        public QueryImpl codebase(String codebase) {
            return new QueryImpl(repid, suffix, codebase);
        }

        @Override
        public Class<?> toClass() {
            return RepIds.toClass(this);
        }

        @Override
        public String toClassName() {
            return RepIds.toClassName(this);
        }
    }

    private static final Logger LOGGER = Logger.getLogger(RepIds.class.getName());

    public static Query query(String repid) {
        return new QueryImpl(repid);
    }

    private static Class<?> toClass(final QueryImpl query) {
        final String repid = query.repid;
        final String suffix = query.suffix;
        final String codebase = query.codebase;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(String.format("Searching for class from repid \"%s\" using suffix \"%s\"", repid, suffix));
        Class<?> result = null;

        //Special case IDL:omg.org/CORBA/WStringValue:1.0
        if ("IDL:omg.org/CORBA/WStringValue:1.0".equals(repid) && "".equals(suffix)) return String.class;

        final String className = toClassName(query);

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(String.format("Class name from repid \"%s\" using suffix \"%s\" is \"%s\"", repid, suffix, className));

        if (className != null) {
            try {
                // get the appropriate class for the loading.
                ClassLoader loader = Thread.currentThread().getContextClassLoader();
                result = Util.loadClass(className, codebase, loader);
            } catch (ClassNotFoundException ex) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(String.format("Class \"%s\" not found", className));
                // ignore
            }
        }

        return result;
    }

    private static final Pattern dotPattern = Pattern.compile(Pattern.quote("."));
    private static final Pattern slashPattern = Pattern.compile(Pattern.quote("/"));

    private static String toClassName(QueryImpl query) {
        final String repid = query.repid;
        final String suffix = query.suffix;

        //Special case IDL:omg.org/CORBA/WStringValue:1.0
        if ("IDL:omg.org/CORBA/WStringValue:1.0".equals(repid) && "".equals(suffix)) return String.class.getName();

        String result = null;
        if (repid.startsWith("IDL:")) {
            result = idlToClassName(repid);
        } else if (repid.startsWith("RMI:")) {
            result = rmiToClassName(repid);
        }
        if (result != null) {
            result += suffix;
            result = removeUnicodeEscapes(result);
        }
        return result;
    }

    private static String rmiToClassName(final String repid) {
        String result;
        final int end = repid.indexOf (':', 4);
        result = end < 0 ? repid.substring (4) : repid.substring (4, end);
        return result;
    }

    private static String idlToClassName(final String repid) {
        try {
            final StringBuilder sb = new StringBuilder(repid.length());

            final int end = repid.lastIndexOf(':');
            String s = end < 0 ? repid.substring(4) : repid.substring(4, end);

            //
            // reverse order of dot-separated name components up
            // till the first slash.
            //
            final int firstSlash = s.indexOf('/');
            if (firstSlash > 0) {
                String prefix = s.substring(0, firstSlash);
                String[] elems = dotPattern.split(prefix);
                Collections.reverse(Arrays.asList(elems)); //reverses the order in the underlying array - i.e. 'elems'
                for (String elem: elems) {
                    sb.append(fixName(elem)).append('.');
                }

                s = s.substring(firstSlash + 1);
            }

            //
            // Append slash-separated name components ...
            //
            for (String elem: slashPattern.split(s)) {
                sb.append(fixName(elem)).append('.');
            }
            sb.deleteCharAt(sb.length() - 1); // eliminate final '.'

            return sb.toString();
        } catch (IndexOutOfBoundsException ex) {
            // id has bad format
            return null;
        }
    }

    private static String removeUnicodeEscapes(String in) {
        // if no escape sequences are in the string, this is easy
        int escape = in.indexOf("\\U");
        if (escape < 0) {
            return in;
        }

        StringBuilder out = new StringBuilder(in.length());
        int start = 0;

        while (escape >= 0) {
            out.append(in.substring(start, escape));
            // step over the escape sequence
            escape += 2;

            int value = 0;
            for (int i=0; i<4; i++) {
                char ch = in.charAt(escape++);
                switch (ch) {
                  case '0':
                  case '1':
                  case '2':
                  case '3':
                  case '4':
                  case '5':
                  case '6':
                  case '7':
                  case '8':
                  case '9':
                     value = (value << 4) + ch - '0';
                     break;
                  case 'a':
                  case 'b':
                  case 'c':
                  case 'd':
                  case 'e':
                  case 'f':
                     value = (value << 4) + 10 + ch - 'a';
                     break;
                  case 'A':
                  case 'B':
                  case 'C':
                  case 'D':
                  case 'E':
                  case 'F':
                     value = (value << 4) + 10 + ch - 'A';
                     break;
                  default:
                      // not sure what to do here.  Just treat it as a 0 nibble
                      value = (value << 4);
                }
            }
            // now append this as a char value
            out.append((char)value);
            // now step and find the next one
            start = escape;
            escape = in.indexOf("\\U", escape);
        }
        // don't forget the trailing segment
        if (start < in.length()) {
            out.append(in.substring(start));
        }
        return out.toString();
    }

    private static final Set<String> keywords = createStringSet(
            "abstract", "assert", "boolean", "break", "byte", "case",
            "catch", "char", "class", "clone", "const", "continue",
            "default", "do", "double", "else", "equals", "extends",
            "false", "final", "finalize", "finally", "float", "for",
            "getClass", "goto", "hashCode", "if", "implements", "import",
            "instanceof", "int", "interface", "long", "native", "new",
            "notify", "notifyAll", "null", "package", "private",
            "protected", "public", "return", "short", "static", "super",
            "switch", "synchronized", "this", "throw", "throws",
            "toString", "transient", "true", "try", "void", "volatile",
            "wait", "while");

    private static Set<String> createStringSet(String...strings) {
        return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(strings)));
    }

    private static final List<String> reservedSuffixes = createStringList(
            "Helper", "Holder", "Operations", "POA",
            "POATie", "Package", "ValueFactory");

    private static List<String> createStringList(String...strings) {
        return Collections.unmodifiableList(Arrays.asList(strings));
    }

    private static String fixName(String name) {
        assert(name.indexOf('.') == -1); // Not for absolute names

        int nameLen = name.length();
        if (nameLen == 0)
            return name;

        if (keywords.contains(name)) return "_" + name;

        //
        // Prepend an underscore for each of the reserved suffixes
        //
        String result = name;
        String curr = name;

        OUTER_LOOP: while (true) {
            for (String reservedSuffix: reservedSuffixes) {
                if (curr.endsWith(reservedSuffix)) {
                    result = "_" + result;

                    int currLength = curr.length();
                    int resLength = reservedSuffix.length();
                    if (currLength == resLength)
                        return result;
                    curr = curr.substring(0, currLength - resLength);
                    continue OUTER_LOOP;
                }
            }
            return result;
        }
    }
}


text:
package commentService

import (
	"errors"
	"net/http"

	"github.com/dorajistyle/goyangi/config"
	"github.com/dorajistyle/goyangi/db"
	"github.com/dorajistyle/goyangi/model"
	"github.com/dorajistyle/goyangi/service/userService"
	"github.com/dorajistyle/goyangi/service/userService/userPermission"
	"github.com/dorajistyle/goyangi/util/log"
	"github.com/dorajistyle/goyangi/util/modelHelper"
	"github.com/dorajistyle/goyangi/util/pagination"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// AssignRelatedUser assign related user of comment.
func AssignRelatedUser(comments []model.Comment) {
	for i, comment := range comments {
		var tempUser model.User
		if db.ORM.Model(&comment).Select(config.UserPublicFields).Related(&tempUser).RecordNotFound() {
			log.Warn("user is not found.")
		}
		// comments[i].User = model.PublicUser{User: &tempUser}
		comments[i].User = tempUser
	}
}

// CreateComment creates a comment.
func CreateComment(c *gin.Context, item interface{}) (int, error) {
	var form CreateCommentForm
	var comment model.Comment
	user, userErr := userService.CurrentUser(c)
	log.Debugf("user error : %s\n", userErr)
	if userErr != nil {
		return http.StatusForbidden, userErr
	}
	form.UserId = user.Id
	if db.ORM.First(item, c.Param("id")).RecordNotFound() {
		return http.StatusNotFound, errors.New("Item is not found.")
	}

	bindErr := c.MustBindWith(&form, binding.Form)
	log.Debugf("bind error : %s\n", bindErr)
	if bindErr != nil  {
		return http.StatusInternalServerError, errors.New("Invalid form.")
	}

	log.Debugf("comment_form : %v", form)

	modelHelper.AssignValue(&comment, &form)
	if db.ORM.Model(item).Association("Comments").Append(comment).Error != nil {
		return http.StatusInternalServerError, errors.New("Comment is not created.")
	}
	return http.StatusOK, nil
}

// RetrieveComments retrieves comments.
func RetrieveComments(item interface{}, currentPages ...int) (model.CommentList) {
	var comments []model.Comment
	var currentPage int
	if len(currentPages) > 0 {
		currentPage = currentPages[0]
	} else {
		currentPage = 1
	}
	count := db.ORM.Model(item).Association("Comments").Count()
	offset, currentPage, hasPrev, hasNext := pagination.Paginate(currentPage, config.CommentPerPage, count)
	db.ORM.Limit(config.CommentPerPage).Order(config.CommentOrder).Offset(offset).Model(item).Association("Comments").Find(&comments)
	AssignRelatedUser(comments)
	log.Debugf("comments : %v", comments)
	return model.CommentList{Comments: comments, HasPrev: hasPrev, HasNext: hasNext, Count: count, CurrentPage: currentPage}
}

// UpdateComment updates a comment.
func UpdateComment(c *gin.Context, item interface{}) (int, error) {
	var form CommentForm
	var comment model.Comment
	itemId := c.Params.ByName("id")

	if db.ORM.First(item, itemId).RecordNotFound() {
		return http.StatusNotFound, errors.New("Item is not found.")
	}

	bindErr := c.MustBindWith(&form, binding.Form)
	log.Debugf("bind error : %s\n", bindErr)
	if bindErr != nil  {
		return http.StatusInternalServerError, errors.New("Invalid form.")
	}

	if db.ORM.First(&comment, form.CommentId).RecordNotFound() {
		return http.StatusNotFound, errors.New("Comment is not found.")
	}
	status, err := userPermission.CurrentUserIdentical(c, comment.UserId)
	if err != nil {
		return status, err
	}
	comment.Content = form.Content
	if db.ORM.Save(&comment).Error != nil {
		return http.StatusInternalServerError, errors.New("Article comment's count is not updated.")
	}
	return http.StatusOK, nil
}

// DeleteComment deletes a comment.
func DeleteComment(c *gin.Context, item interface{}) (int, error) {
	itemId := c.Params.ByName("id")
	commentId := c.Params.ByName("commentId")
	var comment model.Comment
	log.Debugf("item id : %d , comment id : %d \n", itemId, commentId)
	if db.ORM.First(item, itemId).RecordNotFound() {
		return http.StatusNotFound, errors.New("Item is not found.")
	}
	if db.ORM.First(&comment, commentId).RecordNotFound() {
		return http.StatusNotFound, errors.New("Comment is not found.")
	}
	status, err := userPermission.CurrentUserIdentical(c, comment.UserId)
	if err != nil {
		return status, err
	}
	db.ORM.Model(item).Association("Comments").Delete(comment)
	if db.ORM.Delete(&comment).Error != nil {
		return http.StatusInternalServerError, errors.New("Comment is not deleted.")
	}
	return http.StatusOK, nil
}


text:
var gulp = require('gulp');

var webpack = require('gulp-webpack');
var webpackConfig = require('../webpack.config.js');
var rm = require('gulp-rimraf');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var minifycss = require('gulp-minify-css');
var sequence = require('run-sequence');
var all = require('gulp-all');
var mcss = require('gulp_mcss');

var structure = require('../structure.js');
var buildAll = require('../doc-src/buildAll.js');

/**
 * ------------------------------------------------------------
 * Build Doc
 * ------------------------------------------------------------
 */

gulp.task('doc-clean', function() {
    return gulp.src('./doc', {read: false}).pipe(rm());
});

gulp.task('doc-copy', function() {
    return all(
        gulp.src('./doc-src/assets/**').pipe(gulp.dest('./doc')),
        gulp.src('./node_modules/font-awesome/fonts/**').pipe(gulp.dest('./doc/fonts')),
        gulp.src([
            './node_modules/regularjs/dist/regular.min.js',
            './node_modules/marked/marked.min.js'
        ]).pipe(gulp.dest('./doc/vendor'))
    );
});

gulp.task('doc-js', function() {
    return gulp.src('./src/js/index.js')
        .pipe(webpack(webpackConfig))
        .pipe(rename({suffix: '.min'}))
        .pipe(uglify())
        .pipe(gulp.dest('./doc/js'));
});

gulp.task('doc-css', function() {
    var gulpCSS = function(theme) {
        return [
            gulp.src('./src/mcss/' + theme + '.mcss')
                .pipe(mcss({
                    pathes: ['./node_modules'],
                    importCSS: true
                }))
                .pipe(rename('regular-ui.' + theme + '.css'))
                .pipe(rename({suffix: '.min'}))
                .pipe(minifycss())
                .pipe(gulp.dest('./doc/css')),
            gulp.src('./doc-src/mcss/' + theme + '.mcss')
                .pipe(mcss({
                    pathes: ['./node_modules'],
                    importCSS: true
                }))
                .pipe(rename('doc.' + theme + '.min.css'))
                .pipe(minifycss())
                .pipe(gulp.dest('./doc/css'))
        ];
    }

    return all(Array.prototype.concat.apply([], structure.themes.map(gulpCSS)));
});

gulp.task('doc-build', function(done) {
    return buildAll(done);
});

gulp.task('doc', function(done) {
    sequence('doc-clean', 'doc-copy', ['doc-js', 'doc-css', 'doc-build'], done);
});

/**
 * ------------------------------------------------------------
 * Sync to GitHub Page
 * If start `page` task, `doc` task will be running in advance.
 * ------------------------------------------------------------
 */

gulp.task('page-clean', function() {
    return gulp.src([
        '../regular-ui.github.io/*',
        '!../regular-ui.github.io/README.md'
    ], {read: false}).pipe(rm({force: true}));
});

gulp.task('page-copy', function() {
    return gulp.src('./doc/**').pipe(gulp.dest('../regular-ui.github.io'));
});

gulp.task('page', function(done) {
    sequence(['doc', 'page-clean'], ['page-copy'], done);
});


text:
<title>
No place for red-baiting in our movement
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

No place for red-baiting in our movement

February 7, 2003 | Page 4

Dear Socialist Worker,

Some socialist groups in the antiwar movement are being smeared--both by people within the movement and commentators outside of it. This is red-baiting--and is often dressed up in the (incorrect) argument that socialist politics will scare people away from the antiwar movement.

Recently on the National Public Radio show "Fresh Air," Vietnam War-era activist Todd Gitlin blasted the antiwar organization International ANSWER. Gitlin called the politics of the group, and the Workers World Party behind it, "freakish"--citing spokesperson Ramsey Clark's support for Slobodan Milosevic and criticizing the top-down organizing structure.

In the same breath, Gitlin asserted that support for political prisoner Mumia Abu-Jamal and solidarity with Palestinians--campaigns that the Workers World Party is active in--are political issues that "have no place in the antiwar movement."

So much for "democracy." Apparently Gitlin feels he has the authority to declare what issues do and don't belong in the movement. His argument is that any politics beyond mainstream liberalism aren't welcome in the antiwar movement.

Antiwar activists should argue against the Workers World Party's sympathy for Stalinist regimes, as well the top-down structure of ANSWER. But we need to defend groups from attacks that are made just because they're socialists.

Arguing for a broad antiwar movement that includes many points of view will benefit the movement--making it a democratic one characterized by healthy discussion and debate. This is the only kind of movement that will be able to take on Bush.

Khury Petersen-Smith, Rochester, N.Y.

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright Terracotta, Inc.

    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.

-->
<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">
  <parent>
    <artifactId>nms-entity</artifactId>
    <groupId>org.terracotta.management</groupId>
    <version>5.7-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>nms-entity-server</artifactId>
  <name>Terracotta Management :: NMS Entity :: Server</name>

  <dependencies>
    <!-- common server classpath -->
    <dependency>
      <groupId>org.terracotta.management</groupId>
      <artifactId>monitoring-service-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <!-- inside jar -->
    <dependency>
      <groupId>org.terracotta.management</groupId>
      <artifactId>nms-entity-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.terracotta.voltron.proxy</groupId>
      <artifactId>voltron-proxy-server</artifactId>
      <version>${project.version}</version>
    </dependency>

    <!-- provided by voltron (server) -->
    <dependency>
      <groupId>org.terracotta</groupId>
      <artifactId>entity-server-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.terracotta</groupId>
      <artifactId>standard-cluster-services</artifactId>
      <scope>provided</scope>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>true</shadedArtifactAttached>
              <shadedClassifierName>plugin</shadedClassifierName>
              <!-- we have to make sure no voltron api comes in the shaded jar -->
              <artifactSet>
                <includes>
                  <!--
                    management-model must be set as an api library in voltron
                    it is used by the NMS Agent Entity and other entities
                   -->
                  <include>org.terracotta.management:nms-entity-common</include>
                  <include>org.terracotta.voltron.proxy:voltron-proxy-common</include>
                  <include>org.terracotta.voltron.proxy:voltron-proxy-server</include>
                </includes>
              </artifactSet>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>


text:
package dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules;

import dagger.Module;
import dagger.Provides;
import dk.statsbiblioteket.digital_pligtaflevering_aviser.harness.ConfigurationMap;
import io.vavr.control.Try;

import javax.enterprise.inject.Produces;
import javax.inject.Named;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.function.Function;

import static dk.statsbiblioteket.medieplatform.autonomous.iterator.bitrepository.IngesterConfiguration.BITMAG_BASEURL_PROPERTY;

/**
 * Dagger module for bitrepository related dependencies.
 */
@Module
public class BitRepositoryModule {

    public static final String BITREPOSITORY_SBPILLAR_MOUNTPOINT = "bitrepository.sbpillar.mountpoint";
    public static final String PROVIDE_ENCODE_PUBLIC_URL_FOR_FILEID = "provide.encode.public.url.for.fileid";

    /**
     * This is the base url for the public exposure of a given file ingested in the BitRepository.  This
     * is stored as the URL of the CONTENTS datastream.
     * For the SB pillar we can remove this prefix from the URL and get the actual relative filename on disk.
     * Typically this is stored
     *
     * @param map configuration map
     * @return the configuration parameter provided (required)
     */
    @Produces
    @Provides
    public
    @Named(BITMAG_BASEURL_PROPERTY)
    String provideBitrepositoryBaseUrl(ConfigurationMap map) {
        return map.getRequired(BITMAG_BASEURL_PROPERTY);
    }

    /**
     * The SB Bitrepository pillar allows direct access to the files in the repository, typically
     * in the form of a NFS mount point from where the file path can be resolved.
     *
     * @param map configuration map
     * @return the configuration parameter provided (required)
     */
    @Produces
    @Provides
    @Named(BITREPOSITORY_SBPILLAR_MOUNTPOINT)
    String getPutfileDestinationPath(ConfigurationMap map) {
        return map.getRequired(BITREPOSITORY_SBPILLAR_MOUNTPOINT);
    }

    @Produces
    @Provides
    @Named(PROVIDE_ENCODE_PUBLIC_URL_FOR_FILEID)
    public Function<String, String> provideEncodePublicURLForFileID(@Named(BITMAG_BASEURL_PROPERTY) String bitmagUrl) {

        return fileID -> {
            Path path = Paths.get(fileID);

            StringJoiner sj = new StringJoiner("/");
            for (Path name : path) {
                // We must encode _twice_ to get #'s right in the DOMS external link.
                sj.add(Try.of(() -> URLEncoder.encode(URLEncoder.encode(name.toString(), "UTF-8"), "UTF-8")).get());
            }
            return bitmagUrl + sj;
        };
    }
}


text:
"""
Setup file for numdifftools.

Usage:
Run doctests on documentation:
  python setup.py doctest

Build documentation
  python setup.py docs

Build
  python setup.py bdist_wininst
  python setup.py bdist_wheel --universal
  python setup.py sdist

Recommended build
  git pull origin
  git shortlog v0.9.40..HEAD -w80 --format="* %s" --reverse > log.txt
# update CHANGELOG.rst with info from log.txt
# update numdifftools.info (this file will be the generated README.rst)
  python build_package.py 0.9.42rc0
  git commit
  git tag v0.9.42rc0 master
  git push --tags

PyPi upload:
  twine check dist/*   # check
  twine upload dist/*  # wait until the travis report is OK before doing this step.

Notes
-----
Don't use package_data and/or data_files, use include_package_data=True and MANIFEST.in instead!
Don't hard-code the list of packages, use setuptools.find_packages() instead!

See also
--------
https://docs.pytest.org/en/latest/goodpractices.html
https://python-packaging.readthedocs.io/en/latest/
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
https://chriswarrick.com/blog/2014/09/15/python-apps-the-right-way-entry_points-and-scripts/
https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure
https://ep2015.europython.eu/media/conference/slides/less-known-packaging-features-and-tricks.pdf
https://realpython.com/documenting-python-code/#public-and-open-source-projects

"""
import os
import re
import sys
import pkg_resources
from setuptools import setup, Command
pkg_resources.require('setuptools>=39.2') # setuptools >=38.3.0     # version with most `setup.cfg` bugfixes
ROOT = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'numdifftools'

def read(file_path, lines=False):
    """Returns contents of file either as a string or list of lines."""
    with open(file_path, 'r') as fp:
        if lines:
            return fp.readlines()
        return fp.read()

def find_version(file_path):
    """Returns version given in the __version__ variable of a module file"""
    version_file = read(file_path)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)  # @UndefinedVariable
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

class Doctest(Command):
    description = 'Run doctests with Sphinx'
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        from sphinx.application import Sphinx
        sph = Sphinx('./docs',  # source directory
                     './docs',  # directory containing conf.py
                     './docs/_build',  # output directory
                     './docs/_build/doctrees',  # doctree directory
                     'doctest')  # finally, specify the doctest builder
        sph.build()

def setup_package():
    version = find_version(os.path.join(ROOT, 'src', PACKAGE_NAME, "__init__.py"))
    print("Version: {}".format(version))

    sphinx_requires = ['sphinx>=1.3.1']
    needs_sphinx = {'build_sphinx'}.intersection(sys.argv)
    sphinx = ['numpydoc',
              'imgmath',
              'sphinx_rtd_theme>=0.1.7'] + sphinx_requires if needs_sphinx else []
    setup(
        name=PACKAGE_NAME,
        version=version,
        install_requires=read(os.path.join(ROOT, 'requirements.txt'), lines=True),
        extras_require={'build_sphinx': sphinx_requires},
        setup_requires=["pytest-runner"] + sphinx,
        tests_require=['pytest',
                       'pytest-cov',
                       'pytest-pep8',
                       'hypothesis',
                       'matplotlib',
                       'line_profiler'
                       ],
        cmdclass={'doctest': Doctest},
    )

if __name__ == "__main__":
    # sys.argv.append('docs')
    # sys.argv.append('bdist_wininst')
    setup_package()


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// RobotBuilder Version: 0.0.2
002//
003// This file was generated by RobotBuilder. It contains sections of
004// code that are automatically generated and assigned by robotbuilder.
005// These sections will be updated in the future when you export to
006// Java from RobotBuilder. Do not put any code or make any change in
007// the blocks indicating autogenerated code or it will be lost on an
008// update. Deleting the comments indicating the section will prevent
009// it from being updated in th future.
010
011
012package org.usfirst.frc330.Beachbot2013Java.commands;
013import edu.wpi.first.wpilibj.command.AutoSpreadsheetCommandGroup;
014import edu.wpi.first.wpilibj.command.CommandGroup;
015
016/**
017 * Turns off the pickup motor and shooter motor and moves arm to the pickup position
018 */
019public class PickupOffCommandGroup extends AutoSpreadsheetCommandGroup {
020
021    public  PickupOffCommandGroup() {
022        // Add Commands here:
023        // e.g. addSequential(new Command1());
024        //      addSequential(new Command2());
025        // these will run in order.
026
027        // To run multiple commands at the same time,
028        // use addParallel()
029        // e.g. addParallel(new Command1());
030        //      addSequential(new Command2());
031        // Command1 and Command2 will run in parallel.
032
033        // A command group will require all of the subsystems that each member
034        // would require.
035        // e.g. if Command1 requires chassis, and Command2 requires arm,
036        // a CommandGroup containing them would require both the chassis and the
037        // arm.
038        addSequential(new StopShootLow());
039        addSequential(new PickupFrisbeesOff());
040        addSequential(new ArmLowPickup());
041    }
042
043    public AutoSpreadsheetCommandGroup copy() {
044        return new PickupOffCommandGroup();
045    }
046}


text:
cc.Class({
    extends: cc.Component,

    properties: {
        playLabel: {
            default: null,
            type: cc.Label
        },

        pauseLabel: {
            default: null,
            type: cc.Label
        },

        stateLabel: {
            default: null,
            type: cc.Label
        },

        animation: {
            default: null,
            type: cc.Animation
        }
    },

    onEnable: function () {
        var animation = this.animation;

        animation.on('play',      this.onPlay,        this);
        animation.on('stop',      this.onStop,        this);
        animation.on('lastframe', this.onLastFrame,   this);
        animation.on('finished',  this.onFinished,    this);
        animation.on('pause',     this.onPause,       this);
        animation.on('resume',    this.onResume,      this);
    },

    onDisable: function () {
        var animation = this.animation;

        animation.off('play',      this.onPlay,        this);
        animation.off('stop',      this.onStop,        this);
        animation.off('lastframe', this.onLastFrame,   this);
        animation.off('finished',  this.onFinished,    this);
        animation.off('pause',     this.onPause,       this);
        animation.off('resume',    this.onResume,      this);
    },

    onPlayButtonClicked: function () {
        if (this.playLabel.string === 'play') {
            this.playLabel.string = 'stop';
            this.animation.play('linear');
        }
        else {
            this.playLabel.string = 'play';
            this.animation.stop('linear');
        }
    },

    onPauseButtonClicked: function () {
        if (this.pauseLabel.string === 'pause') {
            this.pauseLabel.string = 'resume';
            this.animation.pause('linear');
        }
        else {
            this.pauseLabel.string = 'pause';
            this.animation.resume('linear');
        }
    },

    onPlay: function () {
        cc.log('onPlay');
        this.stateLabel.string = 'onPlay';
    },

    onStop: function () {
        cc.log('onStop');
        this.stateLabel.string = 'onStop';
        this.playLabel.string = 'play';
    },

    onLastFrame: function () {
        cc.log('onLastFrame');
        this.stateLabel.string = 'onLastFrame';
    },

    onFinished: function () {
        cc.log('onFinished');
        this.stateLabel.string = 'onFinished';
    },

    onPause: function () {
        cc.log('onPause');
        this.stateLabel.string = 'onPause';
    },

    onResume: function () {
        cc.log('onResume');
        this.stateLabel.string = 'onResume';
    }
});


text:
exports.loginRequired = function(req, res, next) {
	if (req.session.user) {
		next();
	} else {
		res.redirect('/login');
	}
};

// GET /login -- Formulario de login
exports.new = function(req, res) {
	var errors = req.session.errors || {};
	req.session.errors = {};

	res.render('sessions/new', {errors: errors});
};

// POST /login -- Crear la session
exports.create = function(req, res) {
	var login = req.body.login;
	var password = req.body.password;

	var userController = require('./user_controller');
	userController.autenticar(login, password, function(error, user) {
		if (error) {
			req.session.errors = [{"message": 'Se ha producido un error: ' + error}];
			res.redirect("/login");
			return;
		};

		// Crear req.session.user y guardar campos id y username
		// La sesión se define por la existencia de: req.session.user
		req.session.user = {id: user.id, username: user.username};

		res.redirect(req.session.redir.toString()); // redirección a path anterior a login
	});
};

// DELETE /logout -- Destruir sesión
exports.destroy = function(req, res) {
	delete req.session.user;
	res.redirect(req.session.redir.toString()); // redirección a path anterior a logout
};