text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;

import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.searchchain.Execution;
import org.apache.http.client.utils.URIBuilder;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

/**
 * Tests YQL expressions where a list of terms are supplied by indirection
 *
 * @author bratseth
 */
public class TermListTestCase {

    @Test
    void testTermListInWeightedSet() {
        URIBuilder builder = searchUri();
        builder.setParameter("myTerms", "{'1':1, '2':1, 3:1}");
        builder.setParameter("yql", "select * from sources * where weightedSet(user_id, @myTerms)");
        Query query = searchAndAssertNoErrors(builder);
        assertEquals("select * from sources * where weightedSet(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
                query.yqlRepresentation());
    }

    @Test
    void testTermListInWand() {
        URIBuilder builder = searchUri();
        builder.setParameter("myTerms", "{'1':1, 2:1, '3':1}");
        builder.setParameter("yql", "select * from sources * where wand(user_id, @myTerms)");
        Query query = searchAndAssertNoErrors(builder);
        assertEquals("select * from sources * where wand(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
                query.yqlRepresentation());
    }

    @Test
    void testTermListInDotProduct() {
        URIBuilder builder = searchUri();
        builder.setParameter("myTerms", "{'1':1, '2':1, '3':1}");
        builder.setParameter("yql", "select * from sources * where dotProduct(user_id, @myTerms)");
        Query query = searchAndAssertNoErrors(builder);
        assertEquals("select * from sources * where dotProduct(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
                query.yqlRepresentation());
    }

    private Query searchAndAssertNoErrors(URIBuilder builder) {
        Query query = new Query(builder.toString());
        var searchChain = new Chain<>(new MinimalQueryInserter());
        var context = Execution.Context.createContextStub();
        var execution = new Execution(searchChain, context);
        Result r = execution.search(query);
        var exception = exceptionOf(r);
        assertNull(r.hits().getError(),
                   exception == null ? "No error":
                   exception.getMessage() + "\n" + Arrays.toString(exception.getStackTrace()));
        return query;
    }

    private Throwable exceptionOf(Result r) {
        if (r.hits().getError() == null) return null;
        if (r.hits().getError().getCause() == null) return null;
        return r.hits().getError().getCause();
    }

    private URIBuilder searchUri() {
        URIBuilder builder = new URIBuilder();
        builder.setPath("search/");
        return builder;
    }

}


text:
'use strick'
let path = require('path')
let webpack = require('webpack')
let ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
  entry: {
    // 入口文件
    app: './src/client/app.js'
  },
  output: {
    // 输出目录
    path: path.resolve(__dirname, '../dist/static'),
    publicPath: '/static/',
    filename: '[name].min.js',
    chunkFilename: "[name].min.js"
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'react-hot!babel?presets[]=react'
    }, {
      test: /\.css$/,
      loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
    }, {
      test: /\.scss$/,
      loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader')
    }, {
      test: /\.json$/,
      loader: 'json'
    }, {
      test: /\.(png|jpg|gif|svg|ttf)$/,
      loader: 'url',
      query: {
        limit: 10000
      }
    }]
  },
  plugins: [
    new ExtractTextPlugin("[name].[contenthash].css", {
      allChunks: true,
      disable: false
    })
  ]
}

redpajama_set_name: RedPajamaGithub


text:
package edu.psu.cse.siis.coal;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import soot.MethodOrMethodContext;
import soot.Scene;
import soot.SootMethod;
import soot.Unit;
import soot.Value;
import soot.jimple.toolkits.callgraph.ReachableMethods;
import edu.psu.cse.siis.coal.values.BasePropagationValue;

/**
 * A {@link PropagationSceneTransformerPrinter} that prints to a file.
 */
public class PropagationSceneTransformerFilePrinter implements PropagationSceneTransformerPrinter {
  private final String filePath;
  private final SymbolFilter filter;

  /**
   * Constructor for the printer.
   *
   * @param filePath The path to the output file.
   * @param filter A filter to filter out unwanted symbols (e.g., variables or fields whose value
   *          should not be printed).
   */
  public PropagationSceneTransformerFilePrinter(String filePath, SymbolFilter filter) {
    this.filePath = filePath;
    this.filter = filter;
  }

