text:
package('Custom Extending', function() {
  "use strict";

  group('Extend | String', function () {
    Sugar.extend(String, {
      foo: function() {
        return 'bar';
      }
    });

    equal(run('s', 'foo'), 'bar', 'extend | basic functionality');
    equal('foo' in Sugar.String, true, 'extend | ensure method was added to global as well');
  });

  group('Extend | Number', function () {
    Sugar.extend(Number, {
      plus: function(a, b) {
        return this + a + b;
      },
      chr: function() {
        return String.fromCharCode(this);
      }
    });

    equal(run(1, 'plus', [2, 3]), 6, 'extend | arguments and scope are correct');

    Number.prototype.chr = function() { return 'F'; };

    equal((69).chr(), 'F', 'extend | should overwrite existing methods');

    Sugar.restore(Number, 'chr');

    equal(run(69, 'chr'), 'E', 'extend | simple array of strings should restore Sugar methods');
    equal(run(1, 'plus', [2, 3]), 6, 'extend | restoring Sugar methods should not override other custom extended methods');
    if(Sugar.noConflict) {
      equal((3).chr(), 'F', "Ensure that restore doesn't accidentally map methods to prototypes when no-conflict is active");
      delete Number.prototype.chr;
    }

  });

  group('Extend | Reverting', function () {

    // Issue #248
    // Ensure that methods can be reverted

    Sugar.extend(Object, {
      foobar: function() { return 'haha'; }
    });

    equal(Sugar.Object.foobar(), 'haha', 'Global method exists');
    equal('foobar' in {}, !Sugar.noConflict, 'Object.prototype was extended only if not no-conflict');
    Sugar.revert(Object, 'foobar');
    equal('foobar' in {}, false, 'custom method should be removed');

    // Reset...
    delete Sugar.Object.foobar;

    Object.prototype.foobar = function() {
      return 'original';
    }
    Sugar.extend(Object, {
      foobar: function() {
        return 'overwritten';
      }
    });
    equal(({}).foobar(), Sugar.noConflict ? 'original' : 'overwritten', 'custom method should overwrite');
    Sugar.revert(Object, 'foobar');
    equal(({}).foobar(), 'original', 'should revert back to original method');
    delete Object.prototype.foobar;

  });

});


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

<?php $sorted_order_ids = $this->blogpost_model->get_comments($post->comment_id);
   if ($sorted_order_ids == NULL) { ; }
   else {
      foreach ($sorted_order_ids as $order_id) {
         $comment = $this->blogpost_model->get_comment_info($post->comment_id, $order_id);
         $picture = $this->blogpost_model->get_profile_picture($comment->user_id);
         if ($comment === NULL) { break; }
         else {
            if ($this->blogpost_model->comment_type($comment->order_id) == "comment") { ?>

<?php echo $comment->month." ".$comment->day.", ".$comment->yr; ?>

                              <?php if ($picture === NULL) { ?>
                                 perm_identity
                              <?php } else {?>
                                 <img class="responsive-img z-depth-2 profile-image_2" src="users/<?php echo $comment->user_id; ?>/pictures/<?php echo $picture; ?>"
                                      id="profile-image_2">
                              <?php } ?>

<?php echo $comment->comments; ?>

            <?php if ($order_id == end($sorted_order_ids)) {?>

                           <?php include 'application/views/labcast/blog/post/subcomments.php'; ?>

<?php } ?>
      <?php }
            if ($this->blogpost_model->comment_type($comment->order_id) == "subcomment") { ?>

<?php echo $comment->month." ".$comment->day.", ".$comment->yr; ?>

                        <?php if ($picture === NULL) { ?>
                                 perm_identity
                        <?php } else {?>
                                 <img class="responsive-img z-depth-2 profile-image_2" src="users/<?php echo $comment->user_id; ?>/pictures/<?php echo $picture; ?>"
                                      id="profile-image_2">
                              <?php } ?>

<?php echo $comment->comments; ?>

                  <?php if ($this->blogpost_model->same_subcomment($comment->comment_id, $order_id ))
                  { ?>

<?php include 'application/views/labcast/blog/post/subcomments.php'; ?>

               <?php }?>

            <?php //if ($order_id !== end($sorted_order_ids)) { ?><?php //}?>
      <?php }
         }
      }
   } ?>

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;

namespace Orleankka
{
    public interface IStreamRefMiddleware
    {
        Task Publish<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : PublishMessage;
        Task Receive<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : StreamMessage;
    }

    public abstract class StreamRefMiddleware : IStreamRefMiddleware
    {
        readonly IStreamRefMiddleware next;

        protected StreamRefMiddleware(IStreamRefMiddleware next = null) =>
            this.next = next ?? DefaultStreamRefMiddleware.Instance;

        public virtual Task Publish<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : PublishMessage =>
            next.Publish(path, message, receiver);

        public virtual Task Receive<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : StreamMessage =>
            next.Receive(path, message, receiver);
    }

    public class DefaultStreamRefMiddleware : IStreamRefMiddleware
    {
        public static readonly DefaultStreamRefMiddleware Instance = new DefaultStreamRefMiddleware();

        public Task Publish<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : PublishMessage =>
            receiver(message);

        public Task Receive<TMessage>(StreamPath path, TMessage message, Receive<TMessage> receiver) where TMessage : StreamMessage =>
            receiver(message);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.Telecomm.Transparent" parent="@android:style/Theme.Material">
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
        <item name="android:backgroundDimEnabled">true</item>
    </style>
</resources>


text:
package com.palmelf.test.admin;

import com.palmelf.eoffice.dao.admin.ConfSummaryDao;
import com.palmelf.eoffice.model.admin.ConfSummary;
import com.palmelf.test.BaseTestCase;

import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.test.annotation.Rollback;

public class ConfSummaryDaoTestCase extends BaseTestCase {

	@Resource
	private ConfSummaryDao confSummaryDao;

	@Test
	@Rollback(false)
	public void add() {
		ConfSummary confSummary = new ConfSummary();

		this.confSummaryDao.save(confSummary);
	}
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>News - Summary Extraction</title>
		<link rel="stylesheet" href="css/bootstrap.css">
		<link rel="stylesheet" href="css/news.css">

		More Birthdays For Kids Under 5 Around The World

		www.npr.org

			The number of deaths of children under 5 has dropped by 49 percent since 1990. There are many reasons why, from better vaccines and health workers to ...

		Going—and Listening—to India

		www.gatesnotes.com

			Bill and Melinda Gates are headed to India, whose government has made ambitious commitments in a lot of the areas where the Gates Foundation works. ...

		+SocialGood | Backplane

		plussocialgood.org

			PlusSocialGood.org is powered by the unique insights and experiences of its members. It's a place where the global community of connectors comes ...

		Home - HeForShe

		www.heforshe.org

			A Solidarity Movement for Gender Equality

		The Deadliest Animal in the World

		www.gatesnotes.com

			Bill Gates introduces Mosquito Week on his personal blog, the Gates Notes. Everything posted this week is dedicated to this deadly creature. ...

		How to manage all your financial affairs from a $20 mobile phone

		qz.com

			"I feel like a caveman who's just been handed a Bic lighter," reported Charles Graeber, a writer for Bloomberg Businessweek who recently went to ...

		Pay-as-you-go solar startup signs up 100K solar users in East Africa

		gigaom.com

			Mobile payment enabled solar is working its way across rural Africa and India.

		Inspiring Quotes From Social Good Summit 2014

		mashable.com

			These thought-provoking quotes represent key takeaways from this year's Social Good Summit.

		Water for Ethiopia

		give.water.org

			Help John Green forever change the lives of 4,000 people. Contribute

		Join the fight against extreme poverty

		www.one.org

			Take action now and join the fight against extreme poverty and preventable diseases.

		Extreme Poverty: Choices

		www.youtube.com

			Extreme poverty is commonly defined as living on less than $1.25 per day. But extreme poverty is more than just a measure of daily income - it is the ...

		How not to be ignorant about the world

		www.ted.com

