text:
import React, {Component} from 'react'
import {Text, DatePickerIOS, StyleSheet, View, TextInput, ScrollView} from 'react-native'

var DatePickerExample = React.createClass({
  getDefaultProps(){
    return{
      date: new Date(),
      timeZoneOffsetInHours: (-1) * (new Date()).getTimezoneOffset() / 60,
    }
  },

  getInitialState(){
    return{
      date: this.props.date,
      timeZoneOffsetInHours: this.props.timeZoneOffsetInHours,
    }
  },

   onDateChange: function(date) {
     this.setState({date: date});
  },

  onTimezoneChange: function(event) {
    // parseInt(需转数字,进制)
    var offset = parseInt(event.nativeEvent.text,10);
    alert(offset);
    if (isNaN(offset)) {
      return;
    }
    this.setState({timeZoneOffsetInHours: offset});
  },

  render: function() {
    // Ideally, the timezone input would be a picker rather than a
    // text input, but we don't have any pickers yet :(
    return (
      <View>
        <WithLabel label="Value:">
          <Text>{
            this.state.date.toLocaleDateString() +
            ' ' +
            this.state.date.toLocaleTimeString()
          }</Text>
        </WithLabel>
        <WithLabel label="Timezone:">
          <TextInput
            onChange={this.onTimezoneChange}
            style={styles.textinput}
            value={this.state.timeZoneOffsetInHours.toString()}
          />
          <Text> hours from UTC</Text>
        </WithLabel>
        <Heading label="Date + time picker" />
        <DatePickerIOS
          date={this.state.date}
          mode="datetime"
          timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
          onDateChange={this.onDateChange}
        />
        <Heading label="Date picker" />
        <DatePickerIOS
          date={this.state.date}
          mode="date"
          timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
          onDateChange={this.onDateChange}
        />
        <Heading label="Time picker, 10-minute interval" />
        <DatePickerIOS
          date={this.state.date}
          mode="time"
          timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
          onDateChange={this.onDateChange}
          minuteInterval={10}
        />
      </View>
    );
  }
});

var WithLabel = React.createClass({
  render: function() {
    return (
      <View style={styles.labelContainer}>
        <View style={styles.labelView}>
          <Text style={styles.label}>
            {this.props.label}
          </Text>
        </View>
        {this.props.children}
      </View>
    );
  }
});

var Heading = React.createClass({
  render: function() {
    return (
      <View style={styles.headingContainer}>
        <Text style={styles.heading}>
          {this.props.label}
        </Text>
      </View>
    );
  }
});

export default class DatePickerIOSView extends Component{
  static navigationOptions = {
    title: 'DatePickerIOSView'
  }
  render(){
    return(
       <ScrollView>
        <DatePickerExample />
       </ScrollView>
    );
  }
}

var styles = StyleSheet.create({
  textinput: {
    height: 26,
    width: 50,
    borderWidth: 0.5,
    borderColor: '#0f0f0f',
    padding: 4,
    fontSize: 13,
  },
  labelContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 2,
  },
  labelView: {
    marginRight: 10,
    paddingVertical: 2,
  },
  label: {
    fontWeight: '500',
  },
  headingContainer: {
    padding: 4,
    backgroundColor: '#f6f7f8',
  },
  heading: {
    fontWeight: '500',
    fontSize: 14,
  },
});

redpajama_set_name: RedPajamaGithub


text:
import sys
import re
import os
import shutil
import commands

"""Copy Special exercise
"""

# +++your code here+++
# Write functions and modify main() to call them

# returns a list of the absolute paths of the special files in the given directory
#
def get_special_paths(dir):
  filenames = os.listdir(dir)
  # print filenames

  # print os.path.abspath(dir)

  special_filenames = {}

  for filename in filenames:
    if filename.endswith(".jpg") or filename.endswith("txt"):
      special_filenames[os.path.abspath(os.path.join(dir, filename))] = filename
  return special_filenames

# given a list of paths, copies those files into the given directory
def copy_to(paths, todir):
  if os.path.exists(todir) != True:
    os.mkdir(todir)
  for special_file_path, special_filename in paths.iteritems():
    shutil.copy(special_file_path, todir + '/' + special_filename)

# given a list of paths, zip those files up into the given zipfile
def zip_to(paths, zippath):
  cmd = 'zip -j ' + zippath + ' '
  for special_file_path, special_filename in paths.iteritems():
    cmd += ' \'' + special_file_path + '\''
  print "Command to run:", cmd   ## good to debug cmd before actually running it
  (status, output) = commands.getstatusoutput(cmd)
  if status:    ## Error case, print the command's output to stderr and exit
    sys.stderr.write(output)
    sys.exit(1)
  print output  ## Otherwise do something with the command's output

def main():
  # This basic command line argument parsing code is provided.
  # Add code to call your functions below.

  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.
  args = sys.argv[1:]
  if not args:
    print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
    sys.exit(1)

  # todir and tozip are either set from command line
  # or left as the empty string.
  # The args array is left just containing the dirs.
  todir = ''
  if args[0] == '--todir':
    todir = args[1]
    del args[0:2]

  tozip = ''
  if args[0] == '--tozip':
    tozip = args[1]
    del args[0:2]

  if len(args) == 0:
    print "error: must specify one or more dirs"
    sys.exit(1)

  # +++your code here+++
  # Call your functions
  if todir != '':
    for arg in args:
      special_filepaths = get_special_paths(arg)
      copy_to(special_filepaths, todir)
  elif tozip != '':
    for arg in args:
      special_filepaths = get_special_paths(arg)
      zip_to(special_filepaths, tozip)
  else:
    for arg in args:
      print get_special_paths(arg)

if __name__ == "__main__":
  main()


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<?php
//echo print_r($programs);
?>

List of Consolidated Reports - Course Registration

Sl. No	Name of the Program & Year 	Action

                 <?php

               $sl_no=1;
                foreach ($programs as $program){
                    if($program->program_type==1){
                     for($i=1;$i<=$program->duration;$i++){
                     ?>

                <?php echo $sl_no++; ?>
                  <a href="<?php echo base_url('/report/consolidated_report_course_registration/'.$program->id.'/'.$i);?>"><?php echo $program->name.' - '.$i.' Year' ;?>

              <a class="btn btn-sm btn-primary" href="<?php echo base_url('/report/consolidated_report_course_registration/'.$program->id.'/'.$i);?>" title="View Registered Courses"> View Registered Courses

                 <?php }  ?>

                <?php echo $sl_no++; ?>
                <a href="<?php echo base_url('/report/consolidated_report_course_registration_arrears/'.$program->id.'/0');?>"><?php echo $program->name.' - Others' ;?>

              <a class="btn btn-sm btn-primary" href="<?php echo base_url('/report/consolidated_report_course_registration_arrears/'.$program->id.'/0');?>" title="View Registered Courses"> View Registered Courses

          <?php  }
                }
                ?>


text:
 #
 # Oak game engine
 # Copyright (c) 2013 Remi Papillie
 #
 # 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.
 #
###############################################################################

#! /usr/bin/env python
# encoding: utf-8

import os,sys
from waflib import Configure,Options,Utils
from waflib.Tools import ccroot,ar
from waflib.Configure import conf

def options(ctx):
	group = ctx.add_option_group("android-specific config")
	group.add_option("--ndk", action = "store", default = os.getenv("ANDROID_NDK"), help = "Android NDK root")

@conf
def find_android_gxx(conf):
	exeDir = os.path.join(conf.options.ndk, "toolchains", "arm-linux-androideabi-4.6", "prebuilt", "windows-x86_64", "bin")
	cxx=conf.find_program(['arm-linux-androideabi-g++'], var = "CXX", path_list=[exeDir])
	cxx=conf.cmd_to_list(cxx)
	conf.get_cc_version(cxx,gcc=True)
	conf.env.CXX_NAME='gcc'
	conf.env.CXX=cxx
@conf
def android_gxx_common_flags(conf):
	v=conf.env
	v['CXX_SRC_F']=[]
	v['CXX_TGT_F']=['-c','-o']
	if not v['LINK_CXX']:v['LINK_CXX']=v['CXX']
	v['CXXLNK_SRC_F']=[]
	v['CXXLNK_TGT_F']=['-o']
	v['CPPPATH_ST']='-I%s'
	v['DEFINES_ST']='-D%s'
	v['LIB_ST']='-l%s'
	v['LIBPATH_ST']='-L%s'
	v['STLIB_ST']='-l%s'
	v['STLIBPATH_ST']='-L%s'
	v['RPATH_ST']='-Wl,-rpath,%s'
	v['SONAME_ST']='-Wl,-h,%s'
	v['SHLIB_MARKER']='-Wl,-Bdynamic'
	v['STLIB_MARKER']='-Wl,-Bstatic'
	v['cxxprogram_PATTERN']='%s'
	v['CXXFLAGS_cxxshlib']=['-fPIC']
	v['LINKFLAGS_cxxshlib']=['-shared']
	v['cxxshlib_PATTERN']='lib%s.so'
	v['LINKFLAGS_cxxstlib']=['-Wl,-Bstatic']
	v['cxxstlib_PATTERN']='lib%s.a'
	v['LINKFLAGS_MACBUNDLE']=['-bundle','-undefined','dynamic_lookup']
	v['CXXFLAGS_MACBUNDLE']=['-fPIC']
	v['macbundle_PATTERN']='%s.bundle'