  @Override
  public void print(PropagationSolver solver) {
    try {
      BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
      String newLine = System.getProperty("line.separator");
      List<MethodOrMethodContext> eps =
          new ArrayList<MethodOrMethodContext>(Scene.v().getEntryPoints());
      ReachableMethods reachableMethods =
          new ReachableMethods(Scene.v().getCallGraph(), eps.iterator(), null);
      reachableMethods.update();
      for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) {
        SootMethod ep = iter.next().method();
        if (!ep.isConcrete() || !ep.hasActiveBody()
        // || ep.getName().contains("dummy")
        /* || Model.v().isExcludedClass(ep.getDeclaringClass().getName()) */) {
          continue;
        }
        writer.write(ep.getActiveBody() + newLine);

        writer.write("----------------------------------------------" + newLine);
        writer.write("At end of: " + ep.getSignature() + newLine);
        writer.write("Variables:" + newLine);
        writer.write("----------------------------------------------" + newLine);

        for (Unit ret : ep.getActiveBody().getUnits()) {

          for (Map.Entry<Value, BasePropagationValue> l : solver.resultsAt(ret).entrySet()) {
            Value symbol = l.getKey();
            if (filter.filterOut(symbol)) {
              continue;
            }
            writer.write(symbol + " contains value " + l.getValue() + newLine);
          }

          writer.write("**" + ret + newLine);
        }
      }
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


text:
package alien4cloud.paas.cloudify3.shared;

import alien4cloud.ui.form.annotation.FormLabel;
import alien4cloud.ui.form.annotation.FormProperties;
import alien4cloud.ui.form.annotation.FormPropertyDefinition;
import lombok.Getter;
import lombok.Setter;

/**
 * Manage plugin configuration.
 */
@Getter
@Setter
@FormProperties({ "delayBetweenLogPolling" })
public class PluginConfiguration {
    @FormLabel("polling delay")
    @FormPropertyDefinition(description = "Delay between two events polling in seconds.", defaultValue = "5", type = "integer")
    private Integer delayBetweenLogPolling = 5;
}


text:
/*global describe, it, expect, glitch*/
describe(
	'glitch-canvas browser tests',
	function ()
	{
		// prepare two canvas elements
		var canvas_one = document.getElementById( 'canvas-one' );
		var canvas_two = document.getElementById( 'canvas-two' );
		var ctx_one = canvas_one.getContext( '2d' );
		var ctx_two = canvas_two.getContext( '2d' );
		var canvas_width = canvas_one.clientWidth;
		var canvas_height = canvas_one.clientHeight;

		// draw white background
		ctx_one.fillStyle = '#ffffff';
		ctx_one.fillRect( 0, 0, canvas_width, canvas_height );

		//draw some stuff so we have something to glitch
		ctx_one.beginPath();
		ctx_one.moveTo( 23, 190 );
		ctx_one.lineTo( 230, 80 );
		ctx_one.lineTo( 150, 30 );
		ctx_one.closePath();
		ctx_one.fillStyle = '#77bbaa';
		ctx_one.fill();

		ctx_one.fillStyle = '#ff0000';
		ctx_one.beginPath();
		ctx_one.arc( 100, 100, 50, 0, Math.PI * 2, true );
		ctx_one.closePath();
		ctx_one.fill();

		ctx_one.fillStyle = '#0066ff';
		ctx_one.fillRect( 120, 80, 120, 30 );

		function callback( image_data )
		{
			ctx_two.clearRect( 0, 0, canvas_width, canvas_height );
			ctx_two.putImageData( image_data, 0, 0 );
		}

		var image_data = ctx_one.getImageData( 0, 0, canvas_width, canvas_height );
		var parameters = { amount: 10, seed: 45, iterations: 30, quality: 30 };

		function glitchWithoutImageData() { glitch( undefined, parameters, callback ); }
		function glitchWithEmptyImageData() { glitch( { width: 0, height: 0, data: [ ] }, parameters, callback ); }
		function glitchWithoutParameters() { glitch( image_data, undefined, callback ); }
		function glitchWithoutCallback() { glitch( image_data, parameters ); }
		function glitchWithEmptyParameters() { glitch( image_data, { }, callback ); }
		function glitchCorrectly() { glitch( image_data, parameters, callback ); }

		// http://stackoverflow.com/a/15208067/229189
		function checkAsync( done, fn )
		{
			try
			{
				fn();
				done();
			}

			catch ( e )
			{
				done( e );
			}
		}

		it(
			'adds a global glitch function named "glitch"',
			function ()
			{
				expect( typeof glitch ).to.equal( 'function' );
			}
		);

		it(
			"throws an error if no parameters are given",
			function ()
			{
				expect( glitch ).to.throw( Error );
			}
		);

		it(
			"throws an error if the image_data argument is not undefined",
			function ()
			{
				expect( glitchWithoutImageData ).to.throw( Error );
			}
		);

		it(
			"throws an error if the image_data argument is empty",
			function ()
			{
				expect( glitchWithEmptyImageData ).to.throw( Error );
			}
		);

		it(
			"throws an error if the parameters argument is undefined",
			function ()
			{
				expect( glitchWithoutParameters ).to.throw( Error );
			}
		);

		it(
			"doesn't throw an error if the parameters argument is empty",
			function ()
			{
				expect( glitchWithEmptyParameters ).not.to.throw( Error );
			}
		);

		it(
			"throws an error if the callback argument is not undefined",
			function ()
			{
				expect( glitchWithoutCallback ).to.throw( Error );
			}
		);

		it(
			"doesn't throw an error with correct arguments",
			function ()
			{
				expect( glitchCorrectly ).not.to.throw( Error );
			}
		);

		it(
			"does pass a valid imageData object to callback function",
			function ( done )
			{
				glitch(
					image_data,
					parameters,
					function( glitched_image_data )
					{
						checkAsync(
							done,
							function()
							{
								expect( typeof glitched_image_data ).to.equal( 'object' );
								expect( typeof glitched_image_data.width ).to.equal( 'number' );
								expect( glitched_image_data.width ).to.equal( canvas_width );
								expect( typeof glitched_image_data.height ).to.equal( 'number' );
								expect( glitched_image_data.height ).to.equal( canvas_height );
								expect( typeof glitched_image_data.data ).to.equal( 'object' );
								expect( typeof glitched_image_data.data.length ).to.equal( 'number' );
								expect( glitched_image_data.data.length ).to.equal( image_data.data.length );
							}
						);
					}
				);
			}
		);
	}
);


text:
export function loadFileAjaxSync(filePath, mimeType, body, authorization) {
  const xmlhttp = new XMLHttpRequest()
  if (body) {
    xmlhttp.open("POST", filePath, false)
    xmlhttp.setRequestHeader("Content-Type", mimeType)
    if (authorization) {
      xmlhttp.setRequestHeader("Credentials", "same-origin")
      xmlhttp.setRequestHeader("Authorization", `Bearer ${authorization}`)
    }
    xmlhttp.send(body)
  } else {
    xmlhttp.open("GET", filePath, false)
    if (mimeType !== null) {
      if (xmlhttp.overrideMimeType) {
        xmlhttp.overrideMimeType(mimeType)
      }
    }
    xmlhttp.send()
  }
  if (xmlhttp.status === 200) {
    return xmlhttp.responseText
  } else {
    throw new Error("unable to load " + filePath)
  }
}


text:
package edu.nanoracket.npr.ui.activity;

import android.support.v4.app.Fragment;

import edu.nanoracket.npr.music.MusicListFragment;
import edu.nanoracket.npr.ui.fragment.PodcastListFragment;

public class PodcastListActivity extends NprFragmentActivity {

	@Override
	protected Fragment createFragment() {
		 String mProgramSrc = getIntent()
		         .getStringExtra(PodcastListFragment.PODCAST_SRC);
         String programName = getIntent()
                 .getStringExtra(PodcastListFragment.PODCAST_PROGRAM);
         int imagePosition = getIntent()
                 .getIntExtra(PodcastListFragment.PODCAST_IMAGE, -1);
		 return MusicListFragment.newInstance(mProgramSrc, programName, imagePosition);
	}
}


text:
@interface OHPullToRefreshWidget() {

}

@property (assign, nonatomic) BOOL inRefresh;
@property (assign, nonatomic) CGFloat pullToRefreshOffsetRatio;

@end

@implementation OHPullToRefreshWidget

- (id)init
{
    self = [super init];
    if(self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit
{
    self.pullToRefreshOffsetRatio = 0.12f;
}

- (void)didScroll:(UIScrollView*)scrollView
{
    if(self.inRefresh) {
        return;
    }
//    NSLog(@"Scroll view %f %f", scrollView.contentInset.top, scrollView.contentOffset.y);

    if(scrollView.contentOffset.y < scrollView.contentInset.top) {
        CGFloat offsetNeeded = CGRectGetHeight(scrollView.frame) * self.pullToRefreshOffsetRatio;
        CGFloat offsetTraveled = -(scrollView.contentInset.top + scrollView.contentOffset.y);
        CGFloat progress = offsetTraveled / offsetNeeded;

        [self.delegate willStartPullToRefresh:MIN(1, progress) starting:NO];
//        NSLog(@"offset needed %f offset traveled %f progress %f", offsetNeeded, offsetTraveled, progress);
    } else {
        [self.delegate willStartPullToRefresh:0 starting:NO];
    }
}

- (void)didEndDragging:(UIScrollView *)scrollView decelerating:(BOOL)shouldDecelerating
{
    if(self.inRefresh) {
        return;
    }
//    NSLog(@"Scroll view end dragging %f %f", scrollView.contentInset.top, scrollView.contentOffset.y);
    if(scrollView.contentOffset.y < scrollView.contentInset.top) {
        CGFloat offsetNeeded = CGRectGetHeight(scrollView.frame) * self.pullToRefreshOffsetRatio;
        CGFloat offsetTraveled = -(scrollView.contentInset.top + scrollView.contentOffset.y);
        CGFloat progress = offsetTraveled / offsetNeeded;
        if(progress > 1) {
            [self.delegate willStartPullToRefresh:1.0f starting:YES];
            self.inRefresh = YES;
        }
//        NSLog(@"offset needed %f offset traveled %f progress %f", offsetNeeded, offsetTraveled, progress);
    }

    if(!shouldDecelerating && self.inRefresh) {
        [self.delegate shouldStartRefresh];
    }
}

- (void)didEndDecelerating
{
    if(self.inRefresh) {
        [self.delegate shouldStartRefresh];
    }
}

- (void)endRefreshing
{
    self.inRefresh = NO;
}

@end


text:
package com.socks.jiandan.net.parser;

import android.support.annotation.Nullable;

import com.socks.jiandan.model.Video;
import com.socks.okhttp.plus.parser.OkBaseParser;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import okhttp3.Response;

/**
 * Created by zhaokaiqiang on 15/11/22.
 */
public class VideoParser extends OkBaseParser<ArrayList<Video>> {

    @Nullable
    public ArrayList<Video> parse(Response response) {

        try {
            String jsonStr = response.body().string();
            JSONObject jsonObject = new JSONObject(jsonStr);

            if ("ok".equals(jsonObject.optString("status"))) {

                JSONArray commentsArray = jsonObject.optJSONArray("comments");
                ArrayList<Video> videos = new ArrayList<>();

                for (int i = 0; i < commentsArray.length(); i++) {

                    JSONObject commentObject = commentsArray.getJSONObject(i);
                    JSONObject videoObject = commentObject.optJSONArray("videos").optJSONObject(0);

                    if (videoObject != null) {
                        Video video = new Video();
                        video.setTitle(videoObject.optString("title"));
                        String videoSource = videoObject.optString("video_source");
                        video.setComment_ID(commentObject.optString("comment_ID"));
                        video.setVote_positive(commentObject.optString("vote_positive"));
                        video.setVote_negative(commentObject.optString("vote_negative"));
                        video.setVideo_source(videoSource);

                        if (videoSource.equals("youku")) {
                            video.setUrl(videoObject.optString("link"));
                            video.setDesc(videoObject.optString("description"));
                            video.setImgUrl(videoObject.optString("thumbnail"));
                            video.setImgUrl4Big(videoObject.optString("thumbnail_v2"));
                        } else if (videoSource.equals("56")) {
                            video.setUrl(videoObject.optString("url"));
                            video.setDesc(videoObject.optString("desc"));
                            video.setImgUrl4Big(videoObject.optString("img"));
                            video.setImgUrl(videoObject.optString("mimg"));
                        } else if (videoSource.equals("tudou")) {
                            video.setUrl(videoObject.optString("playUrl"));
                            video.setImgUrl(videoObject.optString("picUrl"));
                            video.setImgUrl4Big(videoObject.optString("picUrl"));
                            video.setDesc(videoObject.optString("description"));
                        }

                        videos.add(video);
                    }
                }

                return videos;
            } else {
                return new ArrayList<>();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}


text:
.class abstract Landroid/support/v4/app/q;
.super Landroid/support/v4/app/p;

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Landroid/support/v4/app/p;-><init>()V

    return-void
.end method

# virtual methods
.method b_()V
    .locals 0

    invoke-super {p0}, Landroid/support/v4/app/p;->onBackPressed()V

    return-void
.end method


text:
mongo-c-driver-build
====================

mongo-c-driver build project


text:
@class ARObject;

@protocol ARObjectDelegate;

@interface ARObject : UIViewController <UIGestureRecognizerDelegate>
{

    // ARObject main components
    NSString *arTitle;

    int nid;
    double lat;
    double lon;
    NSNumber *distance;

    // Overlay View Objects
    IBOutlet UILabel *titleL;
    IBOutlet UILabel *distanceL;
}

@property (nonatomic, strong) NSString *arTitle;
@property (nonatomic, strong) NSNumber *distance;
@property (strong, nonatomic) MMRDetailViewController *detailViewController;

- (id)initWithId:(int)newNid
           title:(NSString*)newTitle
     coordinates:(CLLocationCoordinate2D)newCoordinates
andCurrentLocation:(CLLocationCoordinate2D)currLoc;

- (NSDictionary*)getARObjectData;

@property (weak, nonatomic) id <ARObjectDelegate> delegate;

@end

@protocol ARObjectDelegate <NSObject>
- (void) arObjectControl:(ARObject *)arObjectView didTappedForValue:(NSMutableArray *)memoObject;
@end


text:
/**
 * Listens for the app launching then creates the window
 *
 * @see http://developer.chrome.com/apps/app.runtime.html
 * @see http://developer.chrome.com/apps/app.window.html
 */
chrome.app.runtime.onLaunched.addListener(function() {
  // Center window on screen.
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  var width = screenWidth - 20;
  var height = screenHeight - 20;

  chrome.app.window.create('index.html', {
    id: "welcomewindow",
    outerBounds: {
      width: width,
      height: height,
      left: Math.round((screenWidth-width)/2),
      top: Math.round((screenHeight-height)/2)
    }
  });
});


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>new (SpecFlowReport)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

# File lib/albacore/specflowreport.rb, line 11
  def initialize(command=nil, report=nil)
    @options=[]
    @projects =[]
    super()
    update_attributes specflowreport.to_hash
        @command = command unless command.nil?
        @report = report unless command.nil?
  end


text:
{% extends "../internal/layout.html" %} {% block content_header%}

Users
 {% endblock %} {% block breadcrumb%}

 Dashboard

users

{% endblock %} {% block menu %} {% include "../internal/layout/menu.html" with page="users" %} {% endblock %} {% block content%} {% verbatim %}

Users

            <form method="get" action="/users/">

                    <input type="text" name="q" value="{{ query }}" class="form-control pull-right" placeholder="Search">

                        <button type="submit" class="btn btn-default"></button>

            </form>

                    #
                    user name
                    login
                    email
                    created at
                    updated at
                    {% if CurrentUser.IsSuperuser %}
                    -
                    {% endif %}

                {% for user in users %}

                    {{ user.ID }}
                    {{ user.Name }} {% if user.IsSuperuser %}(superuser){% endif %}
                    {{ user.Login }}
                    {{ user.Email }}
                    {{ user.CreatedAt | time:"Mon, 02 Jan 2006 15:04:05 -0700" }}
                    {{ user.UpdatedAt | time:"Mon, 02 Jan 2006 15:04:05 -0700" }}
                    {% if CurrentUser.IsSuperuser %}

                        edit

                        {% if user.ID != CurrentUser.ID %}
                        reset password
                        {% endif %}
                        {% if !user.IsSuperuser %}
                        delete
                        {% endif %}

                    {% endif %}

                {% endfor %}

        {% if CurrentUser.IsSuperuser %}
        <button type="submit"
         data-toggle="modal"
         data-target="#addUserForm"
         class="btn btn-primary">Add user</button>
        {% endif %} {% endverbatim %} {% include "../internal/pagination.html" %}

    {% verbatim %} {% if CurrentUser.IsSuperuser %}

            <form method="post" action="/users/add/">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add user

                        user name:
                        <input type="text" name="name" class="form-control" data-title="Enter user name" required>

                        email:
                        <input type="email" name="email" class="form-control" data-title="Enter email" required>

                        login:
                        <input type="text" name="login" class="form-control" data-title="Enter login" required>

                        password:
                        <input type="password" name="password" class="form-control" id="password" data-title="Enter password" required>

                        <input type="checkbox" name="is_superuser"> superuser

                    <button type="button" class="btn btn-default" data-dismiss="modal">close</button>
                    <button type="submit" class="btn btn-primary">submit</button>

            </form>

            <form method="post" action="">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Edit user

                        user name:
                        <input type="text" name="name" id="user_name" class="form-control" data-title="Enter user name" required>

                        email:
                        <input type="email" name="email" id="user_email" class="form-control" data-title="Enter email" required>

                        <input type="checkbox" id="is_superuser" name="is_superuser"> superuser

                    <button type="button" class="btn btn-default" data-dismiss="modal">close</button>
                    <button type="submit" class="btn btn-primary">submit</button>

            </form>

            <form method="post" action="">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Reset password

                        new password:
                        <input type="password" name="new_password" class="form-control" data-title="Enter password" required>

                        confirm password:
                        <input type="password" name="confirm_password" class="form-control" data-title="Enter password" required>

                    <button type="button" class="btn btn-default" data-dismiss="modal">close</button>
                    <button type="submit" class="btn btn-primary">submit</button>

            </form>

    {% endif %} {% endverbatim %}

{% endblock %}


text: A Graphical editor to create Relational Database Models


text:
package org.codehaus.groovy.runtime;

import groovy.lang.MissingMethodException;
import org.codehaus.groovy.reflection.CachedMethod;

/**
 * Provides as alternative to reflection using bytecode generation.
 *
 * @author James Strachan
 */
public class Reflector {

    public Object invoke(CachedMethod method, Object object, Object[] arguments) {
        return noSuchMethod(method, object, arguments);
    }

    protected Object noSuchMethod(CachedMethod method, Object object, Object[] arguments) {
        throw new MissingMethodException(method.getName(), method.getDeclaringClass().getTheClass(), arguments, false);
    }
}


text:
import numpy as np
from numba import cuda
from numba.cuda.testing import unittest

class TestArrayAttr(unittest.TestCase):
    def test_contigous_2d(self):
        ary = np.arange(10)
        cary = ary.reshape(2, 5)
        fary = np.asfortranarray(cary)

        dcary = cuda.to_device(cary)
        dfary = cuda.to_device(fary)
        self.assertTrue(dcary.is_c_contiguous())
        self.assertTrue(not dfary.is_c_contiguous())
        self.assertTrue(not dcary.is_f_contiguous())
        self.assertTrue(dfary.is_f_contiguous())

    def test_contigous_3d(self):
        ary = np.arange(20)
        cary = ary.reshape(2, 5, 2)
        fary = np.asfortranarray(cary)

        dcary = cuda.to_device(cary)
        dfary = cuda.to_device(fary)
        self.assertTrue(dcary.is_c_contiguous())
        self.assertTrue(not dfary.is_c_contiguous())
        self.assertTrue(not dcary.is_f_contiguous())
        self.assertTrue(dfary.is_f_contiguous())

    def test_contigous_4d(self):
        ary = np.arange(60)
        cary = ary.reshape(2, 5, 2, 3)
        fary = np.asfortranarray(cary)

        dcary = cuda.to_device(cary)
        dfary = cuda.to_device(fary)
        self.assertTrue(dcary.is_c_contiguous())
        self.assertTrue(not dfary.is_c_contiguous())
        self.assertTrue(not dcary.is_f_contiguous())
        self.assertTrue(dfary.is_f_contiguous())

    def test_ravel_c(self):
        ary = np.arange(60)
        reshaped = ary.reshape(2, 5, 2, 3)
        expect = reshaped.ravel(order='C')
        dary = cuda.to_device(reshaped)
        dflat = dary.ravel()
        flat = dflat.copy_to_host()
        self.assertTrue(flat.ndim == 1)
        self.assertTrue(np.all(expect == flat))

    def test_ravel_f(self):
        ary = np.arange(60)
        reshaped = np.asfortranarray(ary.reshape(2, 5, 2, 3))
        expect = reshaped.ravel(order='F')
        dary = cuda.to_device(reshaped)
        dflat = dary.ravel(order='F')
        flat = dflat.copy_to_host()
        self.assertTrue(flat.ndim == 1)
        self.assertTrue(np.all(expect == flat))

    def test_reshape_c(self):
        ary = np.arange(10)
        expect = ary.reshape(2, 5)
        dary = cuda.to_device(ary)
        dary_reshaped = dary.reshape(2, 5)
        got = dary_reshaped.copy_to_host()
        self.assertTrue(np.all(expect == got))

    def test_reshape_f(self):
        ary = np.arange(10)
        expect = ary.reshape(2, 5, order='F')
        dary = cuda.to_device(ary)
        dary_reshaped = dary.reshape(2, 5, order='F')
        got = dary_reshaped.copy_to_host()
        self.assertTrue(np.all(expect == got))

if __name__ == '__main__':
    unittest.main()


text:
import proto  # type: ignore

from google.cloud.aiplatform_v1beta1.types import annotation
from google.cloud.aiplatform_v1beta1.types import data_item
from google.cloud.aiplatform_v1beta1.types import dataset as gca_dataset
from google.cloud.aiplatform_v1beta1.types import operation
from google.protobuf import field_mask_pb2  # type: ignore

__protobuf__ = proto.module(
    package="google.cloud.aiplatform.v1beta1",
    manifest={
        "CreateDatasetRequest",
        "CreateDatasetOperationMetadata",
        "GetDatasetRequest",
        "UpdateDatasetRequest",
        "ListDatasetsRequest",
        "ListDatasetsResponse",
        "DeleteDatasetRequest",
        "ImportDataRequest",
        "ImportDataResponse",
        "ImportDataOperationMetadata",
        "ExportDataRequest",
        "ExportDataResponse",
        "ExportDataOperationMetadata",
        "ListDataItemsRequest",
        "ListDataItemsResponse",
        "GetAnnotationSpecRequest",
        "ListAnnotationsRequest",
        "ListAnnotationsResponse",
    },
)

class CreateDatasetRequest(proto.Message):
    r"""Request message for
    [DatasetService.CreateDataset][google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset].

    Attributes:
        parent (str):
            Required. The resource name of the Location to create the
            Dataset in. Format:
            ``projects/{project}/locations/{location}``
        dataset (google.cloud.aiplatform_v1beta1.types.Dataset):
            Required. The Dataset to create.
    """

    parent = proto.Field(proto.STRING, number=1,)
    dataset = proto.Field(proto.MESSAGE, number=2, message=gca_dataset.Dataset,)

class CreateDatasetOperationMetadata(proto.Message):
    r"""Runtime operation information for
    [DatasetService.CreateDataset][google.cloud.aiplatform.v1beta1.DatasetService.CreateDataset].

    Attributes:
        generic_metadata (google.cloud.aiplatform_v1beta1.types.GenericOperationMetadata):
            The operation generic information.
    """

    generic_metadata = proto.Field(
        proto.MESSAGE, number=1, message=operation.GenericOperationMetadata,
    )

class GetDatasetRequest(proto.Message):
    r"""Request message for
    [DatasetService.GetDataset][google.cloud.aiplatform.v1beta1.DatasetService.GetDataset].

    Attributes:
        name (str):
            Required. The name of the Dataset resource.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
    """

    name = proto.Field(proto.STRING, number=1,)
    read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,)

class UpdateDatasetRequest(proto.Message):
    r"""Request message for
    [DatasetService.UpdateDataset][google.cloud.aiplatform.v1beta1.DatasetService.UpdateDataset].

    Attributes:
        dataset (google.cloud.aiplatform_v1beta1.types.Dataset):
            Required. The Dataset which replaces the
            resource on the server.
        update_mask (google.protobuf.field_mask_pb2.FieldMask):
            Required. The update mask applies to the resource. For the
            ``FieldMask`` definition, see
            [google.protobuf.FieldMask][google.protobuf.FieldMask].
            Updatable fields:

            -  ``display_name``
            -  ``description``
            -  ``labels``
    """

    dataset = proto.Field(proto.MESSAGE, number=1, message=gca_dataset.Dataset,)
    update_mask = proto.Field(
        proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,
    )

class ListDatasetsRequest(proto.Message):
    r"""Request message for
    [DatasetService.ListDatasets][google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets].

    Attributes:
        parent (str):
            Required. The name of the Dataset's parent resource. Format:
            ``projects/{project}/locations/{location}``
        filter (str):
            An expression for filtering the results of the request. For
            field names both snake_case and camelCase are supported.

            -  ``display_name``: supports = and !=
            -  ``metadata_schema_uri``: supports = and !=
            -  ``labels`` supports general map functions that is:

               -  ``labels.key=value`` - key:value equality
               -  \`labels.key:\* or labels:key - key existence
               -  A key including a space must be quoted.
                  ``labels."a key"``.

            Some examples:

            -  ``displayName="myDisplayName"``
            -  ``labels.myKey="myValue"``
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
        order_by (str):
            A comma-separated list of fields to order by, sorted in
            ascending order. Use "desc" after a field name for
            descending. Supported fields:

            -  ``display_name``
            -  ``create_time``
            -  ``update_time``
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)
    order_by = proto.Field(proto.STRING, number=6,)

class ListDatasetsResponse(proto.Message):
    r"""Response message for
    [DatasetService.ListDatasets][google.cloud.aiplatform.v1beta1.DatasetService.ListDatasets].

    Attributes:
        datasets (Sequence[google.cloud.aiplatform_v1beta1.types.Dataset]):
            A list of Datasets that matches the specified
            filter in the request.
        next_page_token (str):
            The standard List next-page token.
    """

    @property
    def raw_page(self):
        return self

    datasets = proto.RepeatedField(
        proto.MESSAGE, number=1, message=gca_dataset.Dataset,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class DeleteDatasetRequest(proto.Message):
    r"""Request message for
    [DatasetService.DeleteDataset][google.cloud.aiplatform.v1beta1.DatasetService.DeleteDataset].

    Attributes:
        name (str):
            Required. The resource name of the Dataset to delete.
            Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}``
    """

    name = proto.Field(proto.STRING, number=1,)

class ImportDataRequest(proto.Message):
    r"""Request message for
    [DatasetService.ImportData][google.cloud.aiplatform.v1beta1.DatasetService.ImportData].

    Attributes:
        name (str):
            Required. The name of the Dataset resource. Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}``
        import_configs (Sequence[google.cloud.aiplatform_v1beta1.types.ImportDataConfig]):
            Required. The desired input locations. The
            contents of all input locations will be imported
            in one batch.
    """

    name = proto.Field(proto.STRING, number=1,)
    import_configs = proto.RepeatedField(
        proto.MESSAGE, number=2, message=gca_dataset.ImportDataConfig,
    )

class ImportDataResponse(proto.Message):
    r"""Response message for
    [DatasetService.ImportData][google.cloud.aiplatform.v1beta1.DatasetService.ImportData].
        """

class ImportDataOperationMetadata(proto.Message):
    r"""Runtime operation information for
    [DatasetService.ImportData][google.cloud.aiplatform.v1beta1.DatasetService.ImportData].

    Attributes:
        generic_metadata (google.cloud.aiplatform_v1beta1.types.GenericOperationMetadata):
            The common part of the operation metadata.
    """

    generic_metadata = proto.Field(
        proto.MESSAGE, number=1, message=operation.GenericOperationMetadata,
    )

class ExportDataRequest(proto.Message):
    r"""Request message for
    [DatasetService.ExportData][google.cloud.aiplatform.v1beta1.DatasetService.ExportData].

    Attributes:
        name (str):
            Required. The name of the Dataset resource. Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}``
        export_config (google.cloud.aiplatform_v1beta1.types.ExportDataConfig):
            Required. The desired output location.
    """

    name = proto.Field(proto.STRING, number=1,)
    export_config = proto.Field(
        proto.MESSAGE, number=2, message=gca_dataset.ExportDataConfig,
    )

class ExportDataResponse(proto.Message):
    r"""Response message for
    [DatasetService.ExportData][google.cloud.aiplatform.v1beta1.DatasetService.ExportData].

    Attributes:
        exported_files (Sequence[str]):
            All of the files that are exported in this
            export operation.
    """

    exported_files = proto.RepeatedField(proto.STRING, number=1,)

class ExportDataOperationMetadata(proto.Message):
    r"""Runtime operation information for
    [DatasetService.ExportData][google.cloud.aiplatform.v1beta1.DatasetService.ExportData].

    Attributes:
        generic_metadata (google.cloud.aiplatform_v1beta1.types.GenericOperationMetadata):
            The common part of the operation metadata.
        gcs_output_directory (str):
            A Google Cloud Storage directory which path
            ends with '/'. The exported data is stored in
            the directory.
    """

    generic_metadata = proto.Field(
        proto.MESSAGE, number=1, message=operation.GenericOperationMetadata,
    )
    gcs_output_directory = proto.Field(proto.STRING, number=2,)

class ListDataItemsRequest(proto.Message):
    r"""Request message for
    [DatasetService.ListDataItems][google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems].

    Attributes:
        parent (str):
            Required. The resource name of the Dataset to list DataItems
            from. Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}``
        filter (str):
            The standard list filter.
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
        order_by (str):
            A comma-separated list of fields to order by,
            sorted in ascending order. Use "desc" after a
            field name for descending.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)
    order_by = proto.Field(proto.STRING, number=6,)

class ListDataItemsResponse(proto.Message):
    r"""Response message for
    [DatasetService.ListDataItems][google.cloud.aiplatform.v1beta1.DatasetService.ListDataItems].

    Attributes:
        data_items (Sequence[google.cloud.aiplatform_v1beta1.types.DataItem]):
            A list of DataItems that matches the
            specified filter in the request.
        next_page_token (str):
            The standard List next-page token.
    """