			How much do you know about the world? Hans Rosling, with his famous charts of global population, health and income data (and an extra-extra-long ...

		Hans Rosling and Ola Rosling: How not to be ignorant about the world

		www.youtube.com

			How much do you know about the world? Hans Rosling, with his famous charts of global population, health and income data (and an extra-extra-long ...

		How the global banana industry is killing the world's favorite fruit

		qz.com

			During harvest last year, banana farmers in Jordan and Mozambique made a chilling discovery. Their plants were no longer bearing the soft, creamy ...

		After the Ice Bucket

		www.gatesnotes.com

			Steve Gleason is a former NFL player with ALS. He met with Bill Gates and shared with him what it will take to stop the disease and what he's doing ...

		Bill Gates and John Green Discuss Global Health

		www.youtube.com

			A special bonus video in which John Green and Microsoft founder Bill Gates talk about how Ethiopia has reduced its infant mortality dramatically in ...

		When A Home Poses Health Risks, The Floor May Be The Culprit

		www.npr.org

			Homes with dirt floors can make people sick. Replacing them with concrete floors helps cut risks but isn't always affordable. A new project in Rwanda ...

		Crash Course Big History: The Big Bang

		www.youtube.com

			CrashCourse is a fast, funny, irreverent look at history. In this episode, brothers John and Hank Green gives us their take on what makes Big History ...

		Teachers at Their Best | Bill & Melinda Gates Foundation

		www.youtube.com

			To improve the educational system in the United States we need to focus on helping teachers do their best work.

		Food Is Weird: Understanding Agriculture in the Developing World

		www.youtube.com

			In which John Green flies in a helicopter with Bill Gates in Ethiopia, investigates a new form of cursing, and discusses agricultural ...

		Big History Project

		www.bighistoryproject.com

			Big questions about our Universe, our planet, life, and humanity. From the Big Bang to where we are going in the future, Big History covers it all.

		The Growth Mindset

		www.youtube.com

			Sal talks with Stanford Professor Carol Dweck about her research on the Growth Mindset. Join the You Can Learn Anything movement at ...

		How to Make a Teacher's Day

		www.gatesnotes.com

			You can help a teacher start the school year off right. Make a donation via DonorsChoose.org, and the Bill and Melinda Gates Foundation will meet you ...

		Smart Phones for Smart Kids

		www.kpcb.com:80

			In the coming weeks, 55 million U.S. students in grades K-12 will go back to school. In their backpacks they will carry pens, No. 2 pencils, 3-ring ...

		Discover the best edtech products.

		www.graphite.org

			Graphite - Teacher Reviewed Apps, Games, & Websites Discover apps, games, and websites that will help your students learn. Graphite, from Common ...

		6 Tools for Teachers

		www.gatesnotes.com

			Bill Gates highlights six promising apps and websites for making your teacher's job easier: BetterLesson, Lightsail, ThinkCERCA, FineTune, Edmondo, ...

		How Teachers Learn

		www.gatesnotes.com

			Melinda Gates recently met with a group of teachers to discuss what gets them excited about their job—and what they struggle with. Six of them shared ...

		How Teachers Spend Their Summer

		www.youtube.com

			Melinda Gates has learned that a lot of what she's heard about the profession of teaching is wrong. For example, the myth that teacher's get summers ...

		"It's Like You're Conducting an Orchestra"

		www.gatesnotes.com

			Bill Gates shares what he learned from Katie Brown, Washington state's 2014 Teacher of the Year.

		Bill Gates Meets with Katie Brown, Washington State Teacher of the Year

		www.youtube.com

			From the minute you meet Katie Brown, you get the feeling she's an amazing teacher. You immediately think: I would love for my kids to be in her ...


text:
package me.piggypiglet.bottlewars.handlers;

import me.piggypiglet.bottlewars.BottleWars;
import me.piggypiglet.bottlewars.Config;
import org.bukkit.configuration.file.FileConfiguration;

// ------------------------------
// Copyright (c) PiggyPiglet 2017
// https://www.piggypiglet.me
// ------------------------------
public class DataSaving {
    private BottleWars main = BottleWars.getInstance();
    private final FileConfiguration config = new Config(main.getDataFolder().getPath(), "config.yml").getConfig();

    public void saveString(String str) {
        switch (config.getString("storage-method", "yaml").toLowerCase()) {
            case "mysql":
                new MySQL(config);
                break;
            case "json":
                new JSON(config);
                break;
            case "mariadb":
                new MySQL(config);
                break;
            case "mongodb":
                new MongoDB(config);
                break;
            case "yaml":
                new YAML(config);
                break;
            case "h2":
                new H2(config);
                break;
            case "sqllite":
                new H2(config);
                break;
            case "postgresql":
                new PostgreSQL(config);
                break;
        }
    }
}


text:
module CLaSH.Util.CoreHW.Constants
  ( builtinIds
  , builtinDicts
  , builtinDFuns
  , builtinDataCons
  , builtinFuns
  )
where

builtinIds :: [String]
builtinIds = concat [builtinDicts,builtinDFuns,builtinDataCons,builtinFuns]

builtinDicts :: [String]
builtinDicts = ["$dPositiveT","$dNaturalT","$dIntegerT"]

builtinDFuns :: [String]
builtinDFuns = ["$fShowUnsigned","$fEqInteger","$fPositiveTx","$fNaturalTx",
  "$fArrowComponent","$fArrowLoopComponent","$fShowSigned","$fNumInt"]

builtinDataCons :: [String]
builtinDataCons = ["I#","Int#","Signed","Unsigned"]

builtinFuns :: [String]
builtinFuns = concat
  [ stateFuns
  , bitFuns
  , vecFuns
  , unsignedFuns
  , signedFuns
  , numFuns
  , eqFuns
  , ordFuns
  , literalFuns
  ]
  where
    stateFuns = ["delayBuiltin","blockRamBuiltin","build"]

    bitFuns = ["xorB","andB","notB","orB",".&.","xor","$c.&.","$cxor","$c.|."
              ,"$ccomplement", "$cshift", "$crotate", "$cbit", "$csetBit"
              ,"$cclearBit", "$ccomplementBit", "$ctestBit", "$cbitSize"
              ,"$cisSigned","$cshiftL", "$cshiftR", "$crotateL", "$crotateR"
              ]

    vecFuns =
      [ "+>>","<<+","vinit","vlast","singleton","empty","+>","vcopyn"
      , "vcopy","vfoldl","vzipWith","vmap","!","vreplace"
      ]

    numFuns = ["+","*","-","negate","abs","signum","fromInteger"]

    eqFuns = ["==","/="]

    ordFuns = ["compare","<",">=",">","<=","max","min"]

    unsignedFuns =
      ["eqUnsigned","neqUnsigned","plusUnsigned","minUnsigned","timesUnsigned"
      ,"negateUnsigned","unsignedFromInteger","absUnsigned","signumUnsigned"
      ]

    signedFuns =
      ["eqSigned", "neqSigned","plusSigned", "minSigned", "timesSigned"
      ,"negateSigned", "signedFromInteger", "absSigned", "signumSigned"
      ]

    literalFuns = ["timesInteger","plusInteger","smallInteger"]


text:
import type {
  Layout,
  PointerEvent,
} from 'react-native/Libraries/Types/CoreEventTypes';
import type {PlatformTestComponentBaseProps} from '../PlatformTest/RNTesterPlatformTestTypes';

import * as React from 'react';
import {useCallback, useRef, useState} from 'react';
import {View, StyleSheet} from 'react-native';

import RNTesterPlatformTest from '../PlatformTest/RNTesterPlatformTest';
import {check_PointerEvent, useTestEventHandler} from './PointerEventSupport';

const eventList = [
  'pointerOver',
  'pointerEnter',
  'pointerMove',
  'pointerDown',
  'pointerUp',
  'pointerOut',
  'pointerLeave',
];

function PointerEventAttributesHoverablePointersTestCase(
  props: PlatformTestComponentBaseProps,
) {
  const {harness} = props;

  const detected_pointertypesRef = useRef(({}: {[string]: boolean}));
  const detected_eventTypesRef = useRef(({}: {[string]: boolean}));
  const expectedPointerIdRef = useRef(NaN);

  const [square1Visible, setSquare1Visible] = useState(true);
  const [square2Visible, setSquare2Visible] = useState(false);

  // Adapted from https://github.com/web-platform-tests/wpt/blob/6c26371ea1c144dd612864a278e88b6ba2f3d883/pointerevents/pointerevent_attributes_hoverable_pointers.html#L29
  const checkPointerEventAttributes = useCallback(
    (
      event: PointerEvent,
      eventType: string,
      targetLayout: Layout,
      testNamePrefix: string,
      expectedPointerType: string,
    ) => {
      const detected_pointertypes = detected_pointertypesRef.current;
      const detected_eventTypes = detected_eventTypesRef.current;
      const expectedPointerId = expectedPointerIdRef.current;

      if (detected_eventTypes[eventType]) {
        return;
      }
      const expectedEventType =
        eventList[Object.keys(detected_eventTypes).length].toLowerCase();
      detected_eventTypes[eventType] = true;
      const pointerTestName =
        testNamePrefix + ' ' + expectedPointerType + ' ' + expectedEventType;

      detected_pointertypes[event.nativeEvent.pointerType] = true;
      harness.test(({assert_equals}) => {
        assert_equals(
          eventType,
          expectedEventType,
          'Event.type should be ' + expectedEventType,
        );
      }, pointerTestName + "'s type should be " + expectedEventType);

      // Test button and buttons
      if (eventType === 'pointerdown') {
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.button, 0, 'Button attribute is 0');
        }, pointerTestName + "'s button attribute is 0 when left mouse button is pressed.");
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.buttons, 1, 'Buttons attribute is 1');
        }, pointerTestName + "'s buttons attribute is 1 when left mouse button is pressed.");
      } else if (eventType === 'pointerup') {
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.button, 0, 'Button attribute is 0');
        }, pointerTestName + "'s button attribute is 0 when left mouse button is just released.");
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.buttons, 0, 'Buttons attribute is 0');
        }, pointerTestName + "'s buttons attribute is 0 when left mouse button is just released.");
      } else {
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.button, -1, 'Button attribute is -1');
        }, pointerTestName + "'s button is -1 when mouse buttons are in released state.");
        harness.test(({assert_equals}) => {
          assert_equals(event.nativeEvent.buttons, 0, 'Buttons attribute is 0');
        }, pointerTestName + "'s buttons is 0 when mouse buttons are in released state.");
      }

      const left = targetLayout.x;
      const top = targetLayout.y;
      const right = targetLayout.x + targetLayout.width;
      const bottom = targetLayout.y + targetLayout.height;

      // Test clientX and clientY
      if (eventType !== 'pointerout' && eventType !== 'pointerleave') {
        harness.test(({assert_greater_than_equal, assert_less_than_equal}) => {
          assert_greater_than_equal(
            event.nativeEvent.clientX,
            left,
            'clientX should be greater or equal than left of the box',
          );
          assert_greater_than_equal(
            event.nativeEvent.clientY,
            top,
            'clientY should be greater or equal than top of the box',
          );
          assert_less_than_equal(
            event.nativeEvent.clientX,
            right,
            'clientX should be less or equal than right of the box',
          );
          assert_less_than_equal(
            event.nativeEvent.clientY,
            bottom,
            'clientY should be less or equal than bottom of the box',
          );
        }, pointerTestName + "'s ClientX and ClientY attributes are correct.");
      } else {
        harness.test(({assert_true}) => {
          assert_true(
            event.nativeEvent.clientX < left ||
              event.nativeEvent.clientX >= right ||
              event.nativeEvent.clientY < top ||
              event.nativeEvent.clientY >= bottom,
            'ClientX/Y should be out of the boundaries of the box',
          );
        }, pointerTestName + "'s ClientX and ClientY attributes are correct.");
      }

      check_PointerEvent(harness, event, eventType, {
        testNamePrefix,
      });

      // Test isPrimary value
      harness.test(({assert_equals}) => {
        assert_equals(
          event.nativeEvent.isPrimary,
          true,
          'isPrimary should be true',
        );
      }, pointerTestName + '.isPrimary attribute is correct.');

      // Test pointerId value
      if (isNaN(expectedPointerId)) {
        expectedPointerIdRef.current = event.nativeEvent.pointerId;
      } else {
        harness.test(({assert_equals}) => {
          assert_equals(
            event.nativeEvent.pointerId,
            expectedPointerId,
            'pointerId should remain the same for the same active pointer',
          );
        }, pointerTestName + '.pointerId should be the same as previous pointer events for this active pointer.');
      }
    },
    [harness],
  );

  const square1Ref = useRef();
  const square1Handlers = useTestEventHandler(eventList, (event, eventType) => {
    if (!square1Visible) {
      return;
    }

    const square1Elem = square1Ref.current;
    if (square1Elem != null) {
      square1Elem.measure((x, y, width, height, pageX, pageY) => {
        checkPointerEventAttributes(
          event,
          eventType,
          {x: pageX, y: pageY, width, height},
          '',
          'mouse',
        );
        if (
          Object.keys(detected_eventTypesRef.current).length ===
          eventList.length
        ) {
          setSquare1Visible(false);
          detected_eventTypesRef.current = ({}: {[string]: boolean});
          setSquare2Visible(true);
          expectedPointerIdRef.current = NaN;
        }
      });
    }
  });

  const square2Ref = useRef();
  const square2Handlers = useTestEventHandler(eventList, (event, eventType) => {
    const square2Elem = square2Ref.current;
    if (square2Elem != null) {
      square2Elem.measure((x, y, width, height, pageX, pageY) => {
        checkPointerEventAttributes(
          event,
          eventType,
          {x: pageX, y: pageY, width, height},
          'Inner frame ',
          'mouse',
        );
        if (
          Object.keys(detected_eventTypesRef.current).length ===
          eventList.length
        ) {
          setSquare2Visible(false);
          // TODO: Mark test as done
        }
      });
    }
  });

  return (
    <View style={styles.root}>
      <View style={styles.squareContainer}>
        {square1Visible && (
          <View ref={square1Ref} style={styles.square1} {...square1Handlers} />
        )}
      </View>
      <View style={styles.squareContainer}>
        {square2Visible && (
          <View ref={square2Ref} style={styles.square2} {...square2Handlers} />
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    height: 150,
    flexDirection: 'row',
    alignItems: 'center',
  },
  square1: {
    width: 40,
    height: 40,
    backgroundColor: 'black',
  },
  square2: {
    width: 40,
    height: 40,
    backgroundColor: 'red',
  },
  squareContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

type Props = $ReadOnly<{}>;
export default function PointerEventAttributesHoverablePointers(
  props: Props,
): React.MixedElement {
  return (
    <RNTesterPlatformTest
      component={PointerEventAttributesHoverablePointersTestCase}
      description="This test checks the properties of hoverable pointer events. If you are using hoverable pen don't leave the range of digitizer while doing the instructions."
      instructions={[
        'Move your pointer over the black square and click on it.',
        'Then move it off the black square so that it disappears.',
        'When red square appears move your pointer over the red square and click on it.',
        'Then move it off the red square.',
      ]}
      title="Pointer Events hoverable pointer attributes test"
    />
  );
}


text:
var connect = require("gulp-connect"),
    livereload = require("livereload");

module.exports = function(config) {
    return function(done) {

        livereload.listen({
            port: config.liveReloadPort
        });

        connect.server({
            root: config.paths.root_serve,
            port: config.port,
            livereload: false
        });
    };
};


text:
package org.nutz.dao.jdbc;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Pattern;

import org.nutz.dao.DaoException;
import org.nutz.filepool.FilePool;
import org.nutz.filepool.NutFilePool;
import org.nutz.filepool.SynchronizedFilePool;
import org.nutz.lang.Mirror;
import org.nutz.lang.util.Disks;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.Mvcs;

public class JdbcExpertConfigFile {

    private Map<String, Class<? extends JdbcExpert>> experts;

    private Map<Pattern, Class<? extends JdbcExpert>> _experts;

    private Map<String, Object> config;

    private FilePool pool;

    private static final Log log = Logs.get();

    JdbcExpertConfigFile init() {
        // 即使初始化失败,也继续执行
    	String home = config.get("pool-home").toString();
        try {
            home = Disks.normalize(home);
            if (home == null)
            	home = config.get("pool-home").toString();
            long max = config.containsKey("pool-max") ? ((Number) config.get("pool-max")).longValue() : 2000;
            if (home.contains("${app.home}")) {
                try {
                    // 这里引用了Mvcs类, 不太舒服,但应该还是有益处的
                    home.replace("${app.home}", Mvcs.getServletContext().getRealPath("/"));
                }
                catch (Throwable e) {
                }
            }
            try {
                pool = new NutFilePool(home, max);
            }
            catch (Exception e) {
                // 看看是不是Mvc环境,尝试在WebContent下创建
                if (!home.startsWith("~/") || Mvcs.getServletContext() == null)
                    throw e;
                try {
                    String tmp = Mvcs.getServletContext().getRealPath("/") + home.substring(2);
                    pool = new NutFilePool(tmp, max);
                    log.info("had created filepool under webapp root path");
                }
                catch (Exception e1) {
                    throw e; // 抛出原本的异常好了,哎...
                }
            }
            pool = new SynchronizedFilePool(pool);
        } catch (Throwable e) {
            if (log.isWarnEnabled())
                log.warnf("NutDao FilePool create fail!! Blob and Clob Support is DISABLE!! Home="+home, e);
        }
        return this;
    }

    public JdbcExpert getExpert(String str) {
        Class<? extends JdbcExpert> type = experts.get(str);
        return Mirror.me(type).born(config);
    }

    public JdbcExpert matchExpert(String dbName) {
        for (Entry<Pattern, Class<? extends JdbcExpert>> entry : _experts.entrySet()) {
            if (entry.getKey().matcher(dbName).find())
                return Mirror.me(entry.getValue()).born(this);
        }
        return null;
    }

    /**
     * 注意,返回的Map实例不允许被修改
     */
    public Map<String, Class<? extends JdbcExpert>> getExperts() {
        return Collections.unmodifiableMap(experts);
    }

    public Map<String, Object> getConfig() {
        return config;
    }

    public FilePool getPool() {
        if (pool == null) {
            if (log.isWarnEnabled())
                log.warnf("NutDao FilePool create fail!! Blob and Clob Support is DISABLE!!");
            throw new DaoException("NutDao FilePool create fail!! Blob and Clob Support is DISABLE!!");
        }
        return pool;
    }

    // 在 fromJson 的时候,会被调用
    public void setExperts(Map<String, Class<? extends JdbcExpert>> experts) {
        this.experts = experts;
        this._experts = new HashMap<Pattern, Class<? extends JdbcExpert>>();
        for (Entry<String, Class<? extends JdbcExpert>> entry : experts.entrySet()) {
            //忽略大小写,并且让换行符与.能够匹配
            _experts.put(Pattern.compile(entry.getKey(), Pattern.DOTALL & Pattern.CASE_INSENSITIVE), entry.getValue());
        }
    }

    public void setConfig(Map<String, Object> config) {
        this.config = config;
    }

}


text:
require 'rails_helper'

feature 'Creating a suggested quiz' do
  let(:reader) { create :reader }
  let(:case_study) do
    create(:case, :published)
  end

  before(:each) { login_as reader }

  scenario 'is possible' do
    reader.my_cases << case_study

    visit case_path(case_study, edit: true)
    click_on 'Pre/Post Assessment'
    expect(page).to have_content 'Suggested Quizzes'

    click_on 'New Quiz'
    fill_in 'Quiz title', with: 'My Suggested Quiz'
    click_on 'Add question'
    fill_in 'Question text', with: 'What is your favorite color?'
    click_on 'Save'

    expect(page)
      .to have_content 'Questions cannot be blank and correct answers are required.'
    fill_in 'Enter a sample answer, or click "Add option" to make this question multiple choice...',
            with: 'Blue is what most people say.'
    click_on 'Save'

    expect(page).to have_content 'My Suggested Quiz'
    expect(page).to have_content '1 Open Ended Question'

    click_on 'Close'
    click_on 'Save'
    expect(page).to have_content 'Saved successfully'

    other_reader = create :reader
    Capybara.using_session :other do
      login_as other_reader
      visit case_path case_study
      click_on 'Deploy this Case'

      select 'Create a New Study Group', from: 'Study Group'
      fill_in 'Group Name', with: 'My Study Group'
      click_on 'Create Deployment'
      click_on 'Add Quiz'
      expect(page).to have_content 'What is your favorite color?'
    end
  end

  scenario 'is not possible when the user can't edit the case' do
    visit case_path case_study
    expect(page).not_to have_content 'Pre/Post Assessment'

    visit case_path(case_study) + '/suggested_quizzes'
    expect(page).not_to have_content 'Suggested Quizzes'
  end

  scenario 'is possible when other quizzes already exist' do
    reader.my_cases << case_study
    create :quiz, case: case_study

    visit case_path(case_study, edit: true)
    click_on 'Pre/Post Assessment'
    click_on 'New Quiz'
    expect(page).to have_field 'Quiz title'
  end
end


text:
<?php

namespace Core\ViewModel\Gds\Table;

use DvsaCommon\Utility\ArrayUtils;

class GdsRow implements GdsRowFlowInterface
{
    private $htmlId = null;
    private $htmlClass = null;
    /** @var GdsTableActionLink */
    private $actionLink = null;

    /** @var GdsRowLabel */
    private $label = null;

    /** @var GdsRowValue */
    private $value = null;

    /** @var GdsRowValueMetaData */
    private $valueMetaData = null;

    private $parentTable;

    /** @var GdsTableActionLink[] */
    private $actionLinks = [];

    public function __construct(GdsTable $parentTable, $htmlId, $htmlClass)
    {
        $this->parentTable = $parentTable;
        $this->htmlId = $htmlId;
        $this->htmlClass = $htmlClass;
    }

    public function getHtmlId()
    {
        return $this->htmlId;
    }

    public function isHtmlClassSet()
    {
        return $this->htmlClass !== null;
    }

    public function getHtmlClass()
    {
        return $this->htmlClass;
    }

    public function setLabel($content, $escape = true)
    {
        $this->label = new GdsRowLabel($this, $content, $escape);

        return $this->label;
    }

    public function getLabel()
    {
        return $this->label;
    }

    public function addActionLink($text, $url, $tooltip = ' ', $id = '')
    {
        $actionLink = new GdsTableActionLink($this, $text, $url, $tooltip, $id);
        $this->actionLinks[] = $actionLink;

        return $actionLink;
    }

    public function hasActionLink($index = 0)
    {
        return array_key_exists($index, $this->actionLinks);
    }

    public function hasActionLinks()
    {
        return !empty($this->actionLinks);
    }

    public function getActionLink($index = 0)
    {
        return ArrayUtils::tryGet($this->actionLinks, $index);
    }

    public function getActionLinks()
    {
        return $this->actionLinks;
    }

    public function newRow($htmlId = null)
    {
        return $this->parentTable->newRow($htmlId = null);
    }

    public function getRow($index)
    {
        return $this->parentTable->getRow($index);
    }

    public function getRows()
    {
        return $this->parentTable->getRows();
    }

    public function setValue($content, $escape = true)
    {
        $this->value = new GdsRowValue($this, $content, $escape);

        return $this->value;
    }

    public function getValue()
    {
        return $this->value;
    }

    public function setValueMetaData($content, $escape = true)
    {
        $this->valueMetaData = new GdsRowValueMetaData($this, $content, $escape);

        return $this->valueMetaData;
    }

    public function getValueMetaData()
    {
        return $this->valueMetaData;
    }
}


text:
typealias ElSignScaling Cuint
const SIGN_SCALE_NONE = ElSignScaling(0)
const SIGN_SCALE_DET  = ElSignScaling(1)
const SIGN_SCALE_FROB = ElSignScaling(2)

immutable SignCtrl{T<:ElFloatType}
    maxIts::ElInt
    tol::T
    power::T
    scaling::ElSignScaling
    progress::ElBool
end
function SignCtrl{T<:ElFloatType}(::Type{T};
    maxIts = 100,
    tol = 0,
    power = 1,
    scaling = SIGN_SCALE_FROB,
    progress::Bool = false)
    SignCtrl{T}(ElInt(maxIts),
        T(tol),
        T(power),
        ElSignScaling(scaling),
        ElBool(progress))
end

# Schur
immutable HessQRCtrl
    distAED::ElBool
    blockHeight::ElInt
    blockWidth::ElInt
end
function HessQRCtrl(
    distAED::Bool = false,
    blockHeight = 32,
    blockWidth = 32)
    HessQRCtrl(ElBool(distAED),ElInt(blockHeight),ElInt(blockWidth))
end

immutable SDCCtrl{T<:ElFloatType}
    cutoff::ElInt
    maxInnerIts::ElInt
    maxOuterIts::ElInt
    tol::T
    spreadFactor::T
    random::ElBool
    progress::ElBool
    signCtrl::SignCtrl{T}
end
function SDCCtrl{T<:ElFloatType}(::Type{T};
    cutoff = 256,
    maxInnerIts = 2,
    maxOuterIts = 10,
    tol = 0,
    spreadFactor = 1e-6,
    random::Bool = true,
    progress::Bool = false,
    signCtrl = SignCtrl(T))
    SDCCtrl{T}(ElInt(cutoff),
        ElInt(maxInnerIts),
        ElInt(maxOuterIts),
        T(tol),
        T(spreadFactor),
        ElBool(random),
        ElBool(progress),
        signCtrl)
end

immutable SchurCtrl{T<:ElFloatType}
    useSDC::ElBool
    qrCtrl::HessQRCtrl
    sdcCtrl::SDCCtrl{T}
end
function SchurCtrl{T<:ElFloatType}(::Type{T};
    useSDC::Bool = false,
    qrCtrl::HessQRCtrl = HessQRCtrl(),
    sdcCtrl::SDCCtrl{T} = SDCCtrl(T))
    SchurCtrl{T}(ElBool(useSDC),
        qrCtrl,
        sdcCtrl)
end

# Pseueospectra
typealias ElFileFormat Cuint
const AUTO          = ElFileFormat(0)
const ASCII         = ElFileFormat(1)
const ASCII_MATLAB  = ElFileFormat(2)
const BINARY        = ElFileFormat(3)
const BINARY_FLAT   = ElFileFormat(4)
const BMP           = ElFileFormat(5)
const JPG           = ElFileFormat(6)
const JPEG          = ElFileFormat(7)
const MATRIX_MARKET = ElFileFormat(8)
const PNG           = ElFileFormat(9)
const PPM           = ElFileFormat(10)
const XBM           = ElFileFormat(11)
const XPM           = ElFileFormat(12)

immutable SnapshotCtrl
    realSize::ElInt
    imagSize::ElInt
    imgSaveFreq::ElInt
    numSaveFreq::ElInt
    imgDispFreq::ElInt
    imgSaveCount::ElInt
    numSaveCount::ElInt
    imgDispCount::ElInt
    imgBase::Cstring
    numBase::Cstring
    imgFormat::ElFileFormat
    numFormat::ElFileFormat
    itCounts::ElBool
end
function SnapshotCtrl(realSize=0,
    imagSize=0,
    imgSaveFreq=-1,
    numSaveFreq=-1,
    imgDispFreq=-1,
    imgSaveCount=0,
    numSaveCount=0,
    imgDispCount=0,
    imgBase::String="ps",
    numBase::String="ps",
    imgFormat=PNG,
    numFormat=ASCII_MATLAB,
    itCounts::Bool=true)
    SnapshotCtrl(Cint(realSize),
        Cint(imagSize),
        Cint(imgSaveFreq),
        Cint(numSaveFreq),
        Cint(imgDispFreq),
        Cint(imgSaveCount),
        Cint(numSaveCount),
        Cint(imgDispCount),
        Cstring(Symbol(imgBase)),
        Cstring(Symbol(numBase)),
        ElFileFormat(imgFormat),
        ElFileFormat(numFormat),
        ElBool(itCounts))
end

typealias ElPseudospecNorm Cuint
const PS_TWO_NORM = ElPseudospecNorm(0)
const PS_ONE_NORM = ElPseudospecNorm(1)

immutable PseudospecCtrl{T<:ElFloatType}
    norm::ElPseudospecNorm
    blockWidth::ElInt
    schur::ElBool
    forceComplexSchur::ElBool
    forceComplexPs::ElBool
    schurCtrl::SchurCtrl{T}
    maxIts::ElInt
    tol::T
    deflate::ElBool
    arnoldi::ElBool
    basisSize::ElInt
    reorthog::ElBool
    progress::ElBool
    snapCtrl::SnapshotCtrl
end
function PseudospecCtrl{T<:ElFloatType}(::Type{T};
    norm = PS_TWO_NORM,
    blockWidth = 10,
    schur::Bool = true,
    forceComplexSchur::Bool = false,
    forceComplexPs::Bool = false,
    schurCtrl = SchurCtrl(T),
    maxIts = 50,
    tol = 1e-6,
    deflate::Bool = true,
    arnoldi::Bool = true,
    basisSize = 10,
    reorthog::Bool = true,
    progress::Bool = false,
    snapCtrl = SnapshotCtrl())

    PseudospecCtrl{T}(ElPseudospecNorm(norm),
        ElInt(blockWidth),
        ElBool(schur),
        ElBool(forceComplexSchur),
        ElBool(forceComplexPs),
        schurCtrl,
        ElInt(maxIts),
        T(tol),
        ElBool(deflate),
        ElBool(arnoldi),
        ElInt(basisSize),
        ElBool(reorthog),
        ElBool(progress),
        snapCtrl)
end

immutable SpectralBox{T}
    center::Complex{T}
    realWidth::T
    imagWidth::T
end

# SVD
immutable SVDCtrl{T<:ElFloatType}
    seqQR::ElBool
    valChanRatio::Cdouble
    fullChanRatio::Cdouble
    thresholded::ElBool
    relative::ElBool
    tol::T
end
function SVDCtrl{T<:ElFloatType}(::Type{T};
    seqQR = false,
    valChanRatio = 1.2,
    fullChanRatio = 1.5,
    thresholded = false,
    relative = true,
    tol = 0.0)

    SVDCtrl{T}(ElBool(seqQR),
        Cdouble(valChanRatio),
        Cdouble(fullChanRatio),
        ElBool(thresholded),
        ElBool(relative),
        T(tol))
end

for (elty, ext) in ((:Float32, :s),
                    (:Float64, :d),
                    (:Complex64, :c),
                    (:Complex128, :z))
    for mattype in ("", "Dist")
        mat = Symbol(mattype, "Matrix")
        @eval begin

            function eigvalsTridiag(d::$mat{real($elty)}, dSub::$mat{$elty}, sort::SortType = ASCENDING)
                w = $mat(real($elty))
                err = ccall(($(string("ElHermitianTridiagEig", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, Ptr{Void}, SortType),
                    d.obj, dSub.obj, w.obj, sort)
                err == 0 || throw(ElError(err))
                return w
            end

            function eigTridiag(d::$mat{real($elty)}, dSub::$mat{$elty}, sort::SortType = ASCENDING)
                w = $mat(real($elty))
                Z = $mat($elty)
                err = ccall(($(string("ElHermitianTridiagEigPair", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, SortType),
                    d.obj, dSub.obj, w.obj, Z.obj, sort)
                err == 0 || throw(ElError(err))
                return w, Z
            end

            function eigvalsHermitian(uplo::UpperOrLower, A::$mat{$elty}, sort::SortType = ASCENDING)
                w = $mat(real($elty))
                err = ccall(($(string("ElHermitianEig", mattype, "_", ext)), libEl), Cuint,
                    (UpperOrLower, Ptr{Void}, Ptr{Void}, SortType),
                    uplo, A.obj, w.obj, sort)
                err == 0 || throw(ElError(err))
                return w
            end

            function eigHermitian(uplo::UpperOrLower, A::$mat{$elty}, sort::SortType = ASCENDING)
                w = $mat(real($elty))
                Z = $mat($elty)
                err = ccall(($(string("ElHermitianEigPair", mattype, "_", ext)), libEl), Cuint,
                    (UpperOrLower, Ptr{Void}, Ptr{Void}, Ptr{Void}, SortType),
                    uplo, A.obj, w.obj, Z.obj, sort)
                err == 0 || throw(ElError(err))
                return w, Z
            end

            function svdvals!(A::$mat{$elty})
                s = $mat(real($elty))
                err = ccall(($(string("ElSingularValues", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}),
                    A.obj, s.obj)
                err == 0 || throw(ElError(err))
                return s
            end

            function svdvals!(A::$mat{$elty}, ctrl::SVDCtrl{real($elty)})
                s = $mat(real($elty))
                err = ccall(($(string("ElSingularValuesX", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, SVDCtrl{real($elty)}),
                    A.obj, s.obj, ctrl)
                err == 0 || throw(ElError(err))
                return s
            end

            function svd(A::$mat{$elty})
                U = $mat($elty)
                s = $mat(real($elty))
                V = $mat($elty)
                err = ccall(($(string("ElSVD", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}),
                    A.obj, U.obj, s.obj, V.obj)
                err == 0 || throw(ElError(err))
                return U, s, V
            end

            function svd!(A::$mat{$elty}, ctrl::SVDCtrl{real($elty)})
                U = $mat($elty)
                s = $mat(real($elty))
                V = $mat($elty)
                err = ccall(($(string("ElSVDX", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, Ptr{Void}, Ptr{Void}, SVDCtrl{real($elty)}),
                    A.obj, U.obj, s.obj, V.obj, ctrl)
                err == 0 || throw(ElError(err))
                return U, s, V
            end

            function spectralPortrait(A::$mat{$elty}, realSize::ElInt, imagSize::ElInt, psCtrl::PseudospecCtrl{real($elty)}=PseudospecCtrl(real($elty)))
                invNormMap = $mat(real($elty))
                box = Ref{SpectralBox{real($elty)}}()
                err = ccall(($(string("ElSpectralPortraitX", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, ElInt, ElInt, Ref{SpectralBox{real($elty)}},PseudospecCtrl{real($elty)}),
                    A.obj, invNormMap.obj, realSize, imagSize, box, psCtrl)
                err == 0 || throw(ElError(err))
                return invNormMap, box[]
            end

            function spectralWindow(A::$mat{$elty}, center::Complex{real($elty)}, realWidth::real($elty), imagWidth::real($elty), realSize::ElInt, imagSize::ElInt, psCtrl::PseudospecCtrl{real($elty)}=PseudospecCtrl(real($elty)))
                invNormMap = $mat(real($elty))
                err = ccall(($(string("ElSpectralWindowX", mattype, "_", ext)), libEl), Cuint,
                    (Ptr{Void}, Ptr{Void}, Complex{real($elty)}, real($elty), real($elty), ElInt, ElInt, PseudospecCtrl{real($elty)}),
                    A.obj, invNormMap.obj, center, realWidth, imagWidth, realSize, imagSize, psCtrl)
                err == 0 || throw(ElError(err))
                return invNormMap
            end

        end
    end
end


text:
.class public Lorg/cf/smalivm/SamePackageClass;
.super Ljava/lang/Object;

.method public static dummyMethod()V
    .locals 0
    return-void
.end method


text:
'use strict';

function save() {
	const path2 = document.getElementById('path').value;
	const protocol2 = document.getElementById('protocol').value;
	const host2 = document.getElementById('host').value;
	const port2 = document.getElementById('port').value;
	const interf2 = document.getElementById('interf').value;
	const token2 = document.getElementById('token').value;
	browser.storage.local.set({
		path2,
		protocol2,
		host2,
		port2,
		interf2,
		token2,
	}, () => {
		const status = document.getElementById('status');
		status.textContent = browser.i18n.getMessage("OP_saveComplete");
		setTimeout(() => {
			status.textContent = '';
		}, 750);
	});
}

function restore() {
	browser.storage.local.get(Object.assign(config.command.s2), prefs => {
		document.getElementById('path').value = prefs.path2;
		document.getElementById('protocol').value = prefs.protocol2;
		document.getElementById('host').value = prefs.host2;
		document.getElementById('port').value = prefs.port2;
		document.getElementById('interf').value = prefs.interf2;
		document.getElementById('token').value = prefs.token2;
	});
	document.querySelectorAll('[data-message]').forEach(n => {
		n.textContent = browser.i18n.getMessage(n.dataset.message);
	});
	document.body.style = "direction: " + browser.i18n.getMessage("direction");
}

document.addEventListener('DOMContentLoaded', restore);
document.getElementById('save').addEventListener('click', save);


text:
@implementation DIEToolkit
+ (NSDictionary *)deviceParams {
    NSUUID *uuid = [NSUUID UUID];

    UIDevice *device = [UIDevice currentDevice];
    return @{
        @"deviceKey":uuid.UUIDString,
        @"brand":@"Apple",
        @"channelId":@"App Store",
        @"model":device.model,
        @"os":device.systemName,
        @"osv":device.systemVersion,
        @"timestamp":@"1443513638"
    };
}

+ (NSDictionary *)appParams {
    return @{
        @"apiKey":@"yuki_ios",
        @"auth1":@"aeb64759231cc3ab7d771273a555e4fb",
        @"auth2":@"662a595550f05ed39f99367f2052f928",
        @"version":@"2.4.5"
    };
}

+ (NSDictionary *)fullParams:(NSDictionary *)params {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict addEntriesFromDictionary:[self deviceParams]];
    [dict addEntriesFromDictionary:[self appParams]];
    if (params) {
        [dict addEntriesFromDictionary:params];
    }

    return dict;
}

+ (NSString *)apiWithPath:(NSString *)path {
    return [kDIEHost stringByAppendingPathComponent:path];
}

+ (NSString *)categoryApi {
    return [self apiWithPath:kDIECategoryApi];
}

+ (NSString *)categoryDetailApiWithId:(NSString *)categoryId {
    NSString *path = [NSString stringWithFormat:kDIECategoryDetailApi, categoryId];
    return [self apiWithPath:path];
}

+ (NSString *)userAnimeApiWithId:(NSString *)animeId {
    NSString *path = [kDIEUserAnimeApi stringByAppendingPathComponent:animeId];
    return [self apiWithPath:path];
}

+ (NSString *)episodeApiWithAnimeId:(NSString *)animeId index:(NSInteger)index {
    NSString *path = [NSString stringWithFormat:kDIEEpisodeApi, animeId, index];
    return [self apiWithPath:path];
}

+ (NSString *)videoApiWithVideoId:(NSString *)videoId {
    NSString *path = [NSString stringWithFormat:kDIEVideoApi, videoId];
    return [self apiWithPath:path];
}
@end


text:
layout: event
categories:
  - events
links:
title: Civic User Testing Group
speakers:
 - Daniel X. O'Neil, Smart Chicago Collaborative
date: 2014-12-9T18:00:00-06:00
event_id: 135
youtube_id: 0y3_KbhjjZg
sponsor: GitHub
tags:
 - 'user testing'
published: true
---

[Daniel X. O'Neil](https://twitter.com/danxoneil) of the [Smart Chicago Collaborative](http://www.smartchicagocollaborative.org/) will talk about the [Civic User Testing Group](http://www.cutgroup.org/), a set of regular Chicago residents who get paid to test out civic apps.

Dan and his colleagues will give a brief presentation about the [impetus behind the program](http://www.cutgroupbook.org/2-origins/) and cover its three essential [components](http://www.cutgroupbook.org/3-components/): UX testing, digital skills, and community engagement. They'll also talk about how the Civic Tech community here in Chicago can get involved in this program which is being implemented all over the country.

---

#### Leadership Council Meeting #8

Will have our **8th** open leadership discussion at **8pm** after the group breakouts get started. This meeting is for anyone who is interested in being involved in running the hack night, taking on new projects, or doing training sessions.

If you'd like to bring up a topic, [add it to the agenda](https://docs.google.com/document/d/1B1f9-NxCH0C1sbwQ_S21a0X8tuQHRP0CihR35E2NunE/edit#).


text:
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Net;
using System.Text;
using System.Threading;

namespace Microsoft.Live.UnitTest
{
    public class TestAuthClient : IAuthClient
    {
        internal static readonly string ClientId = "0000000068034211";
        internal static readonly string[] Scopes = { "wl.signin", "wl.basic", "wl.contacts_create", "wl.skydrive_update", "wl.offline_access" };
        internal static readonly string FakeAccessToken = "EwAoAq1DBAAUlbRWyAJjK5w968Ru3Cyt%2f6GvwXwAAcyf0TMN5dgEkwdsowUJexmnpsFxiChUj%2fZ0B9X170rNu5CIp7X1RtjH%2fVs7f8uYKwZQvUNY8YLj5bed1LPIaEJuRUKUMQuTz8DyMP%2fUQJqaYRp5Hv3GeiP%2bSQjBX1g8oNs6JjWIdL%2fyQfp9AaRwPrn8stOpXIsboC6r7OeGmq4VBAkuw8RcgK9gZ9hhabXydBZkZMWwNWm35WQp0n8KICti%2bo%2bXh5w5eSTRtTjSqFjCO4hQvc2TnJPSC2SZhHlPt9SI%2b8JDNFx5grXSJmTcRovAcv78FMl4Bn%2fnr8VhSf5l57nbTDMjotd7X6F7si67Vurp%2bYobOOiMIOl1XZLlOw0DZgAACN%2fHShbm3Eu%2f%2bABDFUGBR4adKUdg1V74deM9hgf92OCqlkVeVNggE5GuyCUS4%2bUGoGiE8vAUQk56hYvvnOYBWsocCMiK38ZE0g%2fpvB7k0cGonS8H6xlLP3tsE1w75mJCHNDp0HG2ZJ2J41HmxD0ko5PwCMXKoOAR%2f7AXgVgpZhf4%2bF1QogVVx6Zh87dQkkJmRN%2fv%2bIZUEtB7hdL4PV2m8eOSaGan3BxbEU%2b8zjTNkRhxA43JhcJXgw8ZE9yO%2f5aN0lq8yCUAGlByl80WLqdvFgaMMMWIP9QW07Y0ndmd7MbxXaIOVJ6SrF589QlreaKjfTN11lCkRdEK8IecNxo7BoIdKwAA";
        internal static readonly string FakeOldAccessToken = "EwAoAq1DBAAUlbRWyAJjK5w968Ru3Cyt%2f6GvwXwAAcyf0TMN5dgEkwdsowUJexmnpsFxiChUj%2fZ0B9X170rNu5CIp7X1RtjH%2fVs7f8uYKwZQvUNY8YLj5bed1LPIaEJuRUKUMQuTz8DyMP%2fUQJqaYRp5Hv3GeiP%2bSQjBX1g8oNs6JjWIdL%2fyQfp9AaRwPrn8stOpXIsboC6r7OeGmq4VBAkuw8RcgK9gZ9hhabXydBZkZMWwNWm35WQp0n8KICti%2bo%2bXh5w5eSTRtTjSqFjCO4hQvc2TnJPSC2SZhHlPt9SI%2b8JDNFx5grXSJmTcRovAcv78FMl4Bn%2fnr8VhSf5l57nbTDMjotd7X6F7si67Vurp%2bYobOOiMIOl1XZLlOw0DZgAACN%2fHShbm3Eu%2f%2bABDFUGBR4adKUdg1V74deM9hgf92OCqlkVeVNggE5GuyCUS4%2bUGoGiE8vAUQk56hYvvnOYBWsocCMiK38ZE0g%2fpvB7k0cGonS8H6xlLP3tsE1w75mJCHNDp0HG2ZJ2J41HmxD0ko5PwCMXKoOAR%2f7AXgVgpZhf4%2bF1QogVVx6Zh87dQkkJmRN%2fv%2bIZUEtB7hdL4PV2m8eOSaGan3BxbEU%2b8zjTNkRhxA43JhcJXgw8ZE9yO%2f5aN0lq8yCUAGlByl80WLqdvFgaMMMWIP9QW07Y0ndmd7MbxXaIOVJ6SrF589QlreaKjfTN11lCkRdEK8IecNxo7BoIdKwAA";
        internal static readonly string FakeAuthenticationToken = "eyJhbGciOiJIUzI1NiIsICJ0eXAiOiJKV1QiLCAia2lkIjoiMCJ9.eyJ2ZXIiOjEsICJpc3MiOiJ1cm46d2luZG93czpsaXZlaWQiLCAiZXhwIjoxMzEyMzk4Mzg3LCAiYXVkIjoiIiwgInVpZCI6IjYzOTJkNjY2MWMxZTcwZGJjMWNkYTkzNDAzMGYzNzdlIiwgInVybjptaWNyb3NvZnQ6YXBwdXJpIjoiIn0.6eGQWz4KRlqN8J8qT2SyoeEkJb7pXOM8iu9EiGCKrUo";
        internal static readonly string FakeOldAuthenticationToken = "eyJhbGciOiJIUzI1NiIsICJ0eXAiOiJKV1QiLCAia2lkIjoiMCJ9.eyJ2ZXIiOjEsICJpc3MiOiJ1cm46d2luZG93czpsaXZlaWQiLCAiZXhwIjoxMzEyMzk4Mzg3LCAiYXVkIjoiIiwgInVpZCI6IjYzOTJkNjY2MWMxZTcwZGJjMWNkYTkzNDAzMGYzNzdlIiwgInVybjptaWNyb3NvZnQ6YXBwdXJpIjoiIn0.6eGQWz4KRlqN8J8qT2SyoeEkJb7pXOM8iu9EiGCKrUo";
        internal static readonly string FakeRefreshToken = "!gs!YAAAHgA%24100g7orI2CFb!RP7anoV5yNid2uXJ3dJelO1x6kF!rX5uqWn8bZlehcu!NUQTFYZW4Vw2sUYzG02ntkYF3jv2FQi3G!lp9VhE13CuFf6gsYJgqKqhxAb!Rq92AOWQKNYWuLUzv1wmgyUYTxeo8jEAnEVY8K0GTK0TkzGv8nZhvwRo%24";
        internal static readonly string FakeOldRefreshToken = "!gs!YAAAHgA%2419BHQKzTYCfskuAGvrXdmgP3ymnllRH4TTQY8vp2QSNG6vkIhh0*Xa6KIokuXyoYNmRs*!ec*ZaPb1x6IpBSX6N5pX3lGrmqXGoMmZC7C1SahWVx9YIiIhR6fp1Q!Z2jhCaFAqwAdEsXJ6okPNczcHWUs63wHAT75lQyAi460iTig%24";

        private readonly LiveAuthClient liveAuthClient;

        public TestAuthClient(LiveAuthClient liveAuthClient)
        {
            this.liveAuthClient = liveAuthClient;
        }

        public bool CanSignOut
        {
            get
            {
                return true;
            }
        }

        public void AuthenticateAsync(string clientId, string scopes, bool silent, Action<string, Exception> callback)
        {
            if (silent)
            {
                if (callback != null)
                {
                    ThreadPool.QueueUserWorkItem(
                        (object state) =>
                        {
                            callback(GenerateUserUnknownResponse(this.liveAuthClient.RedirectUrl), null);
                        });
                }

                return;
            }
            else
            {
                string consentUrl = this.liveAuthClient.BuildLoginUrl(scopes, false);

                if (callback != null)
                {
                    ThreadPool.QueueUserWorkItem(
                        (object state) =>
                        {
                            Uri consentUri = new Uri(consentUrl, UriKind.Absolute);
                            var parameters = Helpers.ParseQueryString(consentUri.Query);
                            string responseData = GenerateValidResponse(parameters);

                            callback(responseData, null);
                        });
                }

                return;
            }
        }

        public LiveConnectSession LoadSession(LiveAuthClient authClient)
        {
            var appData = IsolatedStorageSettings.ApplicationSettings;
            LiveConnectSession session = null;
            if (appData.Values.Count > 0)
            {
                session = new LiveConnectSession(authClient);

                if (appData.Contains(AuthConstants.RefreshToken))
                {
                    session.RefreshToken = appData[AuthConstants.RefreshToken] as string;
                }
            }

            return session;
        }

        public void SaveSession(LiveConnectSession session)
        {
            if (session != null)
            {
                var appData = IsolatedStorageSettings.ApplicationSettings;
                if (!string.IsNullOrEmpty(session.RefreshToken))
                {
                    if (appData.Contains(AuthConstants.RefreshToken))
                    {
                        appData.Remove(AuthConstants.RefreshToken);
                    }
                    appData.Add(AuthConstants.RefreshToken, session.RefreshToken);
                }

                appData.Save();
            }
        }

        public void CloseSession()
        {
            var appData = IsolatedStorageSettings.ApplicationSettings;
            if (appData.Values.Count > 0)
            {
                if (appData.Contains(AuthConstants.RefreshToken))
                {
                    appData.Remove(AuthConstants.RefreshToken);
                }

                appData.Save();
            }
        }

        internal static string GenerateValidResponse(IDictionary<string, string> parameters)
        {
            StringBuilder sb = new StringBuilder(HttpUtility.UrlDecode(parameters[AuthConstants.Callback]));
            sb = sb.Append("#").Append(AuthConstants.AccessToken).Append("=").Append(TestAuthClient.FakeAccessToken);
            sb = sb.Append("&").Append(AuthConstants.TokenType).Append("=").Append("bearer");
            sb = sb.Append("&").Append(AuthConstants.AuthenticationToken).Append("=").Append(TestAuthClient.FakeAuthenticationToken);
            sb = sb.Append("&").Append(AuthConstants.ExpiresIn).Append("=").Append("3600");
            sb = sb.Append("&").Append(AuthConstants.Scope).Append("=").Append(parameters[AuthConstants.Scope]);

            return sb.ToString();
        }

        private static string GenerateUserUnknownResponse(string redirectUrl)
        {
            StringBuilder sb = new StringBuilder(redirectUrl);
            sb = sb.Append("#").Append(AuthConstants.Error).Append("=").Append(AuthErrorCodes.UnknownUser);

            return sb.ToString();
        }
    }
}


text:
'use strict';

const lodash = require('lodash');
const path = require('path');

const defaultConfigs = ['./dumpinator.conf.js', './dumpinator.json'];

class Config {
  constructor(options) {
    options = options || {};
    this.routes = [];
    this.reporter = options.reporter || {
      cli: { noColor: options.noColor }
    };

    if (options.htmlReport) {
      this.reporter.html = {
        output: path.join(process.cwd(), 'dumpinator-report')
      };
    }

    if (!lodash.isUndefined(options.rateLimit)) {
      options.rateLimit = parseInt(options.rateLimit, 10);
      if (!lodash.isInteger(options.rateLimit) || options.rateLimit < 1) {
        throw new Error('Arguments invalid: [rateLimit] must be an integer > 0!');
      }
    }

    if (options.tag && !(lodash.isString(options.tag) || lodash.isNumber(options.tag))) {
      throw new Error('Arguments invalid: [tag] must be a string or number!');
    }

    this.rateLimit = options.rateLimit || 1;
    this.tag = options.tag || null;
    this.verbose = options.verbose || false;
    this.noColor = options.noColor || process.env.isTTY;
    this.gitTags = options.gitTags || null;
  }

  load(file) {
    // TODO: Rename file(name) related variables here
    let filenames = [];
    let conf;

    if (file) {
      filenames.push(file.substr(0, 1) === '/' ? file : path.join(process.cwd(), file));
    } else {
      filenames = defaultConfigs.map(defaultFile => path.join(process.cwd(), defaultFile));
    }

    filenames.some((configFile) => {
      try {
        conf = require(configFile); // eslint-disable-line global-require,import/no-dynamic-require
        return !!conf;
      } catch (e) {
        if (e.code === 'ENOENT' && e.path === configFile) {
          throw new Error(`Cannot find config "${configFile}"`);
        }

        throw new Error(`Parse error of config file: "${configFile}"\n${e.stack}`);
      }
    });

    this.parseJSON(conf);
  }

  parseJSON(input) {
    this.setDefaults(lodash.get(input, 'defaults'), {});
    const routes = lodash.get(input, 'routes', []);

    lodash.each(input, (val, key) => {
      if (!lodash.includes(['options', 'defaults', 'routes', 'before', 'after', 'beforeEach', 'afterEach', 'gitTags', 'transform'], key)) {
        throw new Error(`Config invalid: Key "${key}" is not allowed!`);
      }
    });

    if (!Array.isArray(routes)) {
      throw new Error('Config invalid: "routes" must be an array!');
    }

    routes.forEach((route, i) => {
      if (!lodash.isString(route) && !lodash.isObject(route)) {
        throw new Error(`Config invalid: "routes[${i}]" (${route.url || route}) must must be a string or an object!`);
      }

      if (lodash.isString(route)) {
        route = { left: { url: route }, right: { url: route } };
      }

      this.addRoute(route);
    });

    if (input.before) {
      this.before = input.before;
    }

    if (input.beforeEach) {
      this.beforeEach = input.beforeEach;
    }

    if (input.after) {
      this.after = input.after;
    }

    if (input.afterEach) {
      this.afterEach = input.afterEach;
    }
  }

  setDefaults(defaults) {
    if (defaults && !lodash.isObject(defaults)) {
      throw new Error('Config invalid: "defaults" must be an object!');
    }

    lodash.each(defaults, (val, key) => {
      if (!lodash.includes(['left', 'right', 'rateLimit', 'status', 'ignoreBody', 'ignoreHeader'], key)) {
        throw new Error(`Config invalid: Key "${key}" in "defaults" is not allowed!`);
      }
    });

    this.defaults = defaults;
  }

  getRoutes() {
    const routes = [];

    for (let i = 0; i < this.routes.length; i += 1) {
      routes.push({
        url: this.routes[i].left.url,
        id: this.routes[i].id,
        side: 'left',
        name: this.routes[i].name,
        header: this.routes[i].left.header,
        query: this.routes[i].left.query,
        ignoreBody: this.routes[i].left.ignoreBody,
        ignoreHeader: this.routes[i].left.ignoreHeader,
        status: this.routes[i].left.status
      }, {
        url: this.routes[i].right.url,
        id: this.routes[i].id,
        side: 'right',
        name: this.routes[i].name,
        header: this.routes[i].right.header,
        query: this.routes[i].right.query,
        ignoreBody: this.routes[i].right.ignoreBody,
        ignoreHeader: this.routes[i].right.ignoreHeader,
        status: this.routes[i].right.status
      });
    }

    return routes;
  }

  toJSON() {
    return this.routes;
  }

  validate(validateionData) {
    const ALLOWED_SITE_KEYS = [
      'method',
      'hostname', 'url', 'header',
      'query', 'body', 'status', 'transform'
    ];

    const ALLOWED_ROUTE_KEYS = [
      'name', 'tag', 'before', 'after', 'ignoreBody', 'ignoreHeader', 'transform'
    ];

    const ALLOWED_METHODS = [
      'GET', 'POST', 'PUT', 'DELETE',
      'HEAD', 'CHECKOUT', 'COPY',
      'LOCK', 'MERGE', 'MKACTIVITY',
      'MKCOL', 'MOVE', 'M-SEARCH',
      'NOTIFY', 'OPTIONS', 'PATCH',
      'PURGE', 'REPORT', 'SEARCH',
      'SUBSCRIBE', 'TRACE',
      'UNLOCK', 'UNSUBSCRIBE'
    ];

    const regAllowedSiteKeys = new RegExp(`^${ALLOWED_SITE_KEYS.join('|')}$`);
    const regAllowedRouteKeys = new RegExp(`^${ALLOWED_ROUTE_KEYS.concat(ALLOWED_SITE_KEYS).join('|')}$`);
    const regAllowedMethods = new RegExp(`^${ALLOWED_METHODS.join('|')}$`);

    const validate = (obj, level) => {
      Object.keys(obj).forEach((key) => {
        if ((key === 'left' || key === 'right') && !level) {
          validate(obj[key], key);
          return;
        }

        const reg = level ? regAllowedSiteKeys : regAllowedRouteKeys;
        if (!reg.test(key)) {
          throw new Error(`Invalid configuration! ${key} not allowed in ${level || 'base'} route`);
        }
      });
    };

    ['method', 'left.method', 'right.method'].forEach((key) => {
      const value = lodash.get(validateionData, key);
      if (value && !regAllowedMethods.test(value)) {
        throw new Error(`Invalid configuration! ${value} is not a valid method in ${key}`);
      }
    });

    validate(validateionData);
  }

  addRoute(route) {
    lodash.each(this.defaults, (value, key) => {
      if (key === 'left' || key === 'right') {
        route[key] = Object.assign({}, route[key], value);
        return;
      }

      if (!(key in route)) {
        route[key] = this.defaults[key];
      }
    });

    this.validate(route);

    const newRoute = {
      left: {
        url: this.getUrl(route, 'left'),
        method: this.getParam(route, 'left', 'method', 'GET')
      },
      right: {
        url: this.getUrl(route, 'right'),
        method: this.getParam(route, 'right', 'method', 'GET')
      }
    };

    // set optional test properties
    ['before', 'after', 'name', 'ignoreBody', 'ignoreHeader'].forEach((prop) => {
      if (prop in route) {
        newRoute[prop] = route[prop];
      }
    });

    // set optional site properties
    ['status', 'header', 'query', 'body', 'transform'].forEach((prop) => {
      if (!newRoute.left[prop]) {
        const param = this.getParam(route, 'left', prop);
        if (param) {
          newRoute.left[prop] = param;
        }
      }

      if (!newRoute.right[prop]) {
        const param = this.getParam(route, 'right', prop);
        if (param) {
          newRoute.right[prop] = param;
        }
      }
    });

    // set optional route only properties
    ['before', 'after'].forEach((prop) => {
      if (!newRoute.left[prop]) {
        const param = this.getSiteParam(route, 'left', prop);
        if (param) {
          newRoute.left[prop] = param;
        }
      }

      if (!newRoute.right[prop]) {
        const param = this.getSiteParam(route, 'right', prop);
        if (param) {
          newRoute.right[prop] = param;
        }
      }
    });

    this.routes.push(newRoute);

    return newRoute;
  }

  getParam(route, site, param, defaultValue) {
    if (route[site] && route[site][param]) {
      return route[site][param];
    }

    return route[param] || defaultValue;
  }

  getSiteParam(route, site, param, defaultValue) {
    if (route[site] && route[site][param]) {
      return route[site][param];
    }

    return defaultValue;
  }

  getUrl(route, site) {
    let routeHost;
    let routePath;

    if (route[site] && route[site].hostname) {
      routeHost = route[site].hostname.replace(/\/$/, '');
    } else if (route.hostname) {
      routeHost = route.hostname.replace(/\/$/, '');
    }

    if (route[site] && route[site].url) {
      routePath = route[site].url.replace(/^\//, '');
    } else if (route.url) {
      routePath = route.url.replace(/^\//, '');
    }

    if (routeHost && !routePath) {
      return routeHost;
    }

    return routeHost ? `${routeHost}/${routePath}` : routePath;
  }
}

module.exports = Config;


text:
package com.pme.exe;

/**
 * Date: Mar 31, 2006
 * Time: 10:40:56 PM
 */
public class ImageDataDirectory extends Bin.Structure {
  public ImageDataDirectory(String name) {
    super(name);
    addMember( new DWord( "VirtualAddress" ) );
    addMember( new DWord( "Size" ) );
  }
  public ImageDataDirectory( ){
    this("");
  }
}


text:
import Numeric.LinearAlgebra
import Graphics.Plot
import System.Directory(doesFileExist)
import System.Process(system)
import Control.Monad(when)

type Vec = Vector Double
type Mat = Matrix Double

-- Vector with the mean value of the columns of a matrix
mean a = constant (recip . fromIntegral . rows $ a) (rows a) <> a

-- covariance matrix of a list of observations stored as rows
cov x = (trans xc <> xc) / fromIntegral (rows x - 1)
    where xc = x - asRow (mean x)

type Stat = (Vec, [Double], Mat)
-- 1st and 2nd order statistics of a dataset (mean, eigenvalues and eigenvectors of cov)
stat :: Mat -> Stat
stat x = (m, toList s, trans v) where
    m = mean x
    (s,v) = eigSH' (cov x)

-- creates the compression and decompression functions from the desired reconstruction
-- quality and the statistics of a data set
pca :: Double -> Stat -> (Vec -> Vec , Vec -> Vec)
pca prec (m,s,v) = (encode,decode)
  where
    encode x = vp <> (x - m)
    decode x = x <> vp + m
    vp = takeRows n v
    n = 1 + (length $ fst $ span (< (prec'*sum s)) $ cumSum s)
    cumSum = tail . scanl (+) 0.0
    prec' = if prec <=0.0 || prec >= 1.0
                then error "the precision in pca must be 0<prec<1"
                else prec

shdigit :: Vec -> IO ()
shdigit v = imshow (reshape 28 (-v))

-- shows the effect of a given reconstruction quality on a test vector
test :: Stat -> Double -> Vec -> IO ()
test st prec x = do
    let (pe,pd) = pca prec st
    let y = pe x
    print $ dim y
    shdigit (pd y)

main = do
    ok <- doesFileExist ("mnist.txt")
    when (not ok)  $ do
        putStrLn "\nTrying to download test datafile..."
        system("wget -nv http://dis.um.es/~alberto/material/sp/mnist.txt.gz")
        system("gunzip mnist.txt.gz")
        return ()
    m <- loadMatrix "mnist.txt"
    let xs = takeColumns (cols m -1) m
    let x = toRows xs !! 4  -- an arbitrary test vector
    shdigit x
    let st = stat xs
    test st 0.90 x
    test st 0.50 x


text:
"""Test interact and interactive."""

#-----------------------------------------------------------------------------
#  Copyright (C) 2014 The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

from __future__ import print_function

from collections import OrderedDict

import nose.tools as nt
import IPython.testing.tools as tt

# from IPython.core.getipython import get_ipython
from IPython.html import widgets
from IPython.html.widgets import interact, interactive, Widget, interaction
from IPython.utils.py3compat import annotate

#-----------------------------------------------------------------------------
# Utility stuff
#-----------------------------------------------------------------------------

class DummyComm(object):
    comm_id = 'a-b-c-d'
    def send(self, *args, **kwargs):
        pass

    def close(self, *args, **kwargs):
        pass

_widget_attrs = {}
displayed = []

def setup():
    _widget_attrs['comm'] = Widget.comm
    Widget.comm = DummyComm()
    _widget_attrs['_ipython_display_'] = Widget._ipython_display_
    def raise_not_implemented(*args, **kwargs):
        raise NotImplementedError()
    Widget._ipython_display_ = raise_not_implemented

def teardown():
    for attr, value in _widget_attrs.items():
        setattr(Widget, attr, value)

def f(**kwargs):
    pass

def clear_display():
    global displayed
    displayed = []

def record_display(*args):
    displayed.extend(args)

#-----------------------------------------------------------------------------
# Actual tests
#-----------------------------------------------------------------------------

def check_widget(w, **d):
    """Check a single widget against a dict"""
    for attr, expected in d.items():
        if attr == 'cls':
            nt.assert_is(w.__class__, expected)
        else:
            value = getattr(w, attr)
            nt.assert_equal(value, expected,
                "%s.%s = %r != %r" % (w.__class__.__name__, attr, value, expected)
            )

def check_widgets(container, **to_check):
    """Check that widgets are created as expected"""
    # build a widget dictionary, so it matches
    widgets = {}
    for w in container.children:
        widgets[w.description] = w

    for key, d in to_check.items():
        nt.assert_in(key, widgets)
        check_widget(widgets[key], **d)

def test_single_value_string():
    a = u'hello'
    c = interactive(f, a=a)
    w = c.children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        description='a',
        value=a,
    )

def test_single_value_bool():
    for a in (True, False):
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(w,
            cls=widgets.CheckboxWidget,
            description='a',
            value=a,
        )

def test_single_value_dict():
    for d in [
        dict(a=5),
        dict(a=5, b='b', c=dict),
    ]:
        c = interactive(f, d=d)
        w = c.children[0]
        check_widget(w,
            cls=widgets.DropdownWidget,
            description='d',
            values=d,
            value=next(iter(d.values())),
        )

def test_single_value_float():
    for a in (2.25, 1.0, -3.5):
        c = interactive(f, a=a)
        w = c.children[0]
        check_widget(w,
            cls=widgets.FloatSliderWidget,
            description='a',
            value=a,
            min= -a if a > 0 else 3*a,
            max= 3*a if a > 0 else -a,
            step=0.1,
            readout=True,
        )

def test_single_value_int():
    for a in (1, 5, -3):
        c = interactive(f, a=a)
        nt.assert_equal(len(c.children), 1)
        w = c.children[0]
        check_widget(w,
            cls=widgets.IntSliderWidget,
            description='a',
            value=a,
            min= -a if a > 0 else 3*a,
            max= 3*a if a > 0 else -a,
            step=1,
            readout=True,
        )

def test_list_tuple_2_int():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,1))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,-1))
    for min, max in [ (0,1), (1,10), (1,2), (-5,5), (-20,-19) ]:
        c = interactive(f, tup=(min, max), lis=[min, max])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.IntSliderWidget,
            min=min,
            max=max,
            step=1,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)

def test_list_tuple_3_int():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,-1))
    for min, max, step in [ (0,2,1), (1,10,2), (1,100,2), (-5,5,4), (-100,-20,4) ]:
        c = interactive(f, tup=(min, max, step), lis=[min, max, step])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.IntSliderWidget,
            min=min,
            max=max,
            step=step,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)

def test_list_tuple_2_float():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1.0,1.0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(0.5,-0.5))
    for min, max in [ (0.5, 1.5), (1.1,10.2), (1,2.2), (-5.,5), (-20,-19.) ]:
        c = interactive(f, tup=(min, max), lis=[min, max])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.FloatSliderWidget,
            min=min,
            max=max,
            step=.1,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)

def test_list_tuple_3_float():
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2,0.0))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(-1,-2,1.))
    with nt.assert_raises(ValueError):
        c = interactive(f, tup=(1,2.,-1.))
    for min, max, step in [ (0.,2,1), (1,10.,2), (1,100,2.), (-5.,5.,4), (-100,-20.,4.) ]:
        c = interactive(f, tup=(min, max, step), lis=[min, max, step])
        nt.assert_equal(len(c.children), 2)
        d = dict(
            cls=widgets.FloatSliderWidget,
            min=min,
            max=max,
            step=step,
            readout=True,
        )
        check_widgets(c, tup=d, lis=d)

def test_list_tuple_str():
    values = ['hello', 'there', 'guy']
    first = values[0]
    dvalues = OrderedDict((v,v) for v in values)
    c = interactive(f, tup=tuple(values), lis=list(values))
    nt.assert_equal(len(c.children), 2)
    d = dict(
        cls=widgets.DropdownWidget,
        value=first,
        values=dvalues
    )
    check_widgets(c, tup=d, lis=d)

def test_list_tuple_invalid():
    for bad in [
        (),
        (5, 'hi'),
        ('hi', 5),
        ({},),
        (None,),
    ]:
        with nt.assert_raises(ValueError):
            print(bad) # because there is no custom message in assert_raises
            c = interactive(f, tup=bad)

def test_defaults():
    @annotate(n=10)
    def f(n, f=4.5, g=1):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSliderWidget,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSliderWidget,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSliderWidget,
            value=1,
        ),
    )

def test_default_values():
    @annotate(n=10, f=(0, 10.), g=5, h={'a': 1, 'b': 2}, j=['hi', 'there'])
    def f(n, f=4.5, g=1, h=2, j='there'):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSliderWidget,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatSliderWidget,
            value=4.5,
        ),
        g=dict(
            cls=widgets.IntSliderWidget,
            value=5,
        ),
        h=dict(
            cls=widgets.DropdownWidget,
            values={'a': 1, 'b': 2},
            value=2
        ),
        j=dict(
            cls=widgets.DropdownWidget,
            values={'hi':'hi', 'there':'there'},
            value='there'
        ),
    )

def test_default_out_of_bounds():
    @annotate(f=(0, 10.), h={'a': 1}, j=['hi', 'there'])
    def f(f='hi', h=5, j='other'):
        pass

    c = interactive(f)
    check_widgets(c,
        f=dict(
            cls=widgets.FloatSliderWidget,
            value=5.,
        ),
        h=dict(
            cls=widgets.DropdownWidget,
            values={'a': 1},
            value=1,
        ),
        j=dict(
            cls=widgets.DropdownWidget,
            values={'hi':'hi', 'there':'there'},
            value='hi',
        ),
    )

def test_annotations():
    @annotate(n=10, f=widgets.FloatTextWidget())
    def f(n, f):
        pass

    c = interactive(f)
    check_widgets(c,
        n=dict(
            cls=widgets.IntSliderWidget,
            value=10,
        ),
        f=dict(
            cls=widgets.FloatTextWidget,
        ),
    )

def test_priority():
    @annotate(annotate='annotate', kwarg='annotate')
    def f(kwarg='default', annotate='default', default='default'):
        pass

    c = interactive(f, kwarg='kwarg')
    check_widgets(c,
        kwarg=dict(
            cls=widgets.TextWidget,
            value='kwarg',
        ),
        annotate=dict(
            cls=widgets.TextWidget,
            value='annotate',
        ),
    )

@nt.with_setup(clear_display)
def test_decorator_kwarg():
    with tt.monkeypatch(interaction, 'display', record_display):
        @interact(a=5)
        def foo(a):
            pass
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.IntSliderWidget,
        value=5,
    )

@nt.with_setup(clear_display)
def test_decorator_no_call():
    with tt.monkeypatch(interaction, 'display', record_display):
        @interact
        def foo(a='default'):
            pass
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        value='default',
    )