@conf
def android_gxx_modifier_android9(conf):
	v=conf.env
	v['CXXFLAGS']=[
		"-fPIC",
		"-ffunction-sections",
		"-funwind-tables",
		"-fstack-protector",
		"-D__ARM_ARCH_5__",
		"-D__ARM_ARCH_5T__",
		"-D__ARM_ARCH_5E__",
		"-D__ARM_ARCH_5TE__",
		"-Wno-psabi",
		"-mthumb",
		"-Os",
		"-fomit-frame-pointer",
		"-fno-strict-aliasing",
		"-finline-limit=64",
		"-DANDROID"
	]

	if v.TARGET_ARCH == "armv6":
		v.append_unique('CXXFLAGS', [
			"-march=armv5te",
			"-mtune=xscale",
			"-msoft-float"
		])
	elif v.TARGET_ARCH == "armv7":
		v.append_unique('CXXFLAGS', [
			"-march=armv7-a",
			"-mfloat-abi=softfp",
			"-mfpu=vfpv3-d16"
		])
		v.append_unique('LINKFLAGS', [
			"-march=armv7-a",
			"-Wl,--fix-cortex-a8"
		])

	android_arch = "arm"
	if conf.env.TARGET_ARCH == "mips":
		android_arch = "mips"
	elif conf.env.TARGET_ARCH == "x86":
		android_arch = "x86"

	sysroot = os.path.join(conf.options.ndk, "platforms/android-9/arch-" + android_arch)
	v.append_unique('CXXFLAGS', ["--sysroot=" + sysroot])
	v.append_unique('LINKFLAGS', ["--sysroot=" + sysroot])

	v.append_unique('INCLUDES', [os.path.join(conf.options.ndk, 'sources/cxx-stl/gnu-libstdc++/4.6/include')])
	v.append_unique('INCLUDES', [os.path.join(conf.options.ndk, 'sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include')])
	v.append_unique('INCLUDES', [os.path.join(conf.options.ndk, 'sources/android/native_app_glue/')])

	v.append_unique('LIBPATH', [os.path.join(conf.options.ndk, 'sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a')])
	v.append_unique('LIB', ["supc++", "gnustl_static", "android", "log", "GLESv2", "EGL"])

	# save NDK path for later steps
	v.NDK_ROOT = conf.options.ndk

@conf
def android_gxx_modifier_platform(conf):
	android_gxx_modifier_func=getattr(conf,'android_gxx_modifier_'+conf.env.TARGET_OS,None)
	if android_gxx_modifier_func:
		android_gxx_modifier_func()
def configure(conf):
	# Check that the NDK path was given on the command-line
	conf.msg("NDK path configured with --ndk", conf.options.ndk != None)
	if not conf.options.ndk:
		raise "no NDK path"

	conf.load('android-gcc', tooldir="waf-tools")
	conf.find_android_gxx()
	conf.load('android-ar', tooldir="waf-tools")
	conf.android_gxx_common_flags()
	conf.android_gxx_modifier_platform()
	conf.cxx_load_tools()
	conf.cxx_add_flags()
	conf.link_add_flags()


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_demo"
    tools:context="id.pratama.examplebuildflavors.DemoActivity">

</RelativeLayout>


text:
package com.ms.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

public class DateUtils {