    @property
    def raw_page(self):
        return self

    data_items = proto.RepeatedField(
        proto.MESSAGE, number=1, message=data_item.DataItem,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class GetAnnotationSpecRequest(proto.Message):
    r"""Request message for
    [DatasetService.GetAnnotationSpec][google.cloud.aiplatform.v1beta1.DatasetService.GetAnnotationSpec].

    Attributes:
        name (str):
            Required. The name of the AnnotationSpec resource. Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}/annotationSpecs/{annotation_spec}``
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
    """

    name = proto.Field(proto.STRING, number=1,)
    read_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask,)

class ListAnnotationsRequest(proto.Message):
    r"""Request message for
    [DatasetService.ListAnnotations][google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations].

    Attributes:
        parent (str):
            Required. The resource name of the DataItem to list
            Annotations from. Format:
            ``projects/{project}/locations/{location}/datasets/{dataset}/dataItems/{data_item}``
        filter (str):
            The standard list filter.
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
        order_by (str):
            A comma-separated list of fields to order by,
            sorted in ascending order. Use "desc" after a
            field name for descending.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)
    order_by = proto.Field(proto.STRING, number=6,)

class ListAnnotationsResponse(proto.Message):
    r"""Response message for
    [DatasetService.ListAnnotations][google.cloud.aiplatform.v1beta1.DatasetService.ListAnnotations].