@nt.with_setup(clear_display)
def test_call_interact():
    def foo(a='default'):
        pass
    with tt.monkeypatch(interaction, 'display', record_display):
        ifoo = interact(foo)
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        value='default',
    )

@nt.with_setup(clear_display)
def test_call_interact_kwargs():
    def foo(a='default'):
        pass
    with tt.monkeypatch(interaction, 'display', record_display):
        ifoo = interact(foo, a=10)
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.IntSliderWidget,
        value=10,
    )

@nt.with_setup(clear_display)
def test_call_decorated_on_trait_change():
    """test calling @interact decorated functions"""
    d = {}
    with tt.monkeypatch(interaction, 'display', record_display):
        @interact
        def foo(a='default'):
            d['a'] = a
            return a
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        value='default',
    )
    # test calling the function directly
    a = foo('hello')
    nt.assert_equal(a, 'hello')
    nt.assert_equal(d['a'], 'hello')

    # test that setting trait values calls the function
    w.value = 'called'
    nt.assert_equal(d['a'], 'called')

@nt.with_setup(clear_display)
def test_call_decorated_kwargs_on_trait_change():
    """test calling @interact(foo=bar) decorated functions"""
    d = {}
    with tt.monkeypatch(interaction, 'display', record_display):
        @interact(a='kwarg')
        def foo(a='default'):
            d['a'] = a
            return a
    nt.assert_equal(len(displayed), 1)
    w = displayed[0].children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        value='kwarg',
    )
    # test calling the function directly
    a = foo('hello')
    nt.assert_equal(a, 'hello')
    nt.assert_equal(d['a'], 'hello')

    # test that setting trait values calls the function
    w.value = 'called'
    nt.assert_equal(d['a'], 'called')