	public static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR);

	/**
	 * @return
	 */
	public static Date getCurrentDateTimeInGMT() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.add(Calendar.MILLISECOND, cal.getTimeZone().getRawOffset() * (-1));
		return cal.getTime();
	}

	/**
	 * @return
	 */
	public static Date getCurrentDateTime() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		return cal.getTime();
	}

	/**
	 * @return
	 */
	public static Calendar getCustomCalendarInstance() {
		Calendar cal = Calendar.getInstance();
		cal.setFirstDayOfWeek(0);
		return cal;
	}

	/**
	 * @param currentDate
	 * @param noOfDays
	 * @return
	 */
	public static Date getPreviousDateByDays(Date currentDate, int noOfDays) {
		Calendar currentCalander = Calendar.getInstance();
		currentCalander.setTime(currentDate);
		currentCalander.add(Calendar.DAY_OF_YEAR, -noOfDays);
		return currentCalander.getTime();
	}

	/**
	 * @param date
	 * @return
	 */
	public static long getTimeInMilis(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar.getTimeInMillis();
	}

	/**
	 * @param date
	 * @return
	 */
	public static Date convertToDateObject (String dateinStr,String format ) {
		 Date date = null;
		 if(dateinStr !=null  && !dateinStr.equals("")){
			 try {
				 DateFormat df = new SimpleDateFormat(format);
				 date = df.parse(dateinStr);

			    } catch (ParseException e) {
			        e.printStackTrace();
			    }
		 }

		 return date;
	}

	public static String convertToStringObject (Date date,String format ) {
		String dateStr = null;
		if(date != null){
		 DateFormat df = new SimpleDateFormat(format);
		 dateStr = df.format(date);
		}
		 return dateStr;
	}

	public static Timestamp convertStrtDatetoTimeStamp(String dateStr) {
		Date date = convertToDateObject(dateStr,"MM/dd/yyyy");
		if(date!= null){
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			Timestamp tm = new Timestamp(cal.getTimeInMillis());
			return tm;
		}else
			return null;

	}
	public static String convertTimeStampToDateStr(Timestamp timestamp) {
		if(timestamp != null){
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(timestamp.getTime());
		return convertToStringObject(cal.getTime(),"MM/dd/yyyy");
		}else
			return null;

	}

	/**
	 * @param sourceDate
	 * @return
	 */
	public static String  convertDateFormat(String sourceDate) {
		String formattedDate = "";
		DateFormat readFormat = new SimpleDateFormat("MMM dd yyyy hh:mmaaa", Locale.US);

		DateFormat writeFormat = new SimpleDateFormat("MM/dd/yyyy");
		Date date = null;
		try {
			date = readFormat.parse(sourceDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (date != null) {
			formattedDate = writeFormat.format(date);
		}
		return formattedDate;

	}

}


text:
package org.adligo.fabricate.common.files;

import java.io.IOException;

/**
 * This interface helps tests track
 * IOExceptions that are thrown from streams, or channels
 * which throw a IOException on close.
 * @author scott
 *
 */
public interface I_IOCloseTracker {
  public void onCloseException(IOException x);
}


text:
            <ut-dropdown
                icon="operations-icon-share"
                title="Share"
                template="/app/partials/grid/share.html"
            >
            </ut-dropdown>

Crowelab

Protocols

{{protocol.id}}

{{protocol.protocol}}

            <button class="btn" ng-click="edit()">

                Edit
            </button>
            <button class="btn" ng-click="comment()"> Comment</button>

            <ut-edit-module title="Details">

                            Protocol:
                            {{protocol.protocol}}

                            Description:
                            {{protocol.description}}

            </ut-edit-module>
            <ut-edit-module title="Attachments">
                <ut-attachment-module
                    o="Protocol"
                    oid="protocol.id"
                >
                </ut-attachment-module>
            </ut-edit-module>

            <ut-edit-module title="Activity">
                <ut-activity-module
                    o="Protocol"
                    oid="protocol.id"
                    comment="comment"
                >
                </ut-activity-module>
            </ut-edit-module>


text: export { zlibSync, unzlibSync } from "fflate";


text:
/**
 * This class is generated by jOOQ
 */
package org.openforis.collect.persistence.jooq.tables;

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

import org.jooq.Field;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import org.openforis.collect.persistence.jooq.Collect;
import org.openforis.collect.persistence.jooq.Keys;
import org.openforis.collect.persistence.jooq.tables.records.OfcLogoRecord;

/**
 * This class is generated by jOOQ.
 */
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class OfcLogo extends TableImpl<OfcLogoRecord> {

	private static final long serialVersionUID = 90322409;

	/**
	 * The reference instance of collect.ofc_logo
	 */
	public static final OfcLogo OFC_LOGO = new OfcLogo();

	/**
	 * The class holding records for this type
	 */
	@Override
	public Class<OfcLogoRecord> getRecordType() {
		return OfcLogoRecord.class;
	}

	/**
	 * The column collect.ofc_logo.pos.
	 */
	public final TableField<OfcLogoRecord, Integer> POS = createField("pos", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");

	/**
	 * The column collect.ofc_logo.image.
	 */
	public final TableField<OfcLogoRecord, byte[]> IMAGE = createField("image", org.jooq.impl.SQLDataType.BLOB.nullable(false), this, "");

	/**
	 * Create a collect.ofc_logo table reference
	 */
	public OfcLogo() {
		this("ofc_logo", null);
	}

	/**
	 * Create an aliased collect.ofc_logo table reference
	 */
	public OfcLogo(String alias) {
		this(alias, OFC_LOGO);
	}

	private OfcLogo(String alias, Table<OfcLogoRecord> aliased) {
		this(alias, aliased, null);
	}

	private OfcLogo(String alias, Table<OfcLogoRecord> aliased, Field<?>[] parameters) {
		super(alias, Collect.COLLECT, aliased, parameters, "");
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public UniqueKey<OfcLogoRecord> getPrimaryKey() {
		return Keys.OFC_LOGO_PKEY;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<UniqueKey<OfcLogoRecord>> getKeys() {
		return Arrays.<UniqueKey<OfcLogoRecord>>asList(Keys.OFC_LOGO_PKEY);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public OfcLogo as(String alias) {
		return new OfcLogo(alias, this);
	}

	/**
	 * Rename this table
	 */
	public OfcLogo rename(String name) {
		return new OfcLogo(name, null);
	}
}


text:
CLASS({
  name: 'ContactGSnippet',
  package: 'foam.navigator.views',
  extendsModel: 'foam.navigator.views.GSnippet',
  properties: [
    {
      name: 'title',
      lazyFactory: function() { return this.data.title || this.data.email; }
    },
    {
      name: 'snippet',
      defaultValue: '',
    },
    {
      name: 'url',
      lazyFactory: function() {
        return 'https://www.google.com/contacts/u/0/?cplus=0#contact/' + this.data.id.split(':')[1];
      }
    },
    {
      name: 'metadata',
      lazyFactory: function() {
        return [
          this.GSnippetMetadatum.create({ label: 'EMail', text: this.data.email })
        ];
      }
    }
  ]
});


text:
import abc

import numpy as np
from matplotlib.path import Path
from matplotlib.transforms import Transform

from astropy import units as u
from astropy.coordinates import (
    BaseCoordinateFrame, SkyCoord, UnitSphericalRepresentation, frame_transform_graph)

__all__ = ['CurvedTransform', 'CoordinateTransform',
           'World2PixelTransform', 'Pixel2WorldTransform']

class CurvedTransform(Transform, metaclass=abc.ABCMeta):
    """
    Abstract base class for non-affine curved transforms
    """

    input_dims = 2
    output_dims = 2
    is_separable = False

    def transform_path(self, path):
        """
        Transform a Matplotlib Path

        Parameters
        ----------
        path : :class:`~matplotlib.path.Path`
            The path to transform

        Returns
        -------
        path : :class:`~matplotlib.path.Path`
            The resulting path
        """
        return Path(self.transform(path.vertices), path.codes)

    transform_path_non_affine = transform_path

    def transform(self, input):
        raise NotImplementedError("")

    def inverted(self):
        raise NotImplementedError("")

class CoordinateTransform(CurvedTransform):

    has_inverse = True

    def __init__(self, input_system, output_system):
        super().__init__()
        self._input_system_name = input_system
        self._output_system_name = output_system

        if isinstance(self._input_system_name, str):
            frame_cls = frame_transform_graph.lookup_name(self._input_system_name)
            if frame_cls is None:
                raise ValueError(f"Frame {self._input_system_name} not found")
            else:
                self.input_system = frame_cls()
        elif isinstance(self._input_system_name, BaseCoordinateFrame):
            self.input_system = self._input_system_name
        else:
            raise TypeError("input_system should be a WCS instance, string, or a coordinate frame instance")

        if isinstance(self._output_system_name, str):
            frame_cls = frame_transform_graph.lookup_name(self._output_system_name)
            if frame_cls is None:
                raise ValueError(f"Frame {self._output_system_name} not found")
            else:
                self.output_system = frame_cls()

        elif isinstance(self._output_system_name, BaseCoordinateFrame):
            self.output_system = self._output_system_name
        else:
            raise TypeError("output_system should be a WCS instance, string, or a coordinate frame instance")

        if self.output_system == self.input_system:
            self.same_frames = True
        else:
            self.same_frames = False

    @property
    def same_frames(self):
        return self._same_frames

    @same_frames.setter
    def same_frames(self, same_frames):
        self._same_frames = same_frames

    def transform(self, input_coords):
        """
        Transform one set of coordinates to another
        """
        if self.same_frames:
            return input_coords

        input_coords = input_coords*u.deg
        x_in, y_in = input_coords[:, 0], input_coords[:, 1]

        c_in = SkyCoord(UnitSphericalRepresentation(x_in, y_in),
                        frame=self.input_system)

        # We often need to transform arrays that contain NaN values, and filtering
        # out the NaN values would have a performance hit, so instead we just pass
        # on all values and just ignore Numpy warnings
        with np.errstate(all='ignore'):
            c_out = c_in.transform_to(self.output_system)

        lon = c_out.spherical.lon.deg
        lat = c_out.spherical.lat.deg

        return np.concatenate((lon[:, np.newaxis], lat[:, np.newaxis]), axis=1)

    transform_non_affine = transform

    def inverted(self):
        """
        Return the inverse of the transform
        """
        return CoordinateTransform(self._output_system_name, self._input_system_name)

class World2PixelTransform(CurvedTransform, metaclass=abc.ABCMeta):
    """
    Base transformation from world to pixel coordinates
    """

    has_inverse = True
    frame_in = None

    @property
    @abc.abstractmethod
    def input_dims(self):
        """
        The number of input world dimensions
        """

    @abc.abstractmethod
    def transform(self, world):
        """
        Transform world to pixel coordinates. You should pass in a NxM array
        where N is the number of points to transform, and M is the number of
        dimensions. This then returns the (x, y) pixel coordinates
        as a Nx2 array.
        """

    @abc.abstractmethod
    def inverted(self):
        """
        Return the inverse of the transform
        """

class Pixel2WorldTransform(CurvedTransform, metaclass=abc.ABCMeta):
    """
    Base transformation from pixel to world coordinates
    """

    has_inverse = True
    frame_out = None

    @property
    @abc.abstractmethod
    def output_dims(self):
        """
        The number of output world dimensions
        """

    @abc.abstractmethod
    def transform(self, pixel):
        """
        Transform pixel to world coordinates. You should pass in a Nx2 array
        of (x, y) pixel coordinates to transform to world coordinates. This
        will then return an NxM array where M is the number of dimensions.
        """

    @abc.abstractmethod
    def inverted(self):
        """
        Return the inverse of the transform
        """


text:
"""
    Bot functions to generate and post a comments.

    Instructions to file with comments:
        one line - one comment.

    Example:
        lol
        kek

"""
from tqdm import tqdm

def comment(self, media_id, comment_text):
    if self.is_commented(media_id):
        return True
    if not self.reached_limit("comments"):
        if self.blocked_actions["comments"]:
            self.logger.warning("YOUR `COMMENT` ACTION IS BLOCKED")
            if self.blocked_actions_protection:
                from datetime import timedelta

                next_reset = (self.start_time.date() + timedelta(days=1)).strftime(
                    "%Y-%m-%d %H:%M:%S"
                )
                self.logger.warning(
                    (
                        "blocked_actions_protection ACTIVE. "
                        "Skipping `comment` action till, at least, {}."
                    ).format(next_reset)
                )
                return False
        self.delay("comment")
        _r = self.api.comment(media_id, comment_text)
        if _r == "feedback_required":
            self.logger.error("`Comment` action has been BLOCKED...!!!")
            return False
        if _r:
            self.total["comments"] += 1
            return True
    else:
        self.logger.info("Out of comments for today.")
    return False

def reply_to_comment(self, media_id, comment_text, parent_comment_id):
    if not self.is_commented(media_id):
        self.logger.info("Media is not commented yet, nothing to answer to...")
        return False
    if not self.reached_limit("comments"):
        if self.blocked_actions["comments"]:
            self.logger.warning("YOUR `COMMENT` ACTION IS BLOCKED")
            if self.blocked_actions_protection:
                self.logger.warning(
                    "blocked_actions_protection ACTIVE. " "Skipping `comment` action."
                )
                return False
        self.delay("comment")
        media_owner = self.get_media_owner(media_id)
        comment_text = comment_text.replace(
            "[[username]]", self.get_username_from_user_id(media_owner)
        )
        if comment_text[0] != "@":
            msg = (
                "A reply must start with mention, so '@' must be the "
                "1st char, followed by the username you're replying to"
            )
            self.logger.error(msg)
            return False
        if comment_text.split(" ")[0][1:] == self.get_username_from_user_id(
            self.user_id
        ):
            self.logger.error("You can't reply to yourself")
            return False
        _r = self.api.reply_to_comment(media_id, comment_text, parent_comment_id)
        if _r == "feedback_required":
            self.logger.error("`Comment` action has been BLOCKED...!!!")
            return False
        if _r:
            self.logger.info(
                "Replied to comment {} of media {}".format(parent_comment_id, media_id)
            )
            self.total["comments"] += 1
            return True
    else:
        self.logger.info("Out of comments for today.")
    return False

def comment_medias(self, medias):
    broken_items = []
    self.logger.info("Going to comment %d medias." % (len(medias)))
    for media in tqdm(medias):
        if not self.check_media(media):
            continue
        if not self.is_commented(media):
            text = self.get_comment()
            self.logger.info("Commented with text: %s" % text)
            if not self.comment(media, text):
                self.delay("comment")
                broken_items = medias[medias.index(media) :]
                break
    self.logger.info("DONE: Total commented on %d medias. " % self.total["comments"])
    return broken_items

def comment_hashtag(self, hashtag, amount=None):
    self.logger.info("Going to comment medias by %s hashtag" % hashtag)
    medias = self.get_total_hashtag_medias(hashtag, amount)
    return self.comment_medias(medias)

def comment_user(self, user_id, amount=None):
    """ Comments last user_id's medias """
    if not self.check_user(user_id):
        return False
    self.logger.info("Going to comment user_%s's feed:" % user_id)
    user_id = self.convert_to_user_id(user_id)
    medias = self.get_user_medias(user_id, is_comment=True)
    if not medias:
        self.logger.info(
            "None medias received: account is closed or" "medias have been filtered."
        )
        return False
    return self.comment_medias(medias[:amount])

def comment_users(self, user_ids, ncomments=None):
    for user_id in user_ids:
        if self.reached_limit("comments"):
            self.logger.info("Out of comments for today.")
            return
        self.comment_user(user_id, amount=ncomments)

def comment_geotag(self, geotag):
    # TODO: comment every media from geotag
    pass

def is_commented(self, media_id):
    return self.user_id in self.get_media_commenters(media_id)


text:
module Openwsman
  class Transport
      def Transport.auth_request_callback( client, auth_type )
	puts "Transport.auth_request_callback( #{client}, #{auth_type} )"
	puts Transport.auth_name( auth_type )
	puts "#{Transport.auth_name( auth_type )} authentication failed for #{client.host}"
	print "Username:"
	STDOUT.flush
	username = STDIN.gets.chomp
	print "Password:"
	STDOUT.flush
	password = STDIN.gets.chomp
	return [ username, password ]
      end
  end
end


text:
/***********************************************************************/
/*                                                                     */
/*                                OCaml                                */
/*                                                                     */
/*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         */
/*                                                                     */
/*  Copyright 2001 Institut National de Recherche en Informatique et   */
/*  en Automatique.  All rights reserved.  This file is distributed    */
/*  under the terms of the GNU Library General Public License, with    */
/*  the special exception on linking described in file ../LICENSE.     */
/*                                                                     */
/***********************************************************************/

#ifndef CAML_PRINTEXC_H
#define CAML_PRINTEXC_H

#include "misc.h"
#include "mlvalues.h"

#ifdef __cplusplus
extern "C" {
#endif

CAMLextern char * caml_format_exception (value);
void caml_fatal_uncaught_exception (value) Noreturn;

#ifdef __cplusplus
}
#endif

#endif /* CAML_PRINTEXC_H */


text:
import csv
import sys
import os.path
import json

def parse_cad_points_to_json(file, region):
    output_string = ""
    with open(file, 'rb') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            new_row = str(row)
            for ch in [" ","'","[","]"]:
                new_row = new_row.replace(ch,"")
            row_array = new_row.split(",")
            new_array = []
            for x in row_array:
                new_array.append(float(x)/1000)
            output_string += '{"point": ' + str(new_array) + ', "region": "' + region + '"},\n'

    output_string = output_string[:-2]
    return output_string

# def create_json(input1, region1, input2, region2, input3, region3):
def create_json(filename, *arg):
    arg_length = len(arg)
    print arg_length
    if (arg_length > 1) and (arg_length % 2 != 0):
        print "Incorrect number of arguments"
        return
    output_string = "[\n"

    if arg_length == 1:
        output_string += parse_cad_points_to_json(arg[0], "main region")
    else:
        for i in range(arg_length):
            if i % 2 != 0:
                continue
            else:
                output_string += parse_cad_points_to_json(arg[i], arg[i+1])
                output_string += ",\n"

    json_file_name = arg[0].replace(".txt", ".json")
    output_string = output_string[:-2]
    output_string += "\n]"
    print output_string
    print json.loads(output_string)

    write_to_file = open(json_file_name, 'w')
    write_to_file.write(output_string)
    write_to_file.close()

    return json_file_name

if len(sys.argv) > 1:
    json_file = create_json(*sys.argv)
    print json_file + " created"
else:
    print "Booooo-urns"


text:
<?php
namespace backend\controllers;

use common\models\Post;
use common\search\PostSearch;
use Yii;
use backend\components\BackendController;
use yii\web\NotFoundHttpException;

/**
 * Posts controller
 */
class PostsController extends BackendController
{
    /**
     * @inheritDoc
     */
    protected $_rightControlItems = [
        [
            'content' => '<i class="fa fa-plus" aria-hidden="true"></i>',
            'url' => '/posts/edit'
        ]
    ];

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PostSearch();
        $dataProvider = $searchModel->postsList(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Edit existing or create new post
     * @param null|integer $id
     * @return string
     */
    public function actionEdit($id = null) {
        $model = ($id)?$this->loadPost($id):new Post();

        return $this->render(($id)?'update':'create',[
           'model' => $model
        ]);
    }

    /**
     * Search Post model by id
     * @param $id
     * @return Post
     * @throws NotFoundHttpException
     */
    private function loadPost($id) {
        $model = Post::findOne($id);
        if($model === null)
            throw new NotFoundHttpException(Yii::t('app','Post with that id not found in system'));

        return $model;
    }
}


text:
package org.knowm.xchange.bittrex.dto.marketdata;

import java.util.Arrays;

import com.fasterxml.jackson.annotation.JsonProperty;

public class BittrexTradesResponse {

  private final boolean success;
  private final String message;
  private final BittrexTrade[] trades;

  public BittrexTradesResponse(@JsonProperty("success") boolean success, @JsonProperty("message") String message,
      @JsonProperty("result") BittrexTrade[] trades) {

    super();
    this.success = success;
    this.message = message;
    this.trades = trades;
  }

  public boolean getSuccess() {

    return success;
  }

  public String getMessage() {

    return message;
  }

  public BittrexTrade[] getTrades() {

    return trades;
  }

  @Override
  public String toString() {

    return "BittrexTickerResponse [success=" + success + ", message=" + message + ", trades=" + Arrays.toString(trades) + "]";
  }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.gis.db.models.fields

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Position',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('point', django.contrib.gis.db.models.fields.PointField(srid=4326)),
                ('created_date', models.DateTimeField()),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
'''
Problem from
https://code.google.com/codejam/contest/6224486/dashboard
It\'s opening night at the opera, and your friend is the prima donna (the lead female singer). You will not be in the audience, but you want to make sure she receives a standing ovation -- with every audience member standing up and clapping their hands for her.
Initially, the entire audience is seated. Everyone in the audience has a shyness level. An audience member with shyness level Si will wait until at least Si other audience members have already stood up to clap, and if so, she will immediately stand up and clap. If Si = 0, then the audience member will always stand up and clap immediately, regardless of what anyone else does. For example, an audience member with Si = 2 will be seated at the beginning, but will stand up to clap later after she sees at least two other people standing and clapping.
You know the shyness level of everyone in the audience, and you are prepared to invite additional friends of the prima donna to be in the audience to ensure that everyone in the crowd stands up and claps in the end. Each of these friends may have any shyness value that you wish, not necessarily the same. What is the minimum number of friends that you need to invite to guarantee a standing ovation?
Input
4
4 11111
1 09
5 110011
0 1
'''

def solution(n, numbers)
  i = 0
  sum = 0
  while (i < n)
    sum += numbers[i]
    i += 1
  end
  f = n - sum
  if (f < 0)
    f = 0
  end
  return f
end

def main()
  t = gets.to_i
  i = 0
  while (i < t) do
    tmp = gets
    n, tmp  = tmp.split(' ')
    n = n.to_i
    numbers = []
    for e in 0..tmp.length
      numbers.push(tmp[e].to_i)
    end
    f = solution(n, numbers)
    puts("Case #"+(i+1).to_s+": "+f.to_s)
    i += 1
  end
end

main()


text:
module Yandex::Direct
  class ActionResult
    include ActiveModel::Model
    attr_accessor :Id, :Warnings, :Errors
    def initialize(*args)
      super
      self.Warnings = Array(self.Warnings).map{|attributes| ExceptionNotification.new(attributes)}
      self.Errors = Array(self.Errors).map{|attributes| ExceptionNotification.new(attributes)}
    end
    def errors?
      Array(self.Errors).compact.any?
    end
    def warnings?
      Array(self.Warnings).compact.any?
    end
  end
end


text:
namespace policy {

class DeviceCommandSetVolumeJob : public RemoteCommandJob {
 public:
  DeviceCommandSetVolumeJob();

  DeviceCommandSetVolumeJob(const DeviceCommandSetVolumeJob&) = delete;
  DeviceCommandSetVolumeJob& operator=(const DeviceCommandSetVolumeJob&) =
      delete;

  ~DeviceCommandSetVolumeJob() override;

  // RemoteCommandJob:
  enterprise_management::RemoteCommand_Type GetType() const override;

 protected:
  // RemoteCommandJob:
  bool ParseCommandPayload(const std::string& command_payload) override;
  void RunImpl(CallbackWithResult succeeded_callback,
               CallbackWithResult failed_callback) override;

 private:
  // New volume level to be set, value in range [0,100].
  int volume_;
};

}  // namespace policy

#endif  // CHROME_BROWSER_ASH_POLICY_REMOTE_COMMANDS_DEVICE_COMMAND_SET_VOLUME_JOB_H_


text:
<!DOCTYPE html>
<html>
<title>Service Workers: Origin Relativity</title>
    <head>
        <link rel="help" href="https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#origin-relativity">
        <script src="/resources/testharness.js"></script>
        <script src="/resources/testharnessreport.js"></script>

    </head>
    <body>

<!--

One of the advanced concerns that major applications would encounter is whether
they can be hosted from a CDN. By definition, these are servers in other
places, often on other domains. Therefore, Service Workers cannot be hosted on
CDNs. But they can include resources via [importScripts()][1]. The reason for
this restriction is that Service Workers create the opportunity for a bad actor
to turn a bad day into a bad eternity.

[1]: http://goo.gl/Owcfs2

-->

    <script>
        test(function() {
            // not_implemented();
        }, "There are no tests for section Origin Relativity so far.");
    </script>

    </body>
</html>


text:
'use strict';

const virtualModule = require('../module').virtual;

// Transformed modules have the form
//   __d(function(require, module, global, exports, dependencyMap) {
//       /* code */
//   });
//
// This function adds the numeric module ID, and an array with dependencies of
// the dependencies of the module before the closing parenthesis.
exports.addModuleIdsToModuleWrapper = (
module,
idForPath) =>
{const
  dependencies = module.dependencies,file = module.file;const
  code = file.code;
  const index = code.lastIndexOf(')');

  // calling `idForPath` on the module itself first gives us a lower module id
  // for the file itself than for its dependencies. That reflects their order
  // in the bundle.
  const fileId = idForPath(file);

  // This code runs for both development and production builds, after
  // minification. That's why we leave out all spaces.
  const depencyIds =
  dependencies.length ? `,[${dependencies.map(idForPath).join(',')}]` : '';
  return (
    code.slice(0, index) +
    `,${fileId}` +
    depencyIds +
    code.slice(index));

};

exports.concat = function* concat()

{for (var _len = arguments.length, iterables = Array(_len), _key = 0; _key < _len; _key++) {iterables[_key] = arguments[_key];}
  for (const it of iterables) {
    yield* it;
  }
};

// Creates an idempotent function that returns numeric IDs for objects based
// on their `path` property.
exports.createIdForPathFn = () => {
  const seen = new Map();
  let next = 0;
  return (_ref) => {let path = _ref.path;
    let id = seen.get(path);
    if (id == null) {
      id = next++;
      seen.set(path, id);
    }
    return id;
  };
};

// creates a series of virtual modules with require calls to the passed-in
// modules.
exports.requireCallsTo = function* (
modules,
idForPath)
{
  for (const module of modules) {
    yield virtualModule(`require(${idForPath(module.file)});`);
  }
};


text:
class SkBitmap;

class MockStatusIconObserver : public StatusIcon::Observer {
 public:
  MOCK_METHOD0(OnClicked, void());
};

TEST(StatusTrayWinTest, CreateTray) {
  // Just tests creation/destruction.
  StatusTrayWin tray;
}

TEST(StatusTrayWinTest, CreateIconAndMenu) {
  // Create an icon, set the images, tooltip, and context menu, then shut it
  // down.
  StatusTrayWin tray;
  StatusIcon* icon = tray.CreateStatusIcon();
  SkBitmap* bitmap = ui::ResourceBundle::GetSharedInstance().GetBitmapNamed(
      IDR_STATUS_TRAY_ICON);
  icon->SetImage(*bitmap);
  icon->SetPressedImage(*bitmap);
  icon->SetToolTip(ASCIIToUTF16("tool tip"));
  ui::SimpleMenuModel* menu = new ui::SimpleMenuModel(NULL);
  menu->AddItem(0, L"foo");
  icon->SetContextMenu(menu);
}

TEST(StatusTrayWinTest, ClickOnIcon) {
  // Create an icon, send a fake click event, make sure observer is called.
  StatusTrayWin tray;
  StatusIconWin* icon = static_cast<StatusIconWin*>(tray.CreateStatusIcon());
  MockStatusIconObserver observer;
  icon->AddObserver(&observer);
  EXPECT_CALL(observer, OnClicked());
  // Mimic a click.
  tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_LBUTTONDOWN);
  // Mimic a right-click - observer should not be called.
  tray.WndProc(NULL, icon->message_id(), icon->icon_id(), WM_RBUTTONDOWN);
  icon->RemoveObserver(&observer);
}


text:
package business

import (
	"backend/common"
	req "backend/common/request"
	"backend/domain"
	"backend/errors"
	"backend/storage"
	"fmt"
	log "github.com/cihub/seelog"
	"strings"
	"time"
)

func CreateDataset(projectId string, data map[string]interface{}, ctx *req.RequestContext) (*domain.Dataset, *errors.Error) {
	datasetId := common.UniqueId()

	name, ok := data["name"].(string)
	if !ok || name == "" {
		return nil, errors.New("ErrBadRequest", "name", "name was empty or not a valid string.")
	}

	if !domain.IsValidDatasetName(name) {
		return nil, errors.New("ErrBadRequest", "name not valid", "name was not valid (cannot start with numbers).")
	}
	datasetType, ok := data["type"].(string)
	if ok {
		if datasetType != "" && datasetType != "fact" && datasetType != "dimension" {
			return nil, errors.New("ErrBadRequest", "datasetType not valid", "datasetType was not valid (must be either 'fact' or 'dimension').")
		}
	}
	if datasetType == "" {
		datasetType = "fact"
	}
	updateMode, ok := data["updateMode"].(string)
	if ok {
		if updateMode != "" && updateMode != "append" && updateMode != "upsert" {
			return nil, errors.New("ErrBadRequest", "updateMode not valid", "updateMode was not valid (must be either 'append' or 'upsert').")
		}
	}

	ns, ok := data["namespace"].(string)
	if !ok {
		return nil, errors.New("ErrBadRequest", "namespace not valid", "namespace was empty or not string")
	}
	namespace, err := CreateNamespace(projectId, map[string]interface{}{"name": ns}, ctx)
	if err != nil && err.Code != "ErrNamespaceExists" {
		return nil, err
	}
	log.Tracef("business.CreateDataset: namespace=%s", common.ToJson(namespace))
	var cols []interface{}
	var columns []*domain.Column
	if data["columns"] != nil {
		cols, ok = data["columns"].([]interface{})
		if !ok {
			return nil, errors.New("ErrBadRequest", "columns", "columns not a valid array.")
		}
		columns = make([]*domain.Column, len(cols))
		for i, j := range cols {
			colMap, ok := j.(map[string]interface{})
			if !ok {
				return nil, errors.New("ErrBadRequest", "Column definition not map[string]interface{}", fmt.Sprintf("Column definition not valid (array index %d)", i))
			}
			name, ok := colMap["name"].(string)
			if !ok {
				return nil, errors.New("ErrBadRequest", "Column name not string", fmt.Sprintf("Column name not string (array index %d)", i))
			}
			dataType, ok := colMap["dataType"].(string)
			if !ok {
				return nil, errors.New("ErrBadRequest", "Column dataType not string", fmt.Sprintf("Column dataType not string (array index %d)", i))
			}
			def, _ := colMap["default"].(string)
			columns[i] = &domain.Column{Name: name, DataType: dataType, Default: def}
		}

	}

	primaryKey, pkOk := data["primaryKey"].(string)
	if !pkOk {
		return nil, errors.New("ErrBadRequest", "primaryKey", "primaryKey was not valid or not string")
	}
	pk := strings.Split(primaryKey, ",")
	if datasetType == "dimension" && len(pk) > 1 {
		return nil, errors.New("ErrBadRequest", "primaryKey", "primaryKey must be single column for dimensions")

	}
	dateColumn, dateColOk := data["dateColumn"].(string)
	if !dateColOk {
		return nil, errors.New("ErrBadRequest", "need dateColumn", "dateColumn was not valid or not string")
	}
	/*	if !pkOk && !dateColOk {
			dateColumn = name + "_" + common.UniqueId()
			primaryKey = dateColumn
			columns = append(columns, &domain.Column{Name: dateColumn, DataType: "date", Default: "now()"})
		} else if !pkOk {
			primaryKey = dateColumn
		} else if !dateColOk {
			dateColumn = name + "_" + common.UniqueId()
			columns = append(columns, &domain.Column{Name: dateColumn, DataType: "date", Default: "now()"})
		}*/

	columns = append(columns, &domain.Column{Name: "__created", DataType: "datetime", Default: "now()"})
	dataset, err := storage.FindDatasetByName(ns, name, projectId, ctx)
	if dataset != nil {
		return nil, errors.New("ErrDatasetExists", name, "Dataset already exists")
	}

	if err != nil && err.Code != "ErrDatasetNotFound" {
		return nil, err
	}

	created := time.Now()
	dataset = &domain.Dataset{DatasetId: datasetId, Type: datasetType, ProjectId: projectId, Name: name, NamespaceId: namespace.NamespaceId, Namespace: namespace, NamespaceName: namespace.Name, Columns: columns, PrimaryKey: primaryKey, Created: created, Updated: created, DateColumn: dateColumn, UpdateMode: updateMode}
	err = storage.CreateDataset(dataset, ctx)
	if err != nil {
		return nil, err
	}

	return dataset, err
}

func DeleteDataset(datasetId string, ctx *req.RequestContext) *errors.Error {
	dataset, err := storage.FindDatasetById(datasetId, ctx)
	if err != nil {
		return err
	}

	err = storage.DeleteDataset(dataset, ctx)
	if err != nil {
		return err
	}

	return err
}

func TruncateDataset(dataset *domain.Dataset, ctx *req.RequestContext) *errors.Error {
	log.Tracef("TruncateDataset1, Cols: %s %s", dataset.DateColumn, dataset.Columns)
	err := storage.DeleteDataset(dataset, ctx)
	if err != nil {
		return err
	}

	log.Tracef("TruncateDataset2, Cols: %s %s", dataset.DateColumn, dataset.Columns)
	err = storage.CreateDataset(dataset, ctx)
	if err != nil {
		return err
	}

	return nil
}


text:
package com.hazelcast.spi.exception;

import com.hazelcast.nio.Address;

/**
 * A {@link RetryableHazelcastException} that indicates that an operation was sent by a machine which isn't member
 * in the cluster when the operation is executed.
 */
public class CallerNotMemberException extends RetryableHazelcastException {

    public CallerNotMemberException(Address thisAddress, Address caller, int partitionId,
            String operationName, String serviceName) {
        super("Not Member! this: " + thisAddress + ", caller: " + caller + ", partitionId: " + partitionId
                + ", operation: " + operationName + ", service: " + serviceName);
    }

    public CallerNotMemberException(String message) {
        super(message);
    }
}


text:
module Text.CSL
    ( -- * Introduction
      -- $intro

      -- * Overview: A Simple Example
      -- $overview

      -- * Reading Bibliographic Databases
      readBiblioFile
    , BibFormat (..)
    , readBiblioString

    -- ** Reference Representation
    , Reference (..)
    , getReference
    , setNearNote

    -- * CSL Parser, Representation, and Processing
    , readCSLFile
    , parseCSL
    , parseCSL'
    , localizeCSL

    -- ** The Style Types
    , Style (..)
    , Citation (..)
    , Bibliography (..)
    , Cite (..)
    , Abbreviations (..)
    , emptyCite

    -- ** High Level Processing
    , ProcOpts (..)
    , procOpts
    , BibOpts (..)
    , citeproc
    , processCitations
    , processBibliography
    , BiblioData (..)

    -- * The output and the rendering functions
    , renderPlain
    , renderPandoc
    , renderPandoc'
    ) where

import Text.CSL.Proc
import Text.CSL.Reference
import Text.CSL.Style
import Text.CSL.Parser
import Text.CSL.Input.Bibutils
import Text.CSL.Output.Pandoc
import Text.CSL.Output.Plain

-- $intro
--
-- /citeproc-hs/ provides functions for reading bibliographic
-- databases, for reading and parsing CSL files and for generating
-- citations in an internal format, 'Formatted', that can be
-- easily rendered into different final formats. At the present time
-- only 'Pandoc' and plain text rendering functions are provided by
-- the library.
--
-- The library also provides a wrapper around hs-bibutils, the Haskell
-- bindings to Chris Putnam's bibutils, a library that interconverts
-- between various bibliography formats using a common MODS-format XML
-- intermediate. For more information about hs-bibutils see here:
-- <http://hackage.haskell.org/package/hs-bibutils>.
--
-- /citeproc-hs/ can natively read MODS and JSON formatted
-- bibliographic databases. The JSON format is only partially
-- documented. It is used by citeproc-js, by the CSL processor
-- test-suite and is derived by the CSL scheme. More information can
-- be read here:
-- <http://citationstyles.org/>.
--
-- A (git) repository of styles can be found here:
-- <https://github.com/citation-style-language/styles>.

-- $overview
--
-- The following example assumes you have installed citeproc-hs with
-- hs-bibutils support (which is the default).
--
-- Suppose you have a small bibliographic database, like this one:
--
-- > @Book{Rossato2006,
-- > author="Andrea Rossato",
-- > title="My Second Book",
-- > year="2006"
-- > }
-- >
-- > @Book{Caso2007,
-- > author="Roberto Caso",
-- > title="Roberto's Book",
-- > year="2007"
-- > }
--
-- Save it as @mybibdb.bib@.
--
-- Then you can grab one of the CSL styles that come with the
-- test-suite for CSL processors. Suppose this one:
--
-- <https://bitbucket.org/bdarcus/citeproc-test/raw/18141149d1d3/styles/apa-x.csl>
--
-- saved locally as @apa-x.csl@.
--
-- This would be a simple program that formats a list of citations
-- according to that style:
--
-- > import Text.CSL
-- >
-- > cites :: [Cite]
-- > cites = [emptyCite { citeId = "Caso2007"
-- >                    , citeLabel = "page"
-- >                    , citeLocator = "15"}
-- >         ,emptyCite { citeId = "Rossato2006"
-- >                    , citeLabel = "page"
-- >                    , citeLocator = "10"}
-- >         ]
-- >
-- > main :: IO ()
-- > main = do
-- >   m <- readBiblioFile "mybibdb.bib"
-- >   s <- readCSLFile Nothing "apa-x.csl"
-- >   let result = citeproc procOpts s m $ [cites]
-- >   putStrLn . unlines . map renderPlain . citations $ result
--
-- The result would be:
--
-- > (Caso, 2007, p. 15; Rossato, 2006, p. 10)


text:
import sys

class MuninGraph(object):

    def run(self):
        cmd_name = None
        if len(sys.argv) > 1:
            cmd_name = sys.argv[1]
        if cmd_name == 'config':
            self.print_config()
        else:
            metrics = self.calculate_metrics()
            self.print_metrics(metrics)

    def print_config(self):
        for key,value in self.graph_config.items():
            print '%s %s' % (key, value)

    def print_metrics(self, metrics):
        for key, value in metrics.items():
            print '%s.value %s' % (key, value)


text:
beego-blog
==========

wooya's blog use beego framework (forked form UlricQin's beego-blog.)

## install

```
cd $GOPATH/src/
git clone https://github.com/doomsplayer/beego-blog.git
cd beego-blog && modify conf/{app.conf,app.toml}
bee run
```

## admin

```
url: /me
username: set in the app.toml
password: set in the app.toml
```


text:
package com.intellij.xml;

import com.intellij.testFramework.fixtures.CodeInsightTestUtil;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.xml.refactoring.SchemaPrefixRenameHandler;

/**
 * @author Konstantin Bulenkov
 */
public class XmlSchemaPrefixTest extends LightCodeInsightFixtureTestCase {

  public void testPrefixUsages() {
    doFindUsages("usages.xml", 16);
    doFindUsages("usages1.xml", 16);
  }

  public void testRename() {doRename();}
  public void testRename1() {doRename();}

  public void testRename2() {doRename();}
  public void testRenameFromClosingTag() {doRename();}

  private void doRename() {
    doRename("xsd");
  }

  private void doRename(String newValue) {
    final String name = getTestName(true);
    CodeInsightTestUtil.doInlineRenameTest(new SchemaPrefixRenameHandler(), name, "xml", newValue, myFixture);
  }

  @Override
  protected String getBasePath() {
    return "/xml/tests/testData/schemaPrefix";
  }

  protected void doFindUsages(String filename, int usages) {
    assertSize(usages, myFixture.testFindUsages(filename));
  }

}


text: export { PauseFilled16 as default } from "../../";


text:
package com.intellij.codeInsight.completion;

import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.lang.xhtml.XHTMLLanguage;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.patterns.XmlPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import com.intellij.psi.html.HtmlTag;
import com.intellij.psi.impl.source.html.dtd.HtmlElementDescriptorImpl;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ProcessingContext;
import com.intellij.xml.util.HtmlUtil;
import com.intellij.xml.util.XmlUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import static com.intellij.html.impl.util.MicrodataUtil.*;
import static com.intellij.patterns.PlatformPatterns.psiElement;

public class HtmlCompletionContributor extends CompletionContributor {
  public HtmlCompletionContributor() {
    extend(CompletionType.BASIC, psiElement().inside(XmlPatterns.xmlAttributeValue()), new CompletionProvider<CompletionParameters>() {
      @Override
      protected void addCompletions(@NotNull CompletionParameters parameters,
                                    ProcessingContext context,
                                    @NotNull CompletionResultSet result) {
        final PsiElement position = parameters.getPosition();
        if (!hasHtmlAttributesCompletion(position)) {
          return;
        }
        final XmlAttributeValue attributeValue = PsiTreeUtil.getParentOfType(position, XmlAttributeValue.class, false);
        if (attributeValue != null && attributeValue.getParent() instanceof XmlAttribute) {
          for (String element : addSpecificCompletions((XmlAttribute)attributeValue.getParent())) {
            result.addElement(LookupElementBuilder.create(element));
          }
        }
      }
    });
  }

  public static boolean hasHtmlAttributesCompletion(PsiElement position) {
    if (PsiTreeUtil.getParentOfType(position, HtmlTag.class, false) != null) {
      return true;
    }
    XmlTag xmlTag = PsiTreeUtil.getParentOfType(position, XmlTag.class, false);
    return xmlTag != null && xmlTag.getLanguage() == XHTMLLanguage.INSTANCE;
  }

  @NotNull
  @NonNls
  protected static String[] addSpecificCompletions(final XmlAttribute attribute) {
    @NonNls String name = attribute.getName();
    final XmlTag tag = attribute.getParent();
    if (tag == null) return ArrayUtil.EMPTY_STRING_ARRAY;

    @NonNls String tagName = tag.getName();
    if (tag.getDescriptor() instanceof HtmlElementDescriptorImpl) {
      name = name.toLowerCase();
      tagName = tagName.toLowerCase();
    }

    final String namespace = tag.getNamespace();
    if (XmlUtil.XHTML_URI.equals(namespace) || XmlUtil.HTML_URI.equals(namespace)) {

      if ("target".equals(name)) {
        return new String[]{"_blank", "_top", "_self", "_parent"};
      }
      else if ("enctype".equals(name)) {
        return new String[]{"multipart/form-data", "application/x-www-form-urlencoded"};
      }
      else if ("rel".equals(name) || "rev".equals(name)) {
        return new String[]{"alternate", "author", "bookmark", "help", "icon", "license", "next", "nofollow",
          "noreferrer", "prefetch", "prev", "search", "stylesheet", "tag", "start", "contents", "index",
          "glossary", "copyright", "chapter", "section", "subsection", "appendix", "script", "import",
          "apple-touch-icon", "apple-touch-icon-precomposed", "apple-touch-startup-image"};
      }
      else if ("media".equals(name)) {
        return new String[]{ "all", "braille", "embossed", "handheld", "print", "projection", "screen", "speech", "tty", "tv" };
      }
      else if ("language".equals(name)) {
        return new String[]{"JavaScript", "VBScript", "JScript", "JavaScript1.2", "JavaScript1.3", "JavaScript1.4", "JavaScript1.5"};
      }
      else if ("type".equals(name) && "link".equals(tagName)) {
        return new String[]{"text/css", "text/html", "text/plain", "text/xml"};
      }
      else if ("http-equiv".equals(name) && "meta".equals(tagName)) {
        return HtmlUtil.RFC2616_HEADERS;
      }
      else if("content".equals(name) && "meta".equals(tagName) && tag.getAttribute("name") == null) {
        return HtmlUtil.CONTENT_TYPES;
      }
      else if ("accept".equals(name) && "input".equals(tagName)) {
        return HtmlUtil.CONTENT_TYPES;
      }
      else if("accept-charset".equals(name) || "charset".equals(name)) {
        Charset[] charSets = CharsetToolkit.getAvailableCharsets();
        String[] names = new String[charSets.length];
        for (int i = 0; i < names.length; i++) {
          names[i] = charSets[i].toString();
        }
        return names;
      } else if ("itemprop".equals(name)) {
        XmlTag scopeTag = findScopeTag(tag);
        return scopeTag != null ? findItemProperties(scopeTag) : ArrayUtil.EMPTY_STRING_ARRAY;
      }
    }

    return ArrayUtil.EMPTY_STRING_ARRAY;
  }

  private static String[] findItemProperties(@NotNull XmlTag tag) {
    final XmlAttribute typeAttribute = tag.getAttribute(ITEM_TYPE);
    if (typeAttribute != null) {
      final XmlAttributeValue valueElement = typeAttribute.getValueElement();
      final PsiReference[] references = valueElement != null ? valueElement.getReferences() : PsiReference.EMPTY_ARRAY;
      List<String> result = new ArrayList<>();
      for (PsiReference reference : references) {
        final PsiElement target = reference != null ? reference.resolve() : null;
        if (target instanceof PsiFile) {
          result.addAll(extractProperties((PsiFile)target, StringUtil.unquoteString(reference.getCanonicalText())));
        }
      }
      return ArrayUtil.toStringArray(result);
    }
    return ArrayUtil.EMPTY_STRING_ARRAY;
  }

}


text:
package cz.kamenitxan.jakon.validation.validators;

import cz.kamenitxan.jakon.validation.ValidatedBy;
import cz.kamenitxan.jakon.webui.entity.MessageSeverity;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * The string has to be a well-formed email address. Exact semantics of what makes up a valid
 * email address are left to Bean Validation providers. Accepts {@code String}.
 */
@Target({FIELD})
@Retention(RUNTIME)
@ValidatedBy(EmailValidator.class)
public @interface Email {
	MessageSeverity severity() default MessageSeverity.ERROR;
	/** Validator will emit warnings for possible typos and will provide suggested correction (e.g.: @gnail.com -> @gmail.com) */
	boolean suggestions() default true;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>SqlServer - FAKE - F# Make</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">

    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">

    <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />

fsharp.org

github page

FAKE - F# Make

SqlServer

Nested types and modules

Type	Description

            ServerInfo

Functions and values

Function or value	Description

            Attach serverInfo attachOptions files

            Signature:serverInfo:ServerInfo -> attachOptions:AttachOptions -> files:seq<string> -> ServerInfo

Attach a database

            Go to GitHub source

            CreateDb serverInfo

            Signature:serverInfo:ServerInfo -> ServerInfo

Creates a new db on the given server

            Go to GitHub source

            Detach serverInfo

            Signature:serverInfo:ServerInfo -> ServerInfo

Detaches a database

            Go to GitHub source

            Disconnect serverInfo

            Signature:serverInfo:ServerInfo -> unit

Closes the connection to the server

            Go to GitHub source

            DropAndCreateDatabase connectionString

            Signature:connectionString:string -> unit

Drops and creates the database (dropped if db exists. created nonetheless)

            Go to GitHub source

            DropDb serverInfo

            Signature:serverInfo:ServerInfo -> ServerInfo

Drops the given InitialCatalog from the server (if it exists)

            Go to GitHub source

            existDBOnServer serverInfo dbName

            Signature:serverInfo:ServerInfo -> dbName:string -> bool

Checks whether the given Database exists on the server

            Go to GitHub source

            getDatabase serverInfo

            Signature:serverInfo:ServerInfo -> Database

Gets the initial catalog as database instance

            Go to GitHub source

            getDatabaseNamesFromServer serverInfo

            Signature:serverInfo:ServerInfo -> seq<string>

gets the DatabaseNames from the server

            Go to GitHub source

            getDatabasesFromServer serverInfo

            Signature:serverInfo:ServerInfo -> seq<Database>

gets the DatabaseNames from the server

            Go to GitHub source

            getDBName serverInfo

            Signature:serverInfo:ServerInfo -> string

Gets the initial catalog name

            Go to GitHub source

            getServerInfo connectionString

            Signature:connectionString:string -> ServerInfo

Gets a connection to the SQL server and an instance to the ConnectionStringBuilder

            Go to GitHub source

            getServerName serverInfo

            Signature:serverInfo:ServerInfo -> string

Gets the name of the server

            Go to GitHub source

            intitialCatalogExistsOnServer serverInfo

            Signature:serverInfo:ServerInfo -> bool

Checks whether the given InitialCatalog exists on the server

            Go to GitHub source

            KillAllProcesses serverInfo

            Signature:serverInfo:ServerInfo -> ServerInfo

Kills all processes with the given server info

            Go to GitHub source

            ReplaceDatabaseFiles (...)

            Signature:connectionString:string -> targetDir:string -> files:seq<string> -> attachOptions:AttachOptions -> unit

Replaces the database files

            Go to GitHub source

            ReplaceDatabaseFilesWithCache (...)

            Signature:connectionString:string -> targetDir:string -> cacheDir:string -> files:seq<string> -> attachOptions:AttachOptions -> unit

Replaces the database files from a cache.
 If the files in the cache are not up to date, they will be refreshed.

            Go to GitHub source

            runScript serverInfo sqlFile

            Signature:serverInfo:ServerInfo -> sqlFile:string -> unit

Runs a sql script on the server.

            Go to GitHub source

            RunScripts connectionString scripts

            Signature:connectionString:string -> scripts:seq<string> -> unit

Runs the given sql scripts on the server.

            Go to GitHub source

            RunScriptsFromDirectory (...)

            Signature:connectionString:string -> scriptDirectory:string -> unit

Runs all sql scripts from the given directory on the server.

            Go to GitHub source

FAKE - F# Make

Home page

Get FAKE via NuGet

Source Code on GitHub

License (MS-PL)

Who is using FAKE?

Release Notes

Contributing to FAKE

Ask a question

Articles

Getting started

NuGet package restore

Using FxCop in a build

Generating AssemblyInfo

Create NuGet packages

Running specific targets

Running FAKE from command line

Creating custom tasks

TeamCity integration

Running canopy tests

Octopus Deploy

TypeScript support

Fake.Deploy

Documentation

API Reference


text:
try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup
import eutester

setup(name="eutester",
      version=eutester.__version__,
      description="Test Framework and utilities for AWS compatible clouds",
      long_description="Test Framework and utilities for AWS compatible clouds",
      url="https://github.com/eucalyptus/eutester",
      install_requires=['paramiko >= 1.7',
                        'boto >= 2.5.2',
                        'jinja2 >= 2.7',
                        'argparse',
                        'futures',
                        'python-dateutil',
                        'mock',
                        'dnspython',
                        'pywinrm',
                        'BeautifulSoup',
                        'requests >= 1'],
      packages=find_packages(),
      package_data={'testcases.cloud_admin.riak_cs.templates': ['*.template']},
      license='BSD (Simplified)',
      platforms='Posix; MacOS X; Windows',
      classifiers=['Development Status :: 3 - Alpha',
                   'Intended Audience :: System Administrators',
                   'License :: OSI Approved :: BSD License',
                   'Operating System :: OS Independent',
                   'Topic :: System :: Systems Administration'],
      )


text:
package websocket.models.requests;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import websocket.IRequestSendErrorHandler;
import websocket.IResponseHandler;
import websocket.models.IRequestData;
import websocket.models.Request;

/**
 * Created by loganga on 5/9/2016
 */
public class ProjectUnsubscribeRequest implements IRequestData {

    @JsonProperty("ProjectID")
    protected long projectID;

    public ProjectUnsubscribeRequest(long projectID) {
        this.projectID = projectID;
    }

    @JsonIgnore
    @Override
    public Request getRequest(IResponseHandler responseHandler, IRequestSendErrorHandler requestSendErrorHandler) {
        return new Request("Project", "Unsubscribe", this, responseHandler, requestSendErrorHandler);
    }
}


text:
public class Test {
    private String myStr;

    public String getMyStr() {
        return myStr;
    }

    void foo() {
        new Runnable(){
            @Override
            public void run() {
                  System.out.println(<selection>myStr</selection>);
            }
        };
    }
}

class X {
   public void n() {
       new Test().foo();
   }
}


text:
Fraction Matcher
=============
"Fraction Matcher" is an educational simulation in HTML5, by PhET Interactive Simulations
at the University of Colorado Boulder.
For a description of this simulation, associated resources, and a link to the published version,
visit the simulation's web page.

### Try it!

Click here to run "Fraction Matcher".

### Documentation
The PhET Development Overview is the most complete guide to PhET Simulation
Development. This guide includes how to obtain simulation code and its dependencies, notes about architecture & design, how to test and build
the sims, as well as other important information.

### Quick Start
(1) Clone the simulation and its dependencies:
```
git clone https://github.com/phetsims/assert.git
git clone https://github.com/phetsims/axon.git
git clone https://github.com/phetsims/babel.git
git clone https://github.com/phetsims/brand.git
git clone https://github.com/phetsims/chipper.git
git clone https://github.com/phetsims/dot.git
git clone https://github.com/phetsims/fraction-matcher.git
git clone https://github.com/phetsims/fractions-common.git
git clone https://github.com/phetsims/joist.git
git clone https://github.com/phetsims/kite.git
git clone https://github.com/phetsims/perennial.git perennial-alias
git clone https://github.com/phetsims/phet-core.git
git clone https://github.com/phetsims/phetcommon.git
git clone https://github.com/phetsims/phetmarks.git
git clone https://github.com/phetsims/query-string-machine.git
git clone https://github.com/phetsims/scenery.git
git clone https://github.com/phetsims/scenery-phet.git
git clone https://github.com/phetsims/sherpa.git
git clone https://github.com/phetsims/sun.git
git clone https://github.com/phetsims/tambo.git
git clone https://github.com/phetsims/tandem.git
git clone https://github.com/phetsims/twixt.git
git clone https://github.com/phetsims/utterance-queue.git
git clone https://github.com/phetsims/vegas.git
```

(2) Install dev dependencies:
```
cd chipper
npm install
cd ../perennial-alias
npm install
cd ../fraction-matcher
npm install
```

(3) Change directory to chipper `cd ../chipper/`, then transpile the code to JavaScript by running `node js/scripts/transpile.js --watch`. This starts a file-watching process
that will automatically transpile new or changed files.

(4) In a new terminal/command prompt, start an http-server

(5) Open in the browser: `http://localhost/fraction-matcher/fraction-matcher_en.html` (You will probably need to modify this URL based on your HTTP port and relative path.)

#### Optional: Build the simulation into a single file

(1) Change directory to the simulation directory: `cd ../fraction-matcher`

(2) Build the sim: `grunt --brands=adapted-from-phet`. It is safe to ignore warnings like `>> WARNING404: Skipping potentially non-public dependency`,
which indicate that non-public PhET-iO code is not being included in the build.

(3) Open in the browser: `http://localhost/fraction-matcher/build/adapted-from-phet/fraction-matcher_en_adapted-from-phet.html` (You will probably need to modify this URL based on your HTTP port and relative path.)

### Get Involved

Contact us at our Google Group: Developing Interactive Simulations in HTML5

Help us improve, create a New Issue

### License
See the LICENSE


text:
local App = {}

local DEFAULT_WINDOW = {
    screenWidth = MOAIEnvironment.horizontalResolution or 640,
    screenHeight = MOAIEnvironment.verticalResolution or 960,
    viewWidth = 320,
    viewHeight = 480,
    scaleMode = "best_fit", -- "best_fit", "letterbox", "manual"
    viewOffset = {0, 0},
}

---
-- Most common resolutions for mobile devices
-- Keys are resolution of longer side in pixels, values are view coordinates
-- Tried to keep view coords close to 320x480 and maintain
-- integer ratio at the same time
local appleResolutions = {
    -- apple
    [480]  = {480, 320}, -- 480x320
    [960]  = {480, 320}, -- 960x640
    [1136] = {568, 320}, -- 1136x640
    [1024] = {512, 384}, -- 1024x768
    [2048] = {512, 384}, -- 2048x1536
}

local androidResolutions = {
    -- use standard fallback for all androids
    -- { [320]   = {480, 360} }, -- 320x240
    -- { [400]   = {532, 320} }, -- 400x240
    -- { [640]   = {568, 320} }, -- 640x360
    -- { [800]   = {532, 320} }, -- 800x480
    -- { [854]   = {568, 320} }, -- 854x480
    -- { [960]   = {568, 320} }, -- 960x540
    -- { [1280]  = {640, 360} }, -- 1280x720
    -- { [1920]  = {568, 320} }, -- 1920x1080
}

local mobileResolutions = MOAIAppIOS and appleResolutions or androidResolutions

---
-- Create moai window
-- @param title
-- @param windowParams table with parameters
function App:openWindow(title, windowParams)
    windowParams = windowParams or DEFAULT_WINDOW
    title = title or "MOAI"

    for k, v in pairs(DEFAULT_WINDOW) do
        if not windowParams[k] then
            windowParams[k] = v
        end
    end

    Runtime:initialize()
    RenderMgr:initialize()
    InputMgr:initialize()
    SceneMgr:initialize()
    SoundMgr:initialize()

    Runtime:addEventListener("resize", self.onResize, self)

    self.screenWidth = windowParams.screenWidth
    self.screenHeight = windowParams.screenHeight

    self:updateVieport(windowParams)

    MOAISim.openWindow(title, self.screenWidth, self.screenHeight)
end

---
--
--
function App:onResize(event)
    self.screenWidth = event.width
    self.screenHeight = event.height

    self:updateVieport(self.windowParams)
end

---
--
--
function App:updateVieport(params)
    local width = params.viewWidth
    local height = params.viewHeight

    local wRatio = self.screenWidth / width
    local hRatio = self.screenHeight / height

    local view
    if params.scaleMode == "best_fit" then
        if self.screenWidth > self.screenHeight then
            view = mobileResolutions[self.screenWidth]
            self.viewWidth = view and view[1]
            self.viewHeight = view and view[2]
        else
            view = mobileResolutions[self.screenHeight]
            self.viewHeight = view and view[1]
            self.viewWidth = view and view[2]
        end
    end

    if not view or params.scaleMode == "letterbox" then
        self.viewWidth = (wRatio > hRatio) and width * wRatio / hRatio or width
        self.viewHeight = (hRatio > wRatio) and height * hRatio / wRatio or height
    end

    if params.scaleMode == "manual" then
        self.viewWidth = params.viewWidth
        self.viewHeight = params.viewHeight
    end

    self.windowParams = params
    self.viewport = self.viewport or MOAIViewport.new()
    self.viewport:setSize(self.screenWidth, self.screenHeight)
    self.viewport:setScale(self.viewWidth, self.viewHeight)
    self.viewport:setOffset(params.viewOffset[1], params.viewOffset[2])

    if (self.viewWidth == 320 and self.viewHeight == 568) or (self.viewWidth == 568 and self.viewHeight == 320) then
        App.device = "iphone5"
    elseif (self.viewWidth == 320 and self.viewHeight == 480) or (self.viewWidth == 480 and self.viewHeight == 320) then
        App.device = "iphone4"
    elseif (self.viewWidth == 384 and self.viewHeight == 512) or (self.viewWidth == 512 and self.viewHeight == 384) then
        App.device = "ipad"
    end
end

---
function App:getContentScale()
    return self.screenWidth / self.viewWidth
end

return App


text:
[![Build status](https://ci.appveyor.com/api/projects/status/qbq3ld4l475yj8jl?svg=true)](https://ci.appveyor.com/project/samisq/tidalwave)

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

[![Build Status](https://samsq.visualstudio.com/_apis/public/build/definitions/51f364c4-ad8d-4fee-9eeb-dd247b86bc2b/1/badge)](https://samsq.visualstudio.com/TidalWave/_build/index?definitionId=1)

# TidalWave
Tidal Wave is WebService for discovering music


text:
/* @file
 * Device module for a full duplex ethernet link for dist gem5 simulations.
 *
 * See comments in dev/net/dist_iface.hh for a generic description of dist
 * gem5 simulations.
 *
 * This class is meant to be a drop in replacement for the EtherLink class for
 * dist gem5 runs.
 *
 */
#ifndef __DEV_DIST_ETHERLINK_HH__
#define __DEV_DIST_ETHERLINK_HH__

#include <iostream>

#include "dev/net/etherlink.hh"
#include "params/DistEtherLink.hh"

class DistIface;
class EthPacketData;

/**
 * Model for a fixed bandwidth full duplex ethernet link.
 */
class DistEtherLink : public EtherObject
{
  protected:
    class LocalIface;

    /**
     * Model base class for a single uni-directional link.
     *
     * The link will encapsulate and transfer Ethernet packets to/from
     * the message server.
     */
    class Link : public Serializable
    {
      protected:
        std::string objName;
        DistEtherLink *parent;
        LocalIface *localIface;
        EtherDump *dump;
        DistIface *distIface;
        Event *event;
        EthPacketPtr packet;

      public:
        Link(const std::string &name, DistEtherLink *p,
             EtherDump *d, Event *e) :
            objName(name), parent(p), localIface(nullptr), dump(d),
            distIface(nullptr), event(e) {}

        ~Link() {}

        const std::string name() const { return objName; }
        bool busy() const { return (bool)packet; }
        void setLocalInt(LocalIface *i) { assert(!localIface); localIface=i; }

        void serialize(CheckpointOut &cp) const override;
        void unserialize(CheckpointIn &cp) override;
    };

    /**
     * Model for a send link.
     */
    class TxLink : public Link
    {
      protected:
        /**
         * Per byte send delay
         */
        double ticksPerByte;
        /**
         * Random component of the send delay
         */
        Tick delayVar;

        /**
         * Send done callback. Called from doneEvent.
         */
        void txDone();
        EventFunctionWrapper doneEvent;

      public:
        TxLink(const std::string &name, DistEtherLink *p,
               double invBW, Tick delay_var, EtherDump *d) :
            Link(name, p, d, &doneEvent), ticksPerByte(invBW),
            delayVar(delay_var), doneEvent([this]{ txDone(); }, name) {}
        ~TxLink() {}

        /**
         * Register the dist interface to be used to talk to the
         * peer gem5 processes.
         */
        void setDistInt(DistIface *m) { assert(!distIface); distIface=m; }

        /**
         * Initiate sending of a packet via this link.
         *
         * @param packet Ethernet packet to send
         */
        bool transmit(EthPacketPtr packet);
    };

    /**
     * Model for a receive link.
     */
    class RxLink : public Link
    {
      protected:

        /**
         * Transmission delay for the simulated Ethernet link.
         */
        Tick linkDelay;

        /**
         * Receive done callback method. Called from doneEvent.
         */
        void rxDone();
        EventFunctionWrapper _doneEvent;

      public:

        RxLink(const std::string &name, DistEtherLink *p,
               Tick delay, EtherDump *d) :
            Link(name, p, d, &_doneEvent), linkDelay(delay),
            _doneEvent([this]{ rxDone(); }, name) {}
        ~RxLink() {}

        /**
         * Register our dist interface to talk to the peer gem5 processes.
         */
        void setDistInt(DistIface *m);
        /**
         * Done events will be scheduled by DistIface (so we need the accessor)
         */
        const EventFunctionWrapper *doneEvent() const { return &_doneEvent; }
    };

    /**
     * Interface to the local simulated system
     */
    class LocalIface : public EtherInt
    {
      private:
        TxLink *txLink;

      public:
        LocalIface(const std::string &name, TxLink *tx, RxLink *rx,
                   DistIface *m);

        bool recvPacket(EthPacketPtr pkt) { return txLink->transmit(pkt); }
        void sendDone() { peer->sendDone(); }
        bool isBusy() { return txLink->busy(); }
    };

  protected:
    /**
     * Interface to talk to the peer gem5 processes.
     */
    DistIface *distIface;
    /**
     * Send link
     */
    TxLink *txLink;
    /**
     * Receive link
     */
    RxLink *rxLink;
    LocalIface *localIface;

    Tick linkDelay;

  public:
    typedef DistEtherLinkParams Params;
    DistEtherLink(const Params *p);
    ~DistEtherLink();

    const Params *
    params() const
    {
        return dynamic_cast<const Params *>(_params);
    }

    virtual EtherInt *getEthPort(const std::string &if_name,
                                 int idx) override;

    virtual void init() override;
    virtual void startup() override;

    void serialize(CheckpointOut &cp) const override;
    void unserialize(CheckpointIn &cp) override;
};

#endif // __DEV_DIST_ETHERLINK_HH__


text:
import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import withAsyncData from '../../common/hocs/AsyncDataContainer';
import { fetchFavoriteTopicsList } from '../../../actions/topicActions';
import TopicPreviewList from './TopicPreviewList';

const localMessages = {
  empty: { id: 'topics.favorite.none', defaultMessage: 'You don\'t have any starred topics.  You can star topics to save them here so you can find them more quickly. Click the star icon next to any topic\'s name to add it to this list.' },
};

const FavoriteTopicsContainer = (props) => {
  const { topics, onSetFavorited, onFetchAyncData } = props;
  return (
    <div className="favorite-topics-list">
      <TopicPreviewList
        topics={topics}
        linkGenerator={t => `/topics/${t.topics_id}/summary`}
        onSetFavorited={(id, isFav) => { onSetFavorited(id, isFav); onFetchAyncData(); }}
        emptyMsg={localMessages.empty}
      />
    </div>
  );
};

FavoriteTopicsContainer.propTypes = {
  // from parent
  onSetFavorited: PropTypes.func,
  // from state
  topics: PropTypes.array,
  // from compositonla chain
  intl: PropTypes.object.isRequired,
  onFetchAyncData: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.topics.favoriteList.fetchStatus,
  topics: state.topics.favoriteList.topics,
});

const fetchAsyncData = dispatch => dispatch(fetchFavoriteTopicsList());

export default
injectIntl(
  connect(mapStateToProps)(
    withAsyncData(fetchAsyncData)(
      FavoriteTopicsContainer
    )
  )
);


text:
<TITLE>Objects First With Java - Errata</TITLE>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../style.css" rel="stylesheet" type="text/css">

Errata (fifth edition)

(Errata for the fourth edition are here.)

              (Errata for the third edition are here.)

              (Errata for the second edition are
                here.)

Chapter 1:

Page 9:

"(Boolean is a type that can represent ..."

                  should read

                  "(The type boolean can represent ..."

                  (i.e. 'boolean' should be in lowercase, referring to the primitive type.)

Chapter 3:

Page 72:

"If one of the operands of a plus operation is a string and the other is not, then the other operator ..."

                  should read

                  "If one of the operands of a plus operation is a string and the other is not, then the other operand ..."

Chapter 10:

Page 330, Exercise 10.8:

"After having run the simulation for a while, reset it and also call the static reset method of the Randomizer class."

                  should read

                  "After having run the simulation for a while, call the static reset method of the Randomizer class and then the reset method of the Simulator object."

                  (In other words: the order of the method calls should be reversed.)

Back to main page


text:
	#Do this one time only
	./bin/grid install all

	mvn package && rm -rf deploy/samza && mkdir -p deploy/samza && tar -xvf ./target/join-samza-0.0.1-dist.tar.gz -C deploy/samza

## Deployment

	#Start grid
	rm -rf /tmp/kafka-logs/ && rm -rf /tmp/zookeeper/
	./bin/grid start all
	./bin/create-topics.sh
	./bin/load-topics.sh

	#Run the join job
	./bin/start-job.sh requests-join-user-json


text:
layout: page
title: "David Frederick"
comments: true
description: "blanks"
keywords: "David Frederick,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: Leeds School of Business

**Classes taught**: ACCT 4620, ACCT 6620

#### ACCT 4620: Auditing and Assurance Services

**Terms taught**: Fall 2006, Fall 2006, Spring 2007, Fall 2007, Fall 2007, Spring 2008, Fall 2008, Fall 2008, Spring 2009, Fall 2009, Fall 2009, Spring 2010, Fall 2010, Fall 2010, Spring 2011, Fall 2011, Fall 2011, Spring 2012, Fall 2012, Fall 2012, Spring 2013, Fall 2013, Fall 2013, Spring 2014, Fall 2014, Fall 2014, Spring 2015, Fall 2015, Fall 2015, Spring 2016, Fall 2016, Fall 2016, Spring 2017

**Instructor rating**: 5.56

**Standard deviation in instructor rating**: 0.22

**Average grade** (4.0 scale): 3.12

**Standard deviation in grades** (4.0 scale): 0.22

**Average workload** (raw): 2.53

**Standard deviation in workload** (raw): 0.18

#### ACCT 6620: Advanced Auditing: Business Risk and Decision Analysis

**Terms taught**: Spring 2007, Spring 2008, Spring 2008, Spring 2009, Spring 2009, Spring 2010, Spring 2010, Spring 2011, Spring 2011, Spring 2012, Spring 2012, Spring 2013, Spring 2013, Spring 2014, Spring 2014, Spring 2015, Spring 2015, Spring 2016, Spring 2016, Fall 2016, Spring 2017, Spring 2017

**Instructor rating**: 5.71

**Standard deviation in instructor rating**: 0.18

**Average grade** (4.0 scale): 3.59

**Standard deviation in grades** (4.0 scale): 0.16

**Average workload** (raw): 2.21

**Standard deviation in workload** (raw): 0.26


text:
using Newtonsoft.Json;

namespace Thinktecture.AuthorizationServer.OAuth2
{
    [JsonObject]
    public class TokenRequest
    {
        [JsonProperty(PropertyName = "grant_type")]
        public string Grant_Type { get; set; }

        [JsonProperty(PropertyName = "scope")]
        public string Scope { get; set; }

        [JsonProperty(PropertyName = "username")]
        public string UserName { get; set; }

        [JsonProperty(PropertyName = "password")]
        public string Password { get; set; }

        [JsonProperty(PropertyName = "code")]
        public string Code { get; set; }

        [JsonProperty(PropertyName = "refresh_token")]
        public string Refresh_Token { get; set; }

        [JsonProperty(PropertyName = "redirect_uri")]
        public string Redirect_Uri { get; set; }

        [JsonProperty(PropertyName = "assertion")]
        public string Assertion { get; set; }
    }
}