    Attributes:
        annotations (Sequence[google.cloud.aiplatform_v1beta1.types.Annotation]):
            A list of Annotations that matches the
            specified filter in the request.
        next_page_token (str):
            The standard List next-page token.
    """

    @property
    def raw_page(self):
        return self

    annotations = proto.RepeatedField(
        proto.MESSAGE, number=1, message=annotation.Annotation,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

__all__ = tuple(sorted(__protobuf__.manifest))


text:
class FEffect : public FObject
{
public:
	FEffect(FVector, FVector, FEffectType, float);
	void tick(float);
	FEffectType getType();
	bool isAlive();

private:
	FEffectType m_type;
	float m_time;
};

#endif


text:
package jp.mydns.sys1yagi.android.flickrjandroidsample;

public class Settings {
    public final static String API_KEY = "YOUR_FLICKR_API_KEY";
    public final static String API_SECRET = "YOUR_FLICKR_API_SECRET";
}


text:
require 'ruby-hl7'
require_relative '../ez7gen/profile_parser'
require_relative '../ez7gen/structure_parser'
require_relative '../ez7gen/service/segment_generator'
require_relative '../ez7gen/service/template_generator'
require_relative '../ez7gen/service/segment_picker'
require_relative '../ez7gen/service/utils'

class MessageFactory
  include Utils
  attr_accessor :templatePath #TODO: refactor
  # attr_accessor :std; :version; :event; :version_store; :loadFactor;

  def initialize(args)
    @attributes_hash = args
    args.each do |k,v|
      instance_variable_set("@#{k}", v) unless v.nil?
    end
    @loadFactor ||= nil
    # lookup for a template by name if client speified using a template
    @templatePath = (args[:use_template])? self.class.lookup_template_for_event(@std, @use_template):nil
    # @templatePath = self.class.lookup_template_for_event(@std, @event)

  end

  # look up for message template file for an event and standard: 2.4, ADT_A60
  def self.lookup_template_for_event(std, template)
    properties_file = File.expand_path('../resources/properties.yml', __FILE__)
    yml = YAML.load_file properties_file
    path = yml['web.install.dir']
    path = File.join(path, "config/templates/#{std}/#{template}")
    # path = File.join(path, "config/templates/#{std}/*#{event}*")
    # Dir.glob(path, File::FNM_CASEFOLD).sort.last
  end

  # main factory method
  def generate(useExVal=false)
    parsers = {}
    # get message structure from the schema file for message type and version
    parsers[PRIMARY] = ProfileParser.new(@attributes_hash)

    # check if current version is not the base version, find the base version and add use it as a base parser
    if(!is_base?(@version))# version is not standard != '2.4'
      parsers[BASE]= get_base_parser()
    end

    #useExVal can be passed from the client - future feature
    return (@templatePath)? generate_message_from_template(parsers, templatePath, useExVal) : generate_message(parsers)
  end

  # factory method to build message using schema
  def generate_message(parsers)

    # get message structure from the schema file for message type and version
    # use primary parser
    structure = parsers[PRIMARY].get_message_definition()

    # brake message structure into segments, handle groups of segments
    structParser = StructureParser.new()
    structParser.process_segments(structure)

    # select segments to build, keep required and z segments, random pick optional segments
    profile = structure.split('~')
    segment_picker = SegmentPicker.new(profile, structParser.encodedSegments, @loadFactor)
    segments = segment_picker.pick_segments_to_build()

    # configure a segment generator
    baseVersion = @std
    segmentGenerator = SegmentGenerator.new(baseVersion, @event, parsers)

    # msh segment configured by hand, due to many requirements that only apply for this segment
    hl7Msg = HL7::Message.new
    hl7Msg << segmentGenerator.init_msh
    # hl7Msg << segmentGenerator.init_msh(is_base?(@version))

    #iterate over selected segments and build the entire message
    segments.each{ |segment|
      segmentGenerator.generate(hl7Msg, segment, parsers)
     }

    return hl7Msg
  end

  # factory method to build message using MWB templates
  def generate_message_from_template(parsers, templatePath, useExVal)

    hl7Msg = HL7::Message.new

    templateGenerator = TemplateGenerator.new(templatePath, parsers)

    return templateGenerator.generate(hl7Msg, useExVal)

  end

  def is_base?(version)
    isBase = @version_store.find { |s| s[:std] == @std }[:profiles].find { |p| p[:doc] == version }[:std]
  end

  # Add parser for base version of schema
  def get_base_parser()
    # find version for base standard version - standard with 'std' attribute
    v_base = @version_store.find { |s| s[:std] == @std }[:profiles].find { |p| p[:std]!=nil }[:doc]
    v_base_hash = @attributes_hash.clone()
    v_base_hash[:version] = v_base
    ProfileParser.new(v_base_hash)
  end

  def self.to_arr(hl7Msg)
    arr = []
    hl7Msg.each{|it| arr << it.to_s.gsub("\r","\n")}
    return arr
  end

  # Identify segment as a part of a group
  def in_group?(groups, idx)
    is_in_group = !groups.select { |group| group.cover?(idx) }.empty?
    # p is_in_group
  end

  #find ranges of groups before segments collection containing groups can be flattened
  def find_Groups(segments)
    offset = 0
    # groups = segments.map.with_index { |it, idx| (it.instance_of? Array) ? ( groupLn=it.size-1;((offset+idx) .. (idx + offset=offset + groupLn)) ) : nil }.compact

    groups = segments.map.with_index { |it, idx|
      # groups of sequential segments stored as arrays of segments
      if (it.instance_of? Array)
        # calculate group range based on offset that affected flattening arrays of segments
        groupLen = it.size-1
        groupStart = offset + idx
        groupEnd = idx + offset = offset + groupLen # inline var assignment, just cause I can..
        (groupStart..groupEnd) # group range
      end
    }
    # get rid of nils
    groups.compact()
  end

end


text:
<?php

namespace Google\AdsApi\Examples\AdWords\v201609\BasicOperations;

require '../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201609\cm\AdGroup;
use Google\AdsApi\AdWords\v201609\cm\AdGroupOperation;
use Google\AdsApi\AdWords\v201609\cm\AdGroupService;
use Google\AdsApi\AdWords\v201609\cm\AdGroupStatus;
use Google\AdsApi\AdWords\v201609\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example removes an ad group. To get ad groups, run GetAdGroups.php.
 */
class RemoveAdGroup {

  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $adGroupService = $adWordsServices->get($session, AdGroupService::class);

    $operations = [];
    // Create ad group with REMOVED status.
    $adGroup = new AdGroup();
    $adGroup->setId($adGroupId);
    $adGroup->setStatus(AdGroupStatus::REMOVED);

    // Create ad group operation and add it to the list.
    $operation = new AdGroupOperation();
    $operation->setOperand($adGroup);
    $operation->setOperator(Operator::SET);
    $operations[] = $operation;

    // Remove the ad group on the server.
    $result = $adGroupService->mutate($operations);

    $adGroup = $result->getValue()[0];
    printf("Ad group with ID %d was removed.\n", $adGroup->getId());
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::AD_GROUP_ID));
  }
}

RemoveAdGroup::main();


text:
/*
 * Programmer:	Quincey Koziol
 *		Saturday, September 12, 2015
 *
 * Purpose:	This file contains declarations which define macros for the
 *		H5HL package.  Including this header means that the source file
 *		is part of the H5HL package.
 */
#ifndef _H5HLmodule_H
#define _H5HLmodule_H

/* Define the proper control macros for the generic FUNC_ENTER/LEAVE and error
 *      reporting macros.
 */
#define H5HL_MODULE
#define H5_MY_PKG       H5HL
#define H5_MY_PKG_ERR   H5E_HEAP
#define H5_MY_PKG_INIT  NO

#endif /* _H5HLmodule_H */


text:
namespace pe {

// A helper class that assists in assigning address space to PE image sections,
// building self-consistent PE image headers etc.
class PEImageLayoutBuilder : public PECoffImageLayoutBuilder {
 public:
  // Constructs a new image layout builder that populates the provided image
  // layout. The image layout must outlive the builder.
  explicit PEImageLayoutBuilder(ImageLayout* image_layout);

  // Accessors.
  BlockGraph::Block* dos_header_block() { return dos_header_block_; }
  BlockGraph::Block* nt_headers_block() { return nt_headers_block_; }
  const BlockGraph::Block* dos_header_block() const {
    return dos_header_block_;
  }
  const BlockGraph::Block* nt_headers_block() const {
    return nt_headers_block_;
  }

  // Lays out the image headers, and sets the file and section alignment using
  // the values from the header.
  // @param dos_header_block must be a block that's a valid DOS header
  //    and stub. This block must also refer to the NT headers block,
  //    which in turn must contain valid NT headers.
  // @returns true iff the dos_header_block is valid.
  // @pre OpenSection and LayoutBlock must not have been called.
  bool LayoutImageHeaders(BlockGraph::Block* dos_header_block);

  // Creates sections and lays out blocks using the provided ordered block
  // graph as a template. Lays out all sections except for the reloc section,
  // which must be the last section if it is present.
  // @param obg the ordered block graph to layout, which must be for the same
  //     block-graph as used in the constructor.
  // @returns true on success, false otherwise.
  // @pre LayoutImageHeaders has been called.
  bool LayoutOrderedBlockGraph(const OrderedBlockGraph& obg);

  // Finalizes the image layout. This builds the relocs, finalizes the headers,
  // and does any other PE touch-ups that are required to make the image
  // self-consistent. This may remove and/or modify blocks in the block-graph.
  // @returns true on success, false otherwise.
  bool Finalize();

 private:
  // Ensure that the Safe SEH Table is sorted.
  bool SortSafeSehTable();
  // Allocates and populates a new relocations section containing
  // relocations for all absolute references in address_space_.
  bool CreateRelocsSection();
  // Write the NT headers and section headers to the image.
  // After this is done, the image is "baked", and everything except for
  // the image checksum should be up to date.
  bool FinalizeHeaders();
  // Ensure that the image layout has the same number of blocks as the
  // block-graph. The relocs blocks that are in the block-graph but not in the
  // image layout will be removed. If there are extra blocks from other sections
  // in the block-graph an error will be returned.
  // @returns true if the block-graph and the image layout are consistent,
  //     false otherwise.
  bool ReconcileBlockGraphAndImageLayout();

  // The blocks that describe the DOS header and the NT headers.
  BlockGraph::Block* dos_header_block_;
  BlockGraph::Block* nt_headers_block_;

  DISALLOW_COPY_AND_ASSIGN(PEImageLayoutBuilder);
};

}  // namespace pe

#endif  // SYZYGY_PE_PE_IMAGE_LAYOUT_BUILDER_H_


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class xmlns="http://xml.phpdox.net/src" full="Yaf_Exception_LoadFailed_View" namespace="" name="Yaf_Exception_LoadFailed_View">
  <extends name="Yaf_Exception_LoadFailed" full="Yaf_Exception_LoadFailed"/>
  <constructor name="__construct" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact=""/>
      <return type="void"/>
    </docblock>
  </constructor>
  <method name="getPrevious" abstract="false" static="false" visibility="public" final="false">
    <docblock>
      <description compact=""/>
      <return type="void"/>
    </docblock>
  </method>
</class>


text:
var AUTH0_CLIENT_ID='9Ko5GzizqYRXqdAXtYKwTjXtPGryhHpO';
var AUTH0_CALLBACK_URL=location.href;
var AUTH0_DOMAIN='samples.auth0.com';


text:
/*
 * 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.
 */
package com.facebook.presto.sql.tree;

import java.util.Objects;

import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

public final class RenameTable
        extends Statement
{
    private final QualifiedName source;
    private final QualifiedName target;

    public RenameTable(QualifiedName source, QualifiedName target)
    {
        this.source = requireNonNull(source, "source name is null");
        this.target = requireNonNull(target, "target name is null");
    }

    public QualifiedName getSource()
    {
        return source;
    }

    public QualifiedName getTarget()
    {
        return target;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context)
    {
        return visitor.visitRenameTable(this, context);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(source, target);
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj) {
            return true;
        }
        if ((obj == null) || (getClass() != obj.getClass())) {
            return false;
        }
        RenameTable o = (RenameTable) obj;
        return Objects.equals(source, o.source) &&
                Objects.equals(target, o.target);
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("source", source)
                .add("target", target)
                .toString();
    }
}


text:
import {expect} from 'chai';
import {createRequest, handleRequestError, getFileSize} from '../utils';
import {NESTEST_ROM_PATH, NESTEST_THUMB_PATH, roms} from '../fixtures';

describe('ROMs API', () => {
  describe('GET /api/roms/', () => {
    it('returns list of ROMs', () => {
      return createRequest()
        .get('/api/roms/')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(200);
          expect(response).to.be.json;
          expect(response.body).to.deep.equal(roms.all);
        });
    });
  });

  describe('GET /api/roms/:id', () => {
    it('returns ROM with ID', () => {
      return createRequest()
        .get('/api/roms/nes-test')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(200);
          expect(response).to.be.json;
          expect(response.body).to.deep.equal(roms.nestest);
        });
    });

    it('returns 404 for nonexistent ROM', () => {
      return createRequest()
        .get('/api/roms/xxx')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(404);
          expect(response).to.be.json;
          expect(response.body).to.deep.equal({message: 'ROM xxx not found.'});
        });
    });
  });

  describe('GET /api/roms/files/:name', () => {
    it('returns ROM file with name', () => {
      return createRequest()
        .get('/api/roms/files/NES_Test.nes')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(200);
          expect(response).to.have.header('Content-Type', 'application/octet-stream');
          expect(response).to.have.header('Content-Length', getFileSize(NESTEST_ROM_PATH));
        });
    });

    it('returns ROM thumbnail with name', () => {
      return createRequest()
        .get('/api/roms/files/NES_Test.jpg')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(200);
          expect(response).to.have.header('Content-Type', 'image/jpeg');
          expect(response).to.have.header('Content-Length', getFileSize(NESTEST_THUMB_PATH));
        });
    });

    it('returns 404 for nonexistent file', () => {
      return createRequest()
        .get('/api/roms/files/xxx')
        .catch(handleRequestError)
        .then(response => {
          expect(response).to.have.status(404);
          expect(response).to.be.json;
          expect(response.body).to.deep.equal({message: 'File xxx not found.'});
        });
    });
  });
});


text:
var should = require('chai').should();
var reformat = require(process.cwd() + '/lib/reformat');

describe('reformat function', function(){
  it('should return m=13 and y=2014 for january 2015', function(){
    var dat = {day: '1', month: '1', year:'2015'};
    reformat(dat).should.eql({q:'1', m:'13', y:'2014'})
  })
})


text:
from schematax import *
"""
Testing functionaliity of the schemata package

"""
import time

import random

timesf = []
timess = []
for t in xrange(50):
    xs = []

    for _ in range(t):

        string = ""
        for i in range(10):
            string += str(random.randint(0,1))
        xs.append(string)

    start = time.clock()
    ssn = complete_fast(xs)
    end = time.clock()
    nt= end - start
    timesf.append(nt)

    start = time.clock()
    ssf = complete(xs)
    end = time.clock()
    ft =  end - start
    timess.append(ft)
    print ft,nt
    if len(ssf) - len(ssn) !=0:
       print 'fucked'
       break

import matplotlib.pyplot as plt

plt.plot(timesf,color='red')
plt.plot(timess)
plt.show()


text:
layout: post
title: !binary |-
  Q29pbmNpZGVuY2lhPyBIbW1tbW3igKY=
tags:
- pop culture
- micrographic
---
Continuando con la cartelística, hojeando otro libro me encontré esta ilustración, una cartel publicitario de pastillas para la tos. Las pastillas en cuestión se llamaban REM

Pues parece que al bueno de Michael Stipe le hizo gracia la coincidencia…


text:
package com.alibaba.json.test.benchmark.decode;

import com.alibaba.json.test.benchmark.BenchmarkCase;
import com.alibaba.json.test.codec.Codec;

public class IntArray1000Decode extends BenchmarkCase {

    private String text;

    public IntArray1000Decode(){
        super("IntArray1000Decode");

        StringBuilder buf = new StringBuilder();

        buf.append('[');
        for (int i = 0; i < 1000; ++i) {
            if (i != 0) {
                buf.append(",");
            }
            buf.append(i);
        }
        buf.append(']');
        this.text = buf.toString();
    }

    @Override
    public void execute(Codec codec) throws Exception {
        codec.decode(text);
    }
}


text:
class Event {

    public:
        Event(){ id = 0; }

        enum Type { Publish=1, Comment=2, Favorite=4, Follow=8 };

        // Publish: source = author, track, no target, no message
        // Comment: source = author, target, possible track, message = comment
        // Favorite: source, target = artist, track, no message
        // Follow: source = follower, target = followed, no track, no message

        int id;
        Type type;
        User source, target;
        Track track;
        std::string message;
        std::string date;

        void push();

        void fill(Dict*) const;

};

class EventList: public std::vector<Event> {

    public:
        EventList(){}

        static EventList user(const User &u, int limit=0);
        static EventList track(const Track &t);

        Dict* fill(Dict*, const std::string &section, bool hasForm) const;

    private:
        EventList(std::string cond, int limit=0);

};

#endif // SOCIAL_EVENT_H


text:
import Button from "@material-ui/core/Button";
import { createStyles, withStyles, WithStyles } from "@material-ui/core/styles";
import Toolbar from "@material-ui/core/Toolbar";
import * as React from "react";

import i18n from "../../i18n";

const styles = createStyles({
  cardActions: {
    flexDirection: "row-reverse" as "row-reverse"
  }
});

interface FormActionsProps extends WithStyles<typeof styles> {
  submitLabel: string;
  onCancel?();
  onSubmit?(event: React.FormEvent<any>);
}

const FormActions = withStyles(styles, { name: "FormActions" })(
  ({ classes, onCancel, onSubmit, submitLabel }: FormActionsProps) => (
    <Toolbar className={classes.cardActions}>
      <Button
        variant="contained"
        color="primary"
        onClick={onSubmit}
        type="submit"
      >
        {submitLabel}
      </Button>
      {onCancel && (
        <Button onClick={onCancel}>
          {i18n.t("Cancel", { context: "button" })}
        </Button>
      )}
    </Toolbar>
  )
);
FormActions.displayName = "FormActions";
export default FormActions;


text:
package com.hcjcch.designpattern.templatedesignpatten.test1;

/**
 * Created by hcjcch on 2015/4/19.
 */
public class ConcreteTemplate extends AbstractTemplate{
    //基本方法的实现
    @Override
    public void abstractMethod() {
        //业务相关的代码
    }
    //重写父类的方法
    @Override
    public void hookMethod() {
        //业务相关的代码
    }
}


text: <tbd>Een foutmelding (soap header moet leeg zijn)</tbd>


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>STScene Class Reference</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.2 (build 963)" />

Structure SDK

				Occipital

STScene Class Reference

					<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents">Table of Contents</button>

					<select id="jumpTo">
	<option value="top">Jump To…</option>

	<option value="overview">Overview</option>

	<option value="tasks">Tasks</option>

	<option value="instance_methods">Instance Methods</option>

	<option value="//api/name/initWithContext:freeGLTextureUnit:">    - initWithContext:freeGLTextureUnit:</option>

	<option value="//api/name/lockAndGetSceneMesh">    - lockAndGetSceneMesh</option>

	<option value="//api/name/unlockSceneMesh">    - unlockSceneMesh</option>

	<option value="//api/name/renderMeshFromViewpoint:cameraGLProjection:alpha:highlightOutOfRangeDepth:wireframe:">    - renderMeshFromViewpoint:cameraGLProjection:alpha:highlightOutOfRangeDepth:wireframe:</option>

	<option value="//api/name/clear">    - clear</option>

</select>

Overview

Tasks

Instance Methods

initWithContext:freeGLTextureUnit:

lockAndGetSceneMesh

unlockSceneMesh

renderMeshFromViewpoint:cameraGLProjection:alpha:highlightOutOfRangeDepth:wireframe:

clear

Index

Hierarchy

STScene Class Reference

	Inherits from
	NSObject

	Declared in
	StructureSLAM.h

Overview

Common data shared and updated by the SLAM pipeline.

An STScene object contains information about the sensor and the reconstructed mesh.
Special care should be taken when accessing STScene members if an STTracker or STMapper is still active, as they could be accessing the STScene from background threads.
In particular, STMesh objects should be properly locked.

Tasks

		– initWithContext:freeGLTextureUnit:

		– lockAndGetSceneMesh

		– unlockSceneMesh

		– renderMeshFromViewpoint:cameraGLProjection:alpha:highlightOutOfRangeDepth:wireframe:

		– clear

Instance Methods

initWithContext:freeGLTextureUnit:

Mandatory initializer for STScene.

- (instancetype)initWithContext:(EAGLContext *)glContext freeGLTextureUnit:(GLenum)textureUnit

Parameters

glContext

a valid EAGLContext.

textureUnit

A GL_TEXTUREX unit which will be used when SLAM objects need to render meshes to an OpenGL texture.

Declared In

		StructureSLAM.h

lockAndGetSceneMesh

Reference to the current scene mesh.

- (STMesh *)lockAndGetSceneMesh

Discussion

This mesh may be modified by a background thread if an instance of STMapper is running, so proper locking is necessary.

Declared In

		StructureSLAM.h

unlockSceneMesh

Unlocks the mesh previously locked with lockAndGetSceneMesh.

- (void)unlockSceneMesh

Declared In

		StructureSLAM.h

renderMeshFromViewpoint:cameraGLProjection:alpha:highlightOutOfRangeDepth:wireframe:

Render the scene mesh from the given viewpoint.

- (BOOL)renderMeshFromViewpoint:(GLKMatrix4)cameraPose cameraGLProjection:(GLKMatrix4)glProjection alpha:(float)alpha highlightOutOfRangeDepth:(BOOL)highlightOutOfRangeDepth wireframe:(BOOL)wireframe

Parameters

cameraPose

A GLKMatrix4 camera position used for rendering.

glProjection

projection matrix used during rendering. See also [STDepthFrame glProjectionMatrix] and [STColorFrame glProjectionMatrix].

alpha

A float value for transparency between 0 (fully transparent) and 1 (fully opaque)

highlightOutOfRangeDepth

whether the areas of the mesh which are below Structure Sensor minimal depth range should be highlighted in red.

wireframe

whether or not to render a wireframe of the mesh or filled polygons. If enabled, STMapper needs liveWireframeMeshEnabled to be set.

Return Value

TRUE on success, FALSE if there is no STMapper attached to the same STScene with the corresponding (wireframe or triangles) live mode enabled.

Discussion

A virtual camera with the given projection and pose matrices will be used to render the mesh using OpenGL. This method is generally faster than using sceneMeshRef and manually rendering it, since in most cases STScene can reuse mesh data previously uploaded to the GPU.

Declared In

		StructureSLAM.h

clear

Clear the scene mesh and state.

- (void)clear

Declared In

		StructureSLAM.h

Index

Hierarchy

© 2015 Occipital. All rights reserved. (Last updated: 2015-05-20)

						Generated by appledoc 2.2 (build 963).


text:
'use strict';

// Metrics controller
angular.module('metrics').controller('MetricsController', ['$scope', '$modal', '$log', '$rootScope', '$stateParams', '$state', '$location', 'Authentication', 'Metrics','Dashboards', 'ConfirmModal',
	function($scope, $modal, $log, $rootScope, $stateParams, $state, $location, Authentication, Metrics, Dashboards, ConfirmModal) {
		$scope.authentication = Authentication;

        $scope.productName = $stateParams.productName;

        $scope.dashboardName = $stateParams.dashboardName;

        /* values for form drop downs*/
        $scope.metricTypes = ['Average', 'Maximum', 'Minimum', 'Last', 'Slope'];

        $scope.operatorOptions = [{alias: 'lower than', value: '<'}, {alias: 'higher than', value: '>'}];

        $scope.deviationOptions = [{alias: 'negative deviation', value: '<'}, {alias: 'positive deviation', value: '>'}, {alias: '', value: ''}];

        $scope.targets = [''];

        $scope.metric = {};

        $scope.metric.dashboardId = Dashboards.selected._id;

        $scope.metric.targets = [''];

        $scope.enableBenchmarking = 'disabled';

        $scope.enableRequirement ='disabled';

        $scope.percentageOptions = [
            {alias: '10%', value: '0.1'},
            {alias: '25%', value: '0.25'},
            {alias: '50%', value: '0.5'},
            {alias: '100%', value: '1.00'},
            {alias: '200%', value: '2.00'},
            {alias: '300%', value: '3.00'},
            {alias: '400%', value: '4.00'},
            {alias: '500%', value: '5.00'},
        ];

        $scope.$watch('enableRequirement', function (newVal, oldVal) {

            if (newVal !== oldVal) {

                if($scope.enableRequirement === 'disabled'){

                    $scope.metric.requirementOperator = null;
                    $scope.metric.requirementValue = null;

                }
            }
        });

        $scope.addTarget = function() {

            $scope.metric.targets.push('');

        };

        $scope.removeTarget = function(index) {

            $scope.metric.targets.splice(index, 1);

        };

        $scope.loadTags = function(query){

            var matchedTags = [];

            _.each(Dashboards.selected.tags, function(tag){

                if(tag.text.toLowerCase().match(query.toLowerCase()))
                    matchedTags.push(tag);
            });

                return matchedTags;

        };

        $scope.initCreateForm = function () {

           if (Metrics.clone.alias ) $scope.metric = Metrics.clone;
        };

        // Create new Metric
		$scope.create = function() {

            /* Update tags in Dashboard if any new are added */

            if(Dashboards.updateTags($scope.metric.tags)) Dashboards.update().success(function(dashboard){});

            $scope.metric.productName = $stateParams.productName;
            $scope.metric.dashboardName = $stateParams.dashboardName;

            Metrics.create($scope.metric).success(function (metric) {

            /* reset cloned metric */
                Metrics.clone = {};

                $location.path('browse/' + $stateParams.productName + '/' + $stateParams.dashboardName);
            });

        };

		// Remove existing Metric
		$scope.remove = function(metric) {
			if ( metric ) {
				metric.$remove();

				for (var i in $scope.metrics) {
					if ($scope.metrics [i] === metric) {
						$scope.metrics.splice(i, 1);
					}
				}
			} else {
				$scope.metric.$remove(function() {
					$location.path('metrics');
				});
			}
		};

		// Update existing Metric
		$scope.update = function() {

            /* Update tags in Dashboard if any new are added */

            if(Dashboards.updateTags($scope.metric.tags)) Dashboards.update().success(function(dashboard){});

            $scope.metric.productName = $stateParams.productName;
            $scope.metric.dashboardName = $stateParams.dashboardName;

            Metrics.update($scope.metric).success(function (metric) {

                if ($rootScope.previousStateParams)
                    $state.go($rootScope.previousState,$rootScope.previousStateParams);
                else
                    $state.go($rootScope.previousState);
            });
		};

		// Find a list of Metrics
		$scope.find = function() {
			$scope.metrics = Metrics.query();
		};

		// Find existing Metric
		$scope.findOne = function() {

            Metrics.get($stateParams.metricId).success(function(metric){

                $scope.metric = metric;

                /* set benchmark and requirement toggles */

                if($scope.metric.requirementValue)
                    $scope.enableRequirement ='enabled';

                if($scope.metric.benchmarkValue)
                    $scope.enableBenchmarking = 'enabled';

            });
		};

       $scope.clone = function() {

           $scope.metric._id = undefined;

           Metrics.clone = $scope.metric;

           $state.go('createMetric',{"productName":$stateParams.productName, "dashboardName":$stateParams.dashboardName});

       }
       $scope.cancel = function() {

          if ($rootScope.previousStateParams)
              $state.go($rootScope.previousState,$rootScope.previousStateParams);
          else
              $state.go($rootScope.previousState);

       }
        $scope.openDeleteConfirmation = function (size, index) {

            Metrics.selected = $scope.metric;

            ConfirmModal.itemType = 'Delete metric ';
            ConfirmModal.selectedItemId = $scope.metric._id;
            ConfirmModal.selectedItemDescription = $scope.metric.alias;

            var modalInstance = $modal.open({
                templateUrl: 'ConfirmDelete.html',
                controller: 'ModalInstanceController',
                size: size//,
            });

            modalInstance.result.then(function (metricId) {

                Metrics.delete(metricId).success(function(metric){

                    /* refresh dashboard*/
                    Dashboards.get($scope.productName, $scope.dashboardName).success(function(dashboard){

                        $scope.dashboard = Dashboards.selected;

                        /* return to previuos state*/
                        $state.go($rootScope.previousState,$rootScope.previousStateParams);

                    });

                });

            }, function () {
                $log.info('Modal dismissed at: ' + new Date());
            });
        };

    }
]);


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>metageta.icons.shp_img</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

MetaGETA (Metadata Gathering, Extraction and Transformation)

        Package metageta ::
        Module icons ::
        Class shp_img

[hide private]

[frames] | no frames]

Class shp_img

source code

        Class Variables
        [hide private]

        format = 'gif'

        data = 'R0lGODlhEAAQAMIFABAQEIBnII+HgLS0pfDwsC8gIC8gIC8gICH5BA...

        Class Variable Details
        [hide private]

data

Value:

'''R0lGODlhEAAQAMIFABAQEIBnII+HgLS0pfDwsC8gIC8gIC8gICH5BAEKAAcALAAAAAA
QABAAAAND
            eLrcJzBKqcQIN+MtwAvTNHTPSJwoQAigxwpouo4urZ7364I4cM8kC0x20n
2GRGEtJGl9NFBMkBny
            HHzYrNbB7XoXCQA7'''

         Home

         Trees

         Indices

         Help

MetaGETA (Metadata Gathering, Extraction and Transformation)

      http://epydoc.sourceforge.net


text:
package com.graphhopper.routing;

import com.graphhopper.routing.ch.NodeOrderingProvider;
import com.graphhopper.routing.ch.PrepareContractionHierarchies;
import com.graphhopper.routing.util.CarFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.weighting.FastestWeighting;
import com.graphhopper.routing.weighting.Weighting;
import com.graphhopper.storage.CHConfig;
import com.graphhopper.storage.GraphHopperStorage;
import com.graphhopper.storage.RAMDirectory;
import com.graphhopper.storage.RoutingCHGraphImpl;
import com.graphhopper.util.PMap;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class AlternativeRouteCHTest {
    private final FlagEncoder carFE = new CarFlagEncoder();
    private final EncodingManager em = EncodingManager.create(carFE);
    private final Weighting weighting = new FastestWeighting(carFE);

    public GraphHopperStorage createTestGraph(EncodingManager tmpEM) {
        final GraphHopperStorage graph = new GraphHopperStorage(new RAMDirectory(), tmpEM, false);
        CHConfig chConfig = CHConfig.nodeBased("p", new FastestWeighting(carFE));
        graph.addCHGraph(chConfig);
        graph.create(1000);

        /*

           9      11
          /\     /  \
         1  2-3-4-10-12
         \   /   \
         5--6-7---8

         */

        // Make all edges the length of T, the distance around v than an s->v->t path
        // has to be locally-shortest to be considered.
        // So we get all three alternatives.

        graph.edge(5, 6, 10000, true);
        graph.edge(6, 3, 10000, true);
        graph.edge(3, 4, 10000, true);
        graph.edge(4, 10, 10000, true);

        graph.edge(6, 7, 10000, true);
        graph.edge(7, 8, 10000, true);
        graph.edge(8, 4, 10000, true);

        graph.edge(5, 1, 10000, true);
        graph.edge(1, 9, 10000, true);
        graph.edge(9, 2, 10000, true);
        graph.edge(2, 3, 10000, true);

        graph.edge(4, 11, 9000, true);
        graph.edge(11, 12, 9000, true);
        graph.edge(12, 10, 10000, true);

        graph.freeze();

        // Carefully construct the CH so that the forward tree and the backward tree
        // meet on all four possible paths from 5 to 10
        // 5 ---> 11 will be reachable via shortcuts, as 11 is on shortest path 5 --> 12
        final List<Integer> nodeOrdering = Arrays.asList(0, 10, 12, 4, 3, 2, 5, 1, 6, 7, 8, 9, 11);
        PrepareContractionHierarchies contractionHierarchies = PrepareContractionHierarchies.fromGraphHopperStorage(graph, chConfig);
        contractionHierarchies.useFixedNodeOrdering(new NodeOrderingProvider() {
            @Override
            public int getNodeIdForLevel(int level) {
                return nodeOrdering.get(level);
            }

            @Override
            public int getNumNodes() {
                return nodeOrdering.size();
            }
        });
        contractionHierarchies.doWork();
        return graph;
    }

    @Test
    public void testCalcAlternatives() {
        GraphHopperStorage g = createTestGraph(em);
        PMap hints = new PMap();
        hints.putObject("alternative_route.max_weight_factor", 2.3);
        hints.putObject("alternative_route.local_optimality_factor", 0.5);
        hints.putObject("alternative_route.max_paths", 4);
        AlternativeRouteCH altDijkstra = new AlternativeRouteCH(new RoutingCHGraphImpl(g.getCHGraph(), weighting), hints);
        List<AlternativeRouteCH.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(5, 10);
        assertEquals(3, pathInfos.size());
        // 4 -> 11 -> 12 is shorter than 4 -> 10 -> 12 (11 is an admissible via node), BUT
        // 4 -> 11 -> 12 -> 10 is too long compared to 4 -> 10
    }

    @Test
    public void testRelaxMaximumStretch() {
        GraphHopperStorage g = createTestGraph(em);
        PMap hints = new PMap();
        hints.putObject("alternative_route.max_weight_factor", 4);
        hints.putObject("alternative_route.local_optimality_factor", 0.5);
        hints.putObject("alternative_route.max_paths", 4);
        AlternativeRouteCH altDijkstra = new AlternativeRouteCH(new RoutingCHGraphImpl(g.getCHGraph(), weighting), hints);
        List<AlternativeRouteCH.AlternativeInfo> pathInfos = altDijkstra.calcAlternatives(5, 10);
        assertEquals(4, pathInfos.size());
        // 4 -> 11 -> 12 is shorter than 4 -> 10 -> 12 (11 is an admissible via node), AND
        // 4 -> 11 -> 12 -> 10 is not too long compared to 4 -> 10
    }

}


text:
package com.atexpose.dispatcher.channels.web_channel.redirect;

import io.schinzel.basicutils.thrower.Thrower;
import lombok.SneakyThrows;
import org.apache.http.client.utils.URIBuilder;

import java.net.URI;

/**
 * The purpose of this class is to redirect to a fail whale page.
 * <p>
 * Created by schinzel on 2017-04-22.
 */
class FailWhaleRedirect implements IRedirect {
    private final String to;

    FailWhaleRedirect(String to) {
        Thrower.throwIfVarEmpty(to, "to");
        //Set to. Add "/" as first char if is missing
        this.to = (to.charAt(0) == '/') ? to : "/" + to;
    }

    @Override
    public boolean shouldRedirect(URI uri) {
        //Should redirect - i.e. return true - if the argument page is not the
        //same as the to page.
        return !(uri.getPath().equalsIgnoreCase(this.to));
    }

    @Override
    @SneakyThrows
    public URI getNewLocation(URI uri) {
        return new URIBuilder(uri).setPath(this.to).build();
    }
}


text:
package libSB.fx.observableConstants;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

/**
 *
 * @author Simon Berndt
 */
public final class ConstantList<T> implements ObservableList<T> {

    private final List<T> autogeneratedList;

    public static <E extends Enum<E>> ConstantList<E> fromEnum(Class<E> enumClass) {
        return new ConstantList<>(enumClass.getEnumConstants());
    }

    public ConstantList(T... constants) {
	this.autogeneratedList = Collections.unmodifiableList(Arrays.asList(constants));
    }

    @Override
    public void addListener(ListChangeListener<? super T> listener) {
	// No need for this
    }

    @Override
    public void removeListener(ListChangeListener<? super T> listener) {
	// No need for this
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean addAll(T... elements) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean setAll(T... elements) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean setAll(Collection<? extends T> col) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean removeAll(T... elements) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean retainAll(T... elements) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void remove(int from, int to) {
	throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int size() {
	return autogeneratedList.size();
    }

    @Override
    public boolean isEmpty() {
	return autogeneratedList.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
	return autogeneratedList.contains(o);
    }

    @Override
    public Iterator<T> iterator() {
	return autogeneratedList.iterator();
    }

    @Override
    public Object[] toArray() {
	return autogeneratedList.toArray();
    }

    @Override
    @SuppressWarnings("unchecked")
    public <N> N[] toArray(N[] a) {
	return autogeneratedList.toArray(a);
    }

    @Override
    public boolean add(T e) {
	throw new UnsupportedOperationException();
    }

    @Override
    public boolean remove(Object o) {
	throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsAll(Collection<?> c) {
	return autogeneratedList.containsAll(c);
    }

    @Override
    public boolean addAll(Collection<? extends T> c) {
	throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(int index, Collection<? extends T> c) {
	throw new UnsupportedOperationException();
    }

    @Override
    public boolean removeAll(Collection<?> c) {
	throw new UnsupportedOperationException();
    }

    @Override
    public boolean retainAll(Collection<?> c) {
	throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
	throw new UnsupportedOperationException();
    }

    @Override
    public T get(int index) {
	return autogeneratedList.get(index);
    }

    @Override
    public T set(int index, T element) {
	throw new UnsupportedOperationException();
    }

    @Override
    public void add(int index, T element) {
	throw new UnsupportedOperationException();
    }

    @Override
    public T remove(int index) {
	throw new UnsupportedOperationException();
    }

    @Override
    public int indexOf(Object o) {
	return autogeneratedList.indexOf(o);
    }

    @Override
    public int lastIndexOf(Object o) {
	return autogeneratedList.lastIndexOf(o);
    }

    @Override
    public ListIterator<T> listIterator() {
	return autogeneratedList.listIterator();
    }

    @Override
    public ListIterator<T> listIterator(int index) {
	return autogeneratedList.listIterator(index);
    }

    @Override
    public List<T> subList(int fromIndex, int toIndex) {
	return autogeneratedList.subList(fromIndex, toIndex);
    }

    @Override
    public void addListener(InvalidationListener listener) {
	// No need for this
    }

    @Override
    public void removeListener(InvalidationListener listener) {
	// No need for this
    }

}


text:
package com.dm.simple_mvp_demo.ui.login;

/**
 * ILoginView
 * Created by dm on 17-4-19.
 */

public interface ILoginView {
    boolean checkInputInfo();

    void onRegisterSuccessed();

    void onRegisterFailed();

    void onLoginSuccessed();

    void onLoginFailed();
}


text:
Rails plugin that provides a `validates_url_format_of` method to `ActiveRecord` models. URLs are validated by regexp.

Known to be compatible with ActiveRecord 3.0.0.beta, 2.3.5, 2.2.2, 2.1.2.

## Usage

After installing the plugin, it's used like

    class User < ActiveRecord::Base
      validates_url_format_of :url,
                              :allow_nil => true,
                              :message => 'is completely unacceptable'
    end

Takes the same arguments as [`validates_format_of`](http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M001052) except for the `:with` regexp.

The default `:message` is different depending on whether the attribute name contains the word "URL". So you will get "Homepage URL does not appear to be valid" but "Homepage does not appear to be a valid URL" without having to customize the `:message`.

Please note that the regexp used to validate URLs is not perfect, but hopefully good enough. See the test suite. Patches are very welcome.

## Limitations and design choices

Does not handle IPv6.

By design, the plugin does not allow e.g. "http://localhost" or "http://my.localurl", which are valid URLs but not suitable in most web apps. It also requires a "http://" or "https://" prefix, so just "example.com" is not valid. Fix that in the setter.

## Credits and license

By [Henrik Nyh](http://henrik.nyh.se/) under the MIT license:

>  Copyright (c) 2008 Henrik Nyh
>
>  Permission is hereby granted, free of charge, to any person obtaining a copy
>  of this software and associated documentation files (the "Software"), to deal
>  in the Software without restriction, including without limitation the rights
>  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
>  copies of the Software, and to permit persons to whom the Software is
>  furnished to do so, subject to the following conditions:
>
>  The above copyright notice and this permission notice shall be included in
>  all copies or substantial portions of the Software.
>
>  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
>  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
>  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
>  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
>  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
>  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
>  THE SOFTWARE.


text:
using System.Collections.Generic;
using Avalonia.Controls;
using Xunit;

namespace Avalonia.Styling.UnitTests
{
    public class ResourceTests
    {
        [Fact]
        public void FindStyleResource_Should_Find_Correct_Resource()
        {
            Border target;

            var tree = new Decorator
            {
                Styles = new Styles
                {
                    new Style
                    {
                        Resources = new Dictionary<string, object>
                        {
                            { "Foo", "foo resource" },
                            { "Bar", "overridden" },
                        }
                    }
                },
                Child = target = new Border
                {
                    Styles = new Styles
                    {
                        new Style
                        {
                            Resources = new Dictionary<string, object>
                            {
                                { "Bar", "again overridden" },
                            }
                        },
                        new Style
                        {
                            Resources = new Dictionary<string, object>
                            {
                                { "Bar", "bar resource" },
                            }
                        }
                    }
                }
            };

            Assert.Equal("foo resource", target.FindStyleResource("Foo"));
            Assert.Equal("bar resource", target.FindStyleResource("Bar"));
        }

        [Fact]
        public void FindStyleResource_Should_Return_UnsetValue_For_Not_Found()
        {
            Border target;

            var tree = target = new Border
            {
                Styles = new Styles
                    {
                        new Style
                        {
                            Resources = new Dictionary<string, object>
                            {
                                { "Foo", "foo" },
                            }
                        },
                    }
            };

            Assert.Equal(AvaloniaProperty.UnsetValue, target.FindStyleResource("Baz"));
        }
    }
}


text:
<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" href="/css/scenario13.css">

            Resources can depend on many different dimensions, including scale, language and contrast. The resource technology does appropriate fallback behavior to retrieve the most appropriate resource for the current context. The resource qualifiers are evaluated
            in a priority based system (e.g., language is more important than scale). Application developers are encouraged to mark resources as appropriately as possible. Only resources that are appropriate for all contexts should be left without any
            qualifiers. Default resources are qualified resources that are chosen if no resource matches the context. The default language can be set within VS within the Project Properties.

            This sample shows a list of string resources and the ordered set of resource candidates for different languages, scales, etc. Various contexts can be simulated with the drop-down below to see which resources are matched in various situations. Each candidate
            has additional metadata that can used to determine why it was chosen.

        <select id="scenario13SelectLanguage" class="win-dropdown">
            <option value="en-US" class="win-dropdown">English (United States)</option>
            <option value="en-GB" class="win-dropdown">English (United Kingdom)</option>
            <option value="fr-CA" class="win-dropdown">French (Canada)</option>
            <option value="fr-FR" class="win-dropdown">French (France)</option>
            <option value="de-DE" class="win-dropdown">German (Germany)</option>
            <option value="ja" class="win-dropdown">Japanese</option>
        </select>
        <select id="scenario13SelectContrast" class="win-dropdown">
            <option value="standard" class="win-dropdown">Standard</option>
            <option value="black" class="win-dropdown">High Contrast Black</option>
            <option value="white" class="win-dropdown">High Contrast White</option>
            <option value="black" class="win-dropdown">High Contrast #1</option>
            <option value="black" class="win-dropdown">High Contrast #2</option>
        </select>
        <select id="scenario13SelectScale" class="win-dropdown">
            <option value="100" class="win-dropdown">100</option>
            <option value="140" class="win-dropdown">140</option>
            <option value="180" class="win-dropdown">180</option>
        </select>
        <select id="scenario13SelectHomeRegion" class="win-dropdown">
            <option value="001" class="win-dropdown">World</option>
            <option value="019" class="win-dropdown">Americas</option>
            <option value="142" class="win-dropdown">Asia</option>
            <option value="021" class="win-dropdown">Northern America</option>
            <option value="419" class="win-dropdown">Latin America and the Caribbean</option>
            <option value="840" class="win-dropdown">United States of America</option>
            <option value="124" class="win-dropdown">Canada</option>
        </select>
        <button id="scenario13Show" class="win-button">
            Show Resources</button>

                Resource Id

                        <input type="checkbox" disabled="disabled" data-win-bind="checked: isMatch" class="win-checkbox">isMatch

                        <input type="checkbox" disabled="disabled" data-win-bind="checked: isDefault" class="win-checkbox">isDefault


text:
namespace IGCS
{
	AOBBlock::AOBBlock(string blockName, string bytePatternAsString, int occurrence)
									: _blockName{ blockName }, _bytePatternAsString{ bytePatternAsString }, _customOffset{ 0 }, _occurrence{ occurrence },
									  _bytePattern{ nullptr }, _patternMask{ nullptr }, _locationInImage{ nullptr }
	{
	}

	AOBBlock::~AOBBlock()
	{
	}

	bool AOBBlock::scan(LPBYTE imageAddress, DWORD imageSize)
	{
		createAOBPatternFromStringPattern(_bytePatternAsString);
		LPBYTE aobPatternLocation = Utils::findAOBPattern(imageAddress, imageSize, this);
		if (nullptr == aobPatternLocation)
		{
			OverlayConsole::instance().logError("Can't find pattern for block '%s'! Hook not set.", _blockName.c_str());
			return false;
		}
		else
		{
			OverlayConsole::instance().logDebug("Pattern for block '%s' found at address: %p", _blockName.c_str(), (void*)aobPatternLocation);
		}
		_locationInImage = aobPatternLocation;
		return true;
	}

	// Creates an aob_pattern struct which is usable with an aob scan. The pattern given is in the form of "aa bb ??" where '??' is a byte
	// which has to be skipped in the comparison, and 'aa' and 'bb' are hexadecimal bytes which have to have that value at that position.
	// If a '|' is specified in the pattern, the position of the byte following it is the start offset returned by the aob scanner, instead of
	// the position of the first byte of the pattern.
	void AOBBlock::createAOBPatternFromStringPattern(string pattern)
	{
		int index = 0;
		char* pChar = &pattern[0];

		_patternSize = pattern.size();
		_bytePattern = (LPBYTE)calloc(0x1, _patternSize);
		_patternMask = (char*)calloc(0x1, _patternSize);
		_customOffset = 0;

		while (*pChar)
		{
			if (*pChar == ' ')
			{
				pChar++;
				continue;
			}

			if (*pChar == '|')
			{
				pChar++;
				_customOffset = index;
				continue;
			}

			if (*pChar == '?')
			{
				_patternMask[index++] += '?';
				pChar += 2;
				continue;
			}

			_patternMask[index] = 'x';
			_bytePattern[index++] = (Utils::CharToByte(pChar[0]) << 4) + Utils::CharToByte(pChar[1]);
			pChar += 2;
		}
	}

}