def test_fixed():
    c = interactive(f, a=widgets.fixed(5), b='text')
    nt.assert_equal(len(c.children), 1)
    w = c.children[0]
    check_widget(w,
        cls=widgets.TextWidget,
        value='text',
        description='b',
    )


text:
<?php

namespace simplator\medialib\controllers;

use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use simplator\medialib\models\Entity;

/**
 * PictureController implements the CRUD actions for Picture model.
 */
class FileController extends Controller
{
	public function actionDownload($path)
	{
        if ($path!=='/')
        {
            $item = Entity::find()->where([
                'path'=>$path
            ])->one();
        }
        else
        {
            $item = new Entity([
                'id' => 0,
                'ownerid' => \Yii::$app->user->id,
                'entityid' => 0,
                'type' => 'folder',
                'isfolder' => 1,
                'path' => '/',
                'name' => 'root'
            ]);
        }

        if (!$item)
            die("not found");

		//var_dump(Url::toRoute(['/medialib/direct', 'storage' => $item->entity->storage, 'fn'=>$item->entity->path]));

		return $this->redirect(['/medialib/direct', 'storage' => $item->entity->storage, 'fn'=>$item->entity->path]);

		die();
        return $folder;

	}

    /**
     * Displays a single Picture model.
     * @param integer $id
     * @return mixed
     */
    public function actionPicture($id, $size='full')
    {
        if (($model = Picture::findOne($id)) === null)
		    throw new NotFoundHttpException('The requested page does not exist.');
        if (!$model)
			$model=new Picture();
		$this->redirect($model->directlink($size), 301);
    }

    public function actionCreate($a=';l')
    {
        var_dump($GLOBALS);
    }
}


text:
<?php

defined('PROTECTED_PATH') || define('PROTECTED_PATH', realpath(__DIR__ . '/../'));

//set include path and setup default autoload
set_include_path(get_include_path() . PATH_SEPARATOR . implode(PATH_SEPARATOR, [
	PROTECTED_PATH . '/libs',
	PROTECTED_PATH . '/project',
]));

//fix autoload for unit tests:
spl_autoload_register(function($className) {
	$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
	$filePath = $className . '.php';

	@include_once $filePath;
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>FSF.qsort</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

qsort

главная |
стандартные функции

Функция FSF.qsort осуществляет сортировку данных с использованием алгоритма QuickSort.

void WINAPI qsort(
  void *Base,
  size_t NElem,
  size_t Width,
  int (WINAPI *fcmp)(const void *, const void *, void *),
  void *UserParam
);

Параметры

Base

Указатель на начало данных для сортировки.

NElem

Количество сортируемых данных.

Width

Размер одного элемента сортируемых данных.

fcmp

Функция сравнения двух элементов. В процессе сортировки вызывается каждый раз, когда необходимо сравнить пару элементов данных.
    Функция сравнения fcmp должна иметь декларацию WINAPI.

    fcmp получает три аргумента - elem1, elem2 (которые являются указателями на данные) и userparam (то, что было передано в функцию в качестве параметра UserParam),
    и возвращает результат:

*elem1 < *elem2	- fcmp возвращает целое меньше 0

*elem1 == *elem2	- fcmp возвращает 0

*elem1  > *elem2	- fcmp возвращает целое больше 0

UserParam

Указатель на пользовательские данные, которые функция qsort будет передавать в функцию сравнения fcmp в качестве третьего параметра.

Возвращаемое значение

Нет.

Примечание

Функция реализует нестабильную сортировку. Иными словами, порядок элементов, равных с точки зрения функции сравнения, не определён и может меняться при повторных сортировках уже отсортированного массива.

Смотрите также:

FSF.bsearch


text:
/// <reference path="../../../../angular2/typings/node/node.d.ts" />

var file = require('sdk/io/file');
var {Cc, Ci, Cu} = require("chrome");

class Profiler {
  private _profiler;
  constructor() { this._profiler = Cc["@mozilla.org/tools/profiler;1"].getService(Ci.nsIProfiler); }

  start(entries, interval, features) {
    this._profiler.StartProfiler(entries, interval, features, features.length);
  }

  stop() { this._profiler.StopProfiler(); }
  getProfileData() { return this._profiler.getProfileData(); }
}

function saveToFile(savePath: string, body: string) {
  var textWriter = file.open(savePath, 'w');
  textWriter.write(body);
  textWriter.close();
}

function forceGC() {
  Cu.forceGC();
  var os = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
  os.notifyObservers(null, "child-gc-request", null);
}

var profiler = new Profiler();
function startProfiler() {
  profiler.start(/* = profiler memory */ 10000000, 1, ['leaf', 'js', "stackwalk", 'gc']);
};
function stopAndRecord(filePath) {
  var profileData = profiler.getProfileData();
  profiler.stop();
  saveToFile(filePath, JSON.stringify(profileData, null, 2));
};

var mod = require("sdk/page-mod");
var data = require("sdk/self").data;
mod.PageMod({
  include: ['*'],
  contentScriptFile: data.url("installed_script.js"),
  onAttach: worker => {
    worker.port.on('startProfiler', () => startProfiler());
    worker.port.on('stopAndRecord', filePath => stopAndRecord(filePath));
    worker.port.on('forceGC', () => forceGC());
  }
});