text:
/*
 ONOS GUI -- Topo View -- Topo Model Service - Unit Tests
 */
describe('factory: view/topo/topoModel.js', function() {
    var $log, fs, rnd, tms;

    // stop random numbers from being quite so random
    var mockRandom = {
        // mock spread returns s + 1
        spread: function (s) {
            return s + 1;
        },
        // mock random dimension returns d / 2 - 1
        randDim: function (d) {
            return d/2 - 1;
        },
        mock: 'yup'
    };

    // to mock out the [lng,lat] <=> [x,y] transformations, we will
    // add/subtract 2000, 3000 respectively:
    //   lng:2005 === x:5,   lat:3004 === y:4

    var mockProjection = function (lnglat) {
        return [lnglat[0] - 2000, lnglat[1] - 3000];
    };

    mockProjection.invert = function (xy) {
        return [xy[0] + 2000, xy[1] + 3000];
    };

    // our test devices and hosts:
    var dev1 = {
            'class': 'device',
            id: 'dev1',
            x: 17,
            y: 27,
            online: true
        },
        dev2 = {
            'class': 'device',
            id: 'dev2',
            x: 18,
            y: 28,
            online: true
        },
        host1 = {
            'class': 'host',
            id: 'host1',
            x: 23,
            y: 33,
            cp: {
                device: 'dev1',
                port: 7
            },
            ingress: 'dev1/7-host1'
        },
        host2 = {
            'class': 'host',
            id: 'host2',
            x: 24,
            y: 34,
            cp: {
                device: 'dev0',
                port: 0
            },
            ingress: 'dev0/0-host2'
        };

    // our test api
    var api = {
        projection: function () { return mockProjection; },
        network: {
            nodes: [dev1, dev2, host1, host2],
            links: [],
            lookup: {dev1: dev1, dev2: dev2, host1: host1, host2: host2},
            revLinkToKey: {}
        },
        restyleLinkElement: function () {},
        removeLinkElement: function () {}
    };

    // our test dimensions and well known locations..
    var dim = [20, 40],
        randLoc = [9, 19],          // random location using randDim(): d/2-1
        randHostLoc = [40, 50],     // host "near" random location
                                    //  given that 'nearDist' = 15
                                    //  and spread(15) = 16
                                    //  9 + 15 + 16 = 40; 19 + 15 + 16 = 50
        nearDev1 = [48,58],         // [17+15+16, 27+15+16]
        dev1Loc = [17,27],
        dev2Loc = [18,28],
        host1Loc = [23,33],
        host2Loc = [24,34];

    // implement some custom matchers...
    beforeEach(function () {
        jasmine.addMatchers({
            toBePositionedAt: function () {
                return {
                    compare: function (actual, xy) {
                        var result = {},
                            actCoord = [actual.x, actual.y];

                        result.pass = (actual.x === xy[0]) && (actual.y === xy[1]);

                        if (result.pass) {
                            // for negation with ".not"
                            result.message = 'Expected [' + actCoord +
                            '] NOT to be positioned at [' + xy + ']';
                        } else {
                            result.message = 'Expected [' + actCoord +
                            '] to be positioned at [' + xy + ']';
                        }
                        return result;
                    }
                }
            },
            toHaveEndPoints: function () {
                return {
                    compare: function (actual, xy1, xy2) {
                        var result = {};

                        result.pass = (actual.source.x === xy1[0]) &&
                                      (actual.source.y === xy1[1]) &&
                                      (actual.target.x === xy2[0]) &&
                                      (actual.target.y === xy2[1]);

                        if (result.pass) {
                            // for negation with ".not"
                            result.message = 'Expected ' + actual +
                            ' NOT to have endpoints [' + xy1 + ']-[' + xy2 + ']';
                        } else {
                            result.message = 'Expected ' + actual +
                            ' to have endpoints [' + xy1 + ']-[' + xy2 + ']';
                        }
                        return result;
                    }
                }
            },
            toBeFixed: function () {
                return {
                    compare: function (actual) {
                        var result = {
                            pass: actual.fixed
                        };
                        if (result.pass) {
                            result.message = 'Expected ' + actual +
                            ' NOT to be fixed!';
                        } else {
                            result.message = 'Expected ' + actual +
                            ' to be fixed!';
                        }
                        return result;
                    }
                }
            }
        });
    });

    beforeEach(module('ovTopo', 'onosUtil', 'onosNav', 'onosLayer', 'onosWidget', 'onosMast'));

    beforeEach(function () {
        module(function ($provide) {
            $provide.value('RandomService', mockRandom);
        });
    });

    beforeEach(inject(function (_$log_, FnService, RandomService, TopoModelService) {
        $log = _$log_;
        fs = FnService;
        rnd = RandomService;
        tms = TopoModelService;
        tms.initModel(api, dim);
    }));

    it('should install the mock random service', function () {
        expect(rnd.mock).toBe('yup');
        expect(rnd.spread(4)).toBe(5);
        expect(rnd.randDim(8)).toBe(3);
    });

    it('should install the mock projection', function () {
        expect(tms.coordFromLngLat({lng: 2005, lat: 3004})).toEqual([5,4]);
        expect(tms.lngLatFromCoord([5,4])).toEqual([2005,3004]);
    });

    it('should define TopoModelService', function () {
        expect(tms).toBeDefined();
    });

    xit('should define api functions', function () {
        expect(fs.areFunctions(tms, [
            'initModel', 'newDim', 'destroyModel',
            'positionNode', 'createDeviceNode', 'createHostNode',
            'createHostLink', 'createLink',
            'coordFromLngLat', 'lngLatFromCoord',
            'findLink', 'findLinkById', 'findDevices',
            'findAttachedHosts', 'findAttachedLinks', 'findBadLinks'
        ])).toBeTruthy();
    });

    // === unit tests for positionNode()

    it('should position a node using meta x/y', function () {
        var node = {
            metaUi: { x:37, y:48 }
        };
        tms.positionNode(node);
        expect(node).toBePositionedAt([37,48]);
        expect(node).toBeFixed();
    });

    it('should position a node by translating lng/lat', function () {
        var node = {
            location: {
                type: 'lnglat',
                lng: 2008,
                lat: 3009
            }
        };
        tms.positionNode(node);
        expect(node).toBePositionedAt([8,9]);
        expect(node).toBeFixed();
    });

    it('should position a device with no location randomly', function () {
        var node = { 'class': 'device' };
        tms.positionNode(node);
        expect(node).toBePositionedAt(randLoc);
        expect(node).not.toBeFixed();
    });

    it('should position a device randomly even if x/y set', function () {
        var node = { 'class': 'device', x: 1, y: 2 };
        tms.positionNode(node);
        expect(node).toBePositionedAt(randLoc);
        expect(node).not.toBeFixed();
    });

    it('should NOT reposition a device randomly on update', function () {
        var node = { 'class': 'device', x: 1, y: 2 };
        tms.positionNode(node, true);
        expect(node).toBePositionedAt([1,2]);
        expect(node).not.toBeFixed();
    });

    it('should position a host close to its device', function () {
        var node = { 'class': 'host', cp: { device: 'dev1' } };
        tms.positionNode(node);

        // note: nearDist is 15; spread(15) adds 16; dev1 at [17,27]

        expect(node).toBePositionedAt(nearDev1);
        expect(node).not.toBeFixed();
    });

    it('should randomize host with no assoc device', function () {
        var node = { 'class': 'host', cp: { device: 'dev0' } };
        tms.positionNode(node);

        // note: no device gives 'rand loc' [9,19]
        //       nearDist is 15; spread(15) adds 16

        expect(node).toBePositionedAt(randHostLoc);
        expect(node).not.toBeFixed();
    });

    // === unit tests for createDeviceNode()

    it('should create a basic device node', function () {
        var node = tms.createDeviceNode({ id: 'foo' });
        expect(node).toBePositionedAt(randLoc);
        expect(node).not.toBeFixed();
        expect(node.class).toEqual('device');
        expect(node.svgClass).toEqual('node device');
        expect(node.id).toEqual('foo');
    });

    it('should create device node with type', function () {
        var node = tms.createDeviceNode({ id: 'foo', type: 'cool' });
        expect(node).toBePositionedAt(randLoc);
        expect(node).not.toBeFixed();
        expect(node.class).toEqual('device');
        expect(node.svgClass).toEqual('node device cool');
        expect(node.id).toEqual('foo');
    });

    it('should create online device node with type', function () {
        var node = tms.createDeviceNode({ id: 'foo', type: 'cool', online: true });
        expect(node).toBePositionedAt(randLoc);
        expect(node).not.toBeFixed();
        expect(node.class).toEqual('device');
        expect(node.svgClass).toEqual('node device cool online');
        expect(node.id).toEqual('foo');
    });

    it('should create online device node with type and lng/lat', function () {
        var node = tms.createDeviceNode({
            id: 'foo',
            type: 'yowser',
            online: true,
            location: {
                type: 'lnglat',
                lng: 2048,
                lat: 3096
            }
        });
        expect(node).toBePositionedAt([48,96]);
        expect(node).toBeFixed();
        expect(node.class).toEqual('device');
        expect(node.svgClass).toEqual('node device yowser online');
        expect(node.id).toEqual('foo');
    });

    // === unit tests for createHostNode()

    it('should create a basic host node', function () {
        var node = tms.createHostNode({ id: 'bar', cp: { device: 'dev0' } });
        expect(node).toBePositionedAt(randHostLoc);
        expect(node).not.toBeFixed();
        expect(node.class).toEqual('host');
        expect(node.svgClass).toEqual('node host endstation');
        expect(node.id).toEqual('bar');
    });

    it('should create a host with type', function () {
        var node = tms.createHostNode({
            id: 'bar',
            type: 'classic',
            cp: { device: 'dev1' }
        });
        expect(node).toBePositionedAt(nearDev1);
        expect(node).not.toBeFixed();
        expect(node.class).toEqual('host');
        expect(node.svgClass).toEqual('node host classic');
        expect(node.id).toEqual('bar');
    });

    // === unit tests for createHostLink()

    it('should create a basic host link', function () {
        var link = tms.createHostLink(host1);
        expect(link.source).toEqual(host1);
        expect(link.target).toEqual(dev1);
        expect(link).toHaveEndPoints(host1Loc, dev1Loc);
        expect(link.key).toEqual('dev1/7-host1');
        expect(link.class).toEqual('link');
        expect(link.type()).toEqual('hostLink');
        expect(link.linkWidth()).toEqual(1);
        expect(link.online()).toEqual(true);
    });

    it('should return null for failed endpoint lookup', function () {
        spyOn($log, 'error');
        var link = tms.createHostLink(host2);
        expect(link).toBeNull();
        expect($log.error).toHaveBeenCalledWith(
            'Node(s) not on map for link:\n[dst] "dev0" missing'
        );
    });

    // === unit tests for createLink()

    it('should return null for missing endpoints', function () {
        spyOn($log, 'error');
        var link = tms.createLink({src: 'dev0', dst: 'dev00'});
        expect(link).toBeNull();
        expect($log.error).toHaveBeenCalledWith(
            'Node(s) not on map for link:\n[src] "dev0" missing\n[dst] "dev00" missing'
        );
    });

    xit('should create a basic link', function () {
        var linkData = {
                src: 'dev1',
                dst: 'dev2',
                id: 'baz',
                type: 'zoo',
                online: true,
                linkWidth: 1.5
            },
            link = tms.createLink(linkData);
        expect(link.source).toEqual(dev1);
        expect(link.target).toEqual(dev2);
        expect(link).toHaveEndPoints(dev1Loc, dev2Loc);
        expect(link.key).toEqual('baz');
        expect(link.class).toEqual('link');
        expect(link.fromSource).toBe(linkData);
        expect(link.type()).toEqual('zoo');
        expect(link.online()).toEqual(true);
        expect(link.linkWidth()).toEqual(1.5);
    });

    // TODO: more unit tests for additional functions....
});


text:
import unittest
from app.main.common.RedisHelper import RedisHelper
from app.main.jobs.giftCardSchedule import GiftCardSchedule

class RedisHelperTestCase(unittest.TestCase):
    def test_redis_srandmember(self):
        redishelper = RedisHelper()
        aList = redishelper.redis_srandmember('liuqiang-sets', 4)
        print(aList)

    def test_redis_sadd_spop(self):
        redishelper = RedisHelper()
        mylist = []
        mylist.append("1")
        mylist.append("2")
        mylist.append("3")
        mylist.append("4")
        mylist.append("5")
        mylist.append("6")
        mylist.append("7")
        mylist.append("8")
        redishelper = RedisHelper()
        redishelper.redis_sadd('liuqiang-sets', mylist)

        self.assertEqual(8, redishelper.redis_scard('liuqiang-sets'))
        print(redishelper.redis_scard('liuqiang-sets'))

        aList = redishelper.redis_spop_str('liuqiang-sets', 4)
        print(aList)
        self.assertEqual(4, len(aList))
        aList = redishelper.redis_spop_str('liuqiang-sets', 4)
        print(aList)
        self.assertEqual(4, len(aList))

    def test_redis_incr_get(self):
        redisHelper = RedisHelper()
        redisHelper.redis_set('index1', 0)
        self.assertEqual(10, redisHelper.redis_inc('index1', 10))
        self.assertEqual(10, int(redisHelper.redis_get('index1')))

    def test_get_flag(self):
        redisHelper = RedisHelper()
        if redisHelper.redis_get('liuqiang_flag'):
            print("there is something")
        else:
            print("there is None")

    def test_set_flag(self):
        redisHelper = RedisHelper()
        redisHelper.redis_set_expire('liuqiang_flag', 1, 5)

    def test_schedule(self):
        giftCardSchedule = GiftCardSchedule()
        giftCardSchedule.test()

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

redpajama_set_name: RedPajamaGithub


text:
package im.actor

import akka.sbt.AkkaKernelPlugin
import akka.sbt.AkkaKernelPlugin.{ Dist, distBootClass, distJvmOptions, outputDirectory }
import sbt.Keys._
import sbt._
import spray.revolver.RevolverPlugin._
import com.trueaccord.scalapb.{ScalaPbPlugin => PB}

object Build extends sbt.Build {
  val Version = "1.0.2038"
  val ScalaVersion = "2.11.7"

  lazy val buildSettings =
    Defaults.coreDefaultSettings ++
      Seq(
        version := Version,
        scalaVersion := ScalaVersion,
        crossPaths := false,
        organizationHomepage := Some(url("https://actor.im"))
      )

  lazy val compilerWarnings = Seq(
    "-Ywarn-dead-code",
    "-Ywarn-infer-any",
    "-Ywarn-numeric-widen"
  )

  lazy val defaultScalacOptions = Seq(
    "-target:jvm-1.8",
    "-Ybackend:GenBCode",
    "-Ydelambdafy:method",
    "-Yopt:l:classpath",
    "-encoding", "UTF-8",
    "-deprecation",
    "-unchecked",
    "-feature",
    "-language:higherKinds",
    "-Xfatal-warnings",
    "-Xlint",
    "-Xfuture"
  ) ++ compilerWarnings

  lazy val defaultSettings =
    buildSettings ++ Formatting.formatSettings ++
      PB.protobufSettings ++ Seq(
        //PB.javaConversions in PB.protobufConfig := true,
        libraryDependencies += "com.trueaccord.scalapb" %% "scalapb-runtime" % "0.5.9" % PB.protobufConfig,
        PB.includePaths in PB.protobufConfig ++= Seq(
          file("actor-commons-api/src/main/protobuf"),
          file("actor-push/src/main/protobuf")
        )
      ) ++
      Seq(
        initialize ~= { _ =>
          if (sys.props("java.specification.version") != "1.8")
            sys.error("Java 8 is required for this project.")
        },
        resolvers ++= Resolvers.seq,
        scalacOptions in Compile ++= defaultScalacOptions,
        javaOptions ++= Seq("-Dfile.encoding=UTF-8"),
        javacOptions ++= Seq("-source", "1.8", "-target", "1.8", "-Xlint:unchecked", "-Xlint:deprecation"),
        fork in Test := true
      )

  lazy val root = Project(
    "actor-server",
    file("."),
    settings =
      defaultSettings ++
        AkkaKernelPlugin.distSettings ++
        Revolver.settings ++
        Seq(
          libraryDependencies ++= Dependencies.root,
          distJvmOptions in Dist := "-server -Xms256M -Xmx1024M",
          distBootClass in Dist := "im.actor.server.Main",
          outputDirectory in Dist := file("target/dist"),
          Revolver.reStartArgs := Seq("im.actor.server.Main"),
          mainClass in Revolver.reStart := Some("im.actor.server.Main"),
          mainClass in Compile := Some("im.actor.server.Main"),
          autoCompilerPlugins := true,
          scalacOptions in(Compile, doc) ++= Seq(
            "-groups",
            "-implicits",
            "-diagrams"
          )
        )
  ).settings(net.virtualvoid.sbt.graph.Plugin.graphSettings: _*)
    .dependsOn(actorRunner)
    .aggregate(
      actorCommonsApi,
      actorCommonsBase,
//      actorDashboard,
      actorEmail,
      actorEnrich,
      actorFrontend,
      actorHttpApi,
      actorLlectro,
      actorModels,
      actorNotifications,
      actorPersist,
      actorPresences,
      actorSession,
      actorRpcApi,
      actorTests,
      actorUtils,
      actorUtilsCache,
      actorUtilsHttp
    )

  lazy val actorRunner = Project(
    id = "actor-runner",
    base = file("actor-runner"),
    settings = defaultSettings
  ).dependsOn(
      actorActivation,
      actorCommonsBase,
      actorEnrich,
      actorEmail,
      actorFrontend,
      actorHttpApi,
      actorRpcApi,
      actorNotifications,
      actorOAuth
    )

  lazy val actorActivation = Project(
    id = "actor-activation",
    base = file("actor-activation"),
    settings = defaultSettings ++
      Seq(
        libraryDependencies ++= Dependencies.activation,
        scalacOptions in Compile := (scalacOptions in Compile).value.filterNot(_ == "-Ywarn-unused-import")
      )
  ).dependsOn(actorEmail, actorSms)

  lazy val actorCommonsApi = Project(
    id = "actor-commons-api",
    base = file("actor-commons-api"),
    settings =
      defaultSettings ++
        SbtActorApi.settings ++
        Seq(
          libraryDependencies ++= Dependencies.commonsApi,
          scalacOptions in Compile := (scalacOptions in Compile).value.filterNot(_ == "-Ywarn-unused-import")
        )
  ).dependsOn(actorCommonsBase, actorPersist, actorCodecs)

  lazy val actorCommonsBase = Project(
    id = "actor-commons-base",
    base = file("actor-commons-base"),
    settings =
      defaultSettings ++
        Seq(
          libraryDependencies ++= Dependencies.commonsBase
        )
  )

  lazy val actorCQRS = Project(
    id = "actor-cqrs",
    base = file("actor-cqrs"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.cqrs
    )
  ).dependsOn(actorModels, actorPush % PB.protobufConfig, actorPush, actorSocial, actorUtils, actorUtilsCache)
    .aggregate(actorPush)

  lazy val actorEmail = Project(
    id = "actor-email",
    base = file("actor-email"),
    settings = defaultSettings ++
      Seq(
        libraryDependencies ++= Dependencies.email
      )
  )

  lazy val actorEnrich = Project(
    id = "actor-enrich",
    base = file("actor-enrich"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.enrich
    )
  ).dependsOn(actorRpcApi, actorUtils)

  lazy val actorHttpApi = Project(
    id = "actor-http-api",
    base = file("actor-http-api"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.httpApi
    )
  ).dependsOn(actorCQRS, actorPersist, actorTls)

  lazy val actorLlectro = Project(
    id = "actor-llectro",
    base = file("actor-llectro"),
    settings = defaultSettings ++
      Seq(
        libraryDependencies ++= Dependencies.llectro
      )
  ).dependsOn(actorPersist)

  lazy val actorOAuth = Project(
    id = "actor-oauth",
    base = file("actor-oauth"),
    settings = defaultSettings ++
      Seq(
        libraryDependencies ++= Dependencies.oauth
      )
  ).dependsOn(actorPersist)

  lazy val actorSession = Project(
    id = "actor-session",
    base = file("actor-session"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.session
    )
  ).dependsOn(actorPersist, actorCodecs, actorCommonsApi, actorRpcApi, actorPush)

  lazy val actorSessionMessages = Project(
    id = "actor-session-messages",
    base = file("actor-session-messages"),
    settings = defaultSettings ++ Seq(libraryDependencies ++= Dependencies.sessionMessages)
  ).dependsOn(actorCommonsBase, actorCommonsApi)

  lazy val actorPush = Project(
    id = "actor-push",
    base = file("actor-push"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.push
    )
  ).dependsOn(actorCodecs, actorCommonsApi, actorCommonsBase, actorPersist, actorPresences, actorSessionMessages, actorUtils)

  lazy val actorPresences = Project(
    id = "actor-presences",
    base = file("actor-presences"),
    settings = defaultSettings ++ Seq(libraryDependencies ++= Dependencies.presences)
  ).dependsOn(actorPersist)

  lazy val actorRpcApi = Project(
    id = "actor-rpc-api",
    base = file("actor-rpc-api"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.rpcApi
    )
  ).dependsOn(
      actorActivation,
      actorCodecs,
      actorCommonsApi,
      actorCQRS,
      actorLlectro,
      actorHttpApi, // FIXME: remove this dependency
      actorOAuth,
      actorPersist,
      actorPresences,
      actorPush,
      actorSessionMessages,
      actorSms,
      actorSocial,
      actorUtils,
      actorUtilsHttp,
      actorVoximplant)

  lazy val actorSms = Project(
    id = "actor-sms",
    base = file("actor-sms"),
    settings = defaultSettings ++ Seq(libraryDependencies ++= Dependencies.sms)
  ).dependsOn(actorUtils)

  lazy val actorSocial = Project(
    id = "actor-social",
    base = file("actor-social"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.social
    )
  ).dependsOn(actorPersist)

  lazy val actorTls = Project(
    id = "actor-tls",
    base = file("actor-tls"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.tls
    )
  )

  lazy val actorFrontend = Project(
    id = "actor-frontend",
    base = file("actor-frontend"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.frontend
    )
  ).dependsOn(actorCommonsApi, actorSessionMessages, actorSession, actorTls)

  lazy val actorCodecs = Project(
    id = "actor-codecs",
    base = file("actor-codecs"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.codecs
    )
  ).dependsOn(actorModels)

  lazy val actorModels = Project(
    id = "actor-models",
    base = file("actor-models"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.models
    )
  )

  lazy val actorPersist = Project(
    id = "actor-persist",
    base = file("actor-persist"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.persist
    )
  ).dependsOn(actorModels)

//  lazy val actorDashboard = Project(
//    id = "actor-dashboard",
//    base = file("actor-dashboard"),
//    settings = defaultSettings ++ Seq(
//      scalacOptions in Compile := (scalacOptions in Compile).value.filterNot(_ == "-Ywarn-unused-import"),
//      javaOptions := javaOptions.value.filterNot(_.startsWith("-Dscalac.patmat.analysisBudget")),
//      libraryDependencies ++= Dependencies.dashboard
//    )
//  )
//    .enablePlugins(PlayScala)
//    .dependsOn(actorPersist, actorUtils)

  lazy val actorNotifications = Project(
    id = "actor-notifications",
    base = file("actor-notifications"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.notifications
    )
  )
    .dependsOn(actorModels, actorPersist, actorSms, actorUtils)

  lazy val actorUtils = Project(
    id = "actor-utils",
    base = file("actor-utils"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.utils
    )
  )
    .dependsOn(actorCommonsApi, actorModels, actorPersist)

  lazy val actorUtilsCache = Project(
    id = "actor-utils-cache",
    base = file("actor-utils-cache"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.utilsCache
    )
  )

  lazy val actorUtilsHttp = Project(
    id = "actor-utils-http",
    base = file("actor-utils-http"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.utilsHttp
    )
  )

  lazy val actorVoximplant = Project(
    id = "actor-voximplant",
    base = file("actor-voximplant"),
    settings = defaultSettings ++ Seq(
      libraryDependencies ++= Dependencies.voximplant
    )
  )

  lazy val actorTests = Project(
    id = "actor-tests",
    base = file("actor-tests"),
    settings = defaultSettings ++ Testing.settings ++ Seq(
      libraryDependencies ++= Dependencies.tests
    ))
    .configs(Configs.all: _*)
    .dependsOn(
      actorActivation,
      actorCodecs,
      actorCommonsApi,
      actorCommonsBase,
//      actorDashboard,
      actorEmail,
      actorEnrich,
      actorFrontend,
      actorHttpApi,
      actorNotifications,
      actorOAuth,
      actorPersist,
      actorPush,
      actorRpcApi,
      actorRunner,
      actorSession
    )
}


text:
layout: post
title:  "Angular Tips #7"
date:   2017-12-23 10:00:00 +0200
categories: Angular
---
# Angular : Création du composant

La troisième partie est la création de la classe représentant le composant.

```typescript
export class MyComponent {
 private _mymemberofclass: type;
 public get mymemberofclass():type{
   return this._mymemberofclass
 }
 public set mymemberofclass(myaffectation:type){
  this._mymemberofclass = myaffectation
 }
 constructor(){ }
}
```

Certains mots clés se rapproche du langage Java.

Le mot clé

```typescript
export
```

fait référence au mot clé

```typescript
public
```

en java. Ils ont une signification assez proche.
Lorsqu'on déclare une classe public en Java, celle ci est visible de l'ensemble des autres classes.
En TypeScript, ou en JavaScript en suivant la norme ES6, cette objet est utilisable en utilisant le mot clé

```typescript
inport
```

Le mot clé

```typescript
class
```

fait référence au mot clé

```typescript
 class
```

en java. Ils ont la même signification.
On représente un objet qui possèdera des propriétés ainsi que des méthodes. (attribut d'une classe ainsi que les accesseurs)

```typescript
Interface
```

, et

```typescript
Type
```

sont d'autres types de mot clé existant et que l'on peut utiliser.

Le mot clé
```typescript
constructor
```

 est la méthode permettant de créer un objet du type de la classe. Ici seront initialisés l'ensemble des propretiés par défaut d'un objet.

Le méthode ou le mot clé

```typescript
get
```

 &

```typescript
 set
 ```
  apparaisse, sont des méthodes qui permette d'accéder, et de modifier les valeurs d'un attribut de classe. Il s'agit des getter/setter classique Java. Une petite différence notamenet dans l'écriture, le type de retour de la méthode se trouve après les () à l'inverse du Java ou cela se trouve au début


text:
package hello.controller;

import hello.controller.persistence.WorldsMongodbRepository;
import hello.domain.World;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import com.strategicgains.restexpress.Request;
import com.strategicgains.restexpress.Response;

public class MongodbController
{
	// Database details.
	private static final int DB_ROWS = 10000;

	private WorldsMongodbRepository worldRepo;

	public MongodbController(WorldsMongodbRepository worldsRepository)
	{
		super();
		this.worldRepo = worldsRepository;
	}

	public Object read(Request request, Response response)
	{
    // Get the count of queries to run.
    int count = 1;
    try
    {
      count = Integer.parseInt(request.getHeader("queries"));

      // Bounds check.
      if (count > 500)
      {
        count = 500;
      }
      if (count < 1)
      {
        count = 1;
      }
    }
    catch(NumberFormatException nfexc)
    {
      // do nothing
    }

		// Fetch some rows from the database.
		final World[] worlds = new World[count];
		final Random random = ThreadLocalRandom.current();

		for (int i = 0; i < count; i++)
		{
			worlds[i] = worldRepo.find(random.nextInt(DB_ROWS) + 1);
		}

		if (count == 1)
		{
			return worlds[0];
		}

		return worlds;
	}
}


text:
/// <reference path="base.js"/>
/// <reference path="bounding_box.js"/>
/// <reference path="color.js"/>
/// <reference path="object.js"/>
/// <reference path="point.js"/>
/// <reference path="rectangle.js"/>
/// <reference path="shadow.js"/>
/// <reference path="transform.js"/>

/**
 * An abstract class that renders shapes and objects to an HTMLCanvasElement
 * object.
 * @param {HTMLCanvasElement} canvas
 * @param {number} width
 * @param {number} height
 * @constructor
 */
createjs.Renderer = function(canvas, width, height) {
  /// <param type="HTMLCanvasElement" name="canvas"/>
  /// <param type="number" name="width"/>
  /// <param type="number" name="height"/>
  /**
   * The output <canvas> element.
   * @type {HTMLCanvasElement}
   * @private
   */
  this.canvas_ = canvas;

  /**
   * The current width of the output <canvas> element.
   * @type {number}
   * @private
   */
  this.width_ = width;

  /**
   * The current height of the output <canvas> element.
   * @type {number}
   * @private
   */
  this.height_ = height;
};

/**
 * The output <canvas> element.
 * @type {HTMLCanvasElement}
 * @private
 */
createjs.Renderer.prototype.canvas_ = null;

/**
 * The current width of the output <canvas> element.
 * @type {number}
 * @private
 */
createjs.Renderer.prototype.width_ = 0;

/**
 * The current height of the output <canvas> element.
 * @type {number}
 * @private
 */
createjs.Renderer.prototype.height_ = 0;

/**
 * Whether this renderer applies workarounds for Android browsers.
 * @type {number}
 * @private
 */
createjs.Renderer.prototype.useAndroidWorkarounds_ = -1;

/**
 * The ratio of a point in this renderer to one of CSS.
 * @type {createjs.Point}
 * @private
 */
createjs.Renderer.prototype.cssRatio_ = null;

/**
 * Composite operations.
 * @enum {number}
 */
createjs.Renderer.Composition = {
  SOURCE_OVER: 0,
  SOURCE_ATOP: 1,
  SOURCE_IN: 2,
  SOURCE_OUT: 3,
  DESTINATION_OVER: 4,
  DESTINATION_ATOP: 5,
  DESTINATION_IN: 6,
  DESTINATION_OUT: 7,
  LIGHTER: 8,
  COPY: 9,
  XOR: 10,
  DARKER: 11,
  MULTIPLY: 12,
  MASK: 15
};

/**
 * Mask methods.
 * @enum {number}
 */
createjs.Renderer.Mask = {
  SCISSOR: 1,
  COMPOSE: 2,
  SHOW: 3,
  HIDE: 4
};

/**
 * Color formats used by WebGLTextures.
 * @enum {number}
 */
createjs.Renderer.Format = {
  RGBA8888: 0,
  RGBA4444: 1
};

/**
 * Extensions.
 * @enum {number}
 */
createjs.Renderer.Extension = {
  VIDEO: 1 << 0
};

/**
 * Returns the composition ID associated with the specified name.
 * @param {string} name
 * @return {number}
 */
createjs.Renderer.getCompositionKey = function(name) {
  var KEYS = {
    'source-over': createjs.Renderer.Composition.SOURCE_OVER,
    'source-atop': createjs.Renderer.Composition.SOURCE_ATOP,
    'source-in': createjs.Renderer.Composition.SOURCE_IN,
    'source-out': createjs.Renderer.Composition.SOURCE_OUT,
    'destination-over': createjs.Renderer.Composition.DESTINATION_OVER,
    'destination-atop': createjs.Renderer.Composition.DESTINATION_ATOP,
    'destination-in': createjs.Renderer.Composition.DESTINATION_IN,
    'destination-out': createjs.Renderer.Composition.DESTINATION_OUT,
    'lighter': createjs.Renderer.Composition.LIGHTER,
    'copy': createjs.Renderer.Composition.COPY,
    'xor': createjs.Renderer.Composition.XOR,
    'darker': createjs.Renderer.Composition.DARKER
  };
  return KEYS[name] || createjs.Renderer.Composition.SOURCE_OVER;
};

/**
 * Returns the composition name from the specified ID.
 * @param {number} key
 * @return {string}
 */
createjs.Renderer.getCompositionName = function(key) {
  var NAMES = [
    'source-over',
    'source-atop',
    'source-in',
    'source-out',
    'destination-over',
    'destination-atop',
    'destination-in',
    'destination-out',
    'lighter',
    'copy',
    'xor',
    'darker',
    'multiply'
];
  return NAMES[key];
};

/**
 * An inner class used by createjs.Renderer objects to clip RenderObject
 * objects.
 * @param {createjs.Transform} transform
 * @param {createjs.BoundingBox} rectangle
 * @param {createjs.BoundingBox} box
 * @param {number} method
 * @param {number} composition
 * @param {createjs.Renderer.RenderObject} shape
 * @constructor
 */
createjs.Renderer.Clip =
    function(transform, rectangle, box, method, composition, shape) {
  /// <param type="createjs.Transform" name="transform"/>
  /// <param type="createjs.BoundingBox" name="rectangle"/>
  /// <param type="createjs.BoundingBox" name="box"/>
  /// <param type="number" name="method"/>
  /// <param type="number" name="composition"/>
  /// <param type="createjs.Renderer.RenderObject" name="shape"/>
  /**
   * An affine transformation applied to a clipping rectangle.
   * @const {createjs.Transform}
   * @private
   */
  this.transform_ = transform;

  /**
   * A clipping rectangle in the local coordinate.
   * @const {createjs.Rectangle}
   * @private
   */
  this.rectangle_ = new createjs.Rectangle(rectangle.getLeft(),
                                           rectangle.getTop(),
                                           rectangle.getWidth(),
                                           rectangle.getHeight());

  /**
   * A clipping rectangle in the global coordinate.
   * @const {createjs.BoundingBox}
   * @private
   */
  this.box_ = createjs.Renderer.Clip.cloneBox(box);

  /**
   * A method used for applying this clip to a render object.
   * rectangle.
   * @const {number}
   * @private
   */
  this.method_ = method;

  /**
   * A composition operation used in rendering the clipped image.
   * @const {number}
   * @private
   */
  this.composition_ = composition;

  /**
   * A render object that renders this clip.
   * @const {createjs.Renderer.RenderObject}
   * @private
   */
  this.shape_ =
      (method > createjs.Renderer.Mask.SCISSOR) ? shape : null;
};

/**
 * Returns a clone of the specified box.
 * @param {createjs.BoundingBox} box
 * @return {createjs.BoundingBox}
 */
createjs.Renderer.Clip.cloneBox = function(box) {
  /// <param type="createjs.BoundingBox" name="box"/>
  /// <returns type="createjs.BoundingBox"/>
  var clone = new createjs.BoundingBox();
  clone.minX = createjs.truncate(box.minX) + 1;
  clone.minY = createjs.truncate(box.minY);
  clone.maxX = createjs.truncate(box.maxX);
  clone.maxY = createjs.truncate(box.maxY);
  return clone;
};

/**
 * Returns the affine transformation.
 * @return {createjs.Transform}
 * @const
 */
createjs.Renderer.Clip.prototype.getTransform = function() {
  /// <returns type="createjs.Transform"/>
  return this.transform_;
};

/**
 * Returns the clipping rectangle.
 * @return {createjs.Rectangle}
 * @const
 */
createjs.Renderer.Clip.prototype.getRectangle = function() {
  /// <returns type="createjs.Rectangle"/>
  return this.rectangle_;
};

/**
 * Returns the bounding box.
 * @return {createjs.BoundingBox}
 * @const
 */
createjs.Renderer.Clip.prototype.getBox = function() {
  /// <returns type="createjs.BoundingBox"/>
  return this.box_;
};

/**
 * Returns the clipping method.
 * @return {number}
 * @const
 */
createjs.Renderer.Clip.prototype.getMethod = function() {
  /// <returns type="number"/>
  // Disable this clip when it is invisible to avoid a crash in rendering an
  // invisible shape. (A tween may set an empty shape to this mask.)
  if (this.shape_ && !this.shape_.isVisible()) {
    return 0;
  }
  return this.method_;
};

/**
 * Returns whether a renderer has to compose this clip to a render object.
 * @return {boolean}
 * @const
 */
createjs.Renderer.Clip.prototype.isCompose = function() {
  /// <returns type="boolean"/>
  return this.method_ == createjs.Renderer.Mask.COMPOSE;
};

/**
 * Returns whether a renderer should show a render object without applying this
 * clip.
 * @return {boolean}
 * @const
 */
createjs.Renderer.Clip.prototype.isShow = function() {
  /// <returns type="boolean"/>
  return this.method_ == createjs.Renderer.Mask.SHOW;
};

/**
 * Returns whether this clip can use its bounding box as a scissor box.
 * @return {number}
 * @const
 */
createjs.Renderer.Clip.prototype.getComposition = function() {
  /// <returns type="number"/>
  return this.composition_;
};

/**
 * Returns a display object used as a mask.
 * @return {createjs.Renderer.RenderObject}
 * @const
 */
createjs.Renderer.Clip.prototype.getShape = function() {
  /// <returns type="createjs.Renderer.RenderObject"/>
  return this.shape_;
};

/**
 * An interface used by a renderer object to draw objects registered with the
 * paintObject() method.
 * @interface
 */
createjs.Renderer.RenderObject = function() {};

/**
 * Returns whether this object needs a redraw.
 * @param {createjs.BoundingBox} box
 * @return {boolean}
 */
createjs.Renderer.RenderObject.prototype.isDirtyObject = function(box) {
  /// <returns type="createjs.BoundingBox"/>
};

/**
 * Returns the bounding box of this object in the global coordinate system.
 * @return {createjs.BoundingBox}
 */
createjs.Renderer.RenderObject.prototype.getRenderBox = function() {
  /// <returns type="createjs.BoundingBox"/>
};

/**
 * Returns a createjs.Renderer.Clip object associated with this object.
 * @return {createjs.Renderer.Clip}
 */
createjs.Renderer.RenderObject.prototype.getClip = function() {
  /// <returns type="createjs.Renderer.Clip"/>
};

/**
 * Starts painting this object.
 * @param {createjs.Renderer} renderer
 */
createjs.Renderer.RenderObject.prototype.beginPaintObject =
    function(renderer) {
  /// <param type="createjs.Renderer" name="renderer"/>
};

/**
 * Paints an object.
 * @param {createjs.Renderer} renderer
 */
createjs.Renderer.RenderObject.prototype.paintObject = function(renderer) {
  /// <param type="createjs.Renderer" name="renderer"/>
};

/**
 * Calculates the ratio of a point in this renderer to one of CSS. When this
 * renderer has its <canvas> element applied CSS transforms, this ratio does not
 * become (1, 1) to (1, 1). This method retrieves the computed rectangle from a
 * browser and calculates it.
 * @private
 */
createjs.Renderer.prototype.calculateRatio_ = function() {
  var canvas = this.getCanvas();
  var bounds = canvas.getBoundingClientRect();
  var zoom = window.getComputedStyle(canvas).zoom;
  this.cssRatio_ = new createjs.Point(
      bounds.width * zoom / this.width_, bounds.height * zoom / this.height_);
};

/**
 * Synchronizes the width property of this renderer with the specified one.
 * @param {number} width
 * @protected
 * @const
 */
createjs.Renderer.prototype.setWidth = function(width) {
  /// <param type="number" name="width"/>
  this.width_ = width;
};

/**
 * Synchronizes the height properties of this renderer with the specified one.
 * @param {number} height
 * @protected
 * @const
 */
createjs.Renderer.prototype.setHeight = function(height) {
  /// <param type="number" name="height"/>
  this.height_ = height;
};

/**
 * Resets the HTMLCanvasElement object attached to this renderer.
 * @protected
 * @const
 */
createjs.Renderer.prototype.resetCanvas = function() {
  if (this.canvas_) {
    this.canvas_.width = 0;
    this.canvas_ = null;
  }
};

/**
 * Updates the layout of the HTMLCanvasElement object attached to this renderer.
 * @param {string} context
 * @suppress {uselessCode}
 * @protected
 * @const
 */
createjs.Renderer.prototype.updateCanvas = function(context) {
  /// <param type="string" name="context"/>
  if (this.useAndroidWorkarounds_ < 0) {
    this.useAndroidWorkarounds_ =
        createjs.Config.useAndroidWorkarounds(context);
  }
  var canvas = this.getCanvas();
  if (this.useAndroidWorkarounds_ == 1) {
    var display = canvas.style.display;
    if (display != 'none') {
      canvas.style.display = 'none';
      canvas.offsetHeight;
      canvas.style.display = display;
    }
  } else if (this.useAndroidWorkarounds_) {
    canvas.width = canvas.width;
  }
};

/**
 * Destroys the resources attached to this renderer.
 */
createjs.Renderer.prototype.destroy = function() {
  createjs.notReached();
};

/**
 * Returns the HTMLCanvasElement object attached to this renderer.
 * @return {HTMLCanvasElement}
 * @const
 */
createjs.Renderer.prototype.getCanvas = function() {
  /// <returns type="HTMLCanvasElement"/>
  return this.canvas_;
};

/**
 * Returns the width.
 * @return {number}
 * @const
 */
createjs.Renderer.prototype.getWidth = function() {
  /// <returns type="number"/>
  return this.width_;
};

/**
 * Returns the height.
 * @return {number}
 * @const
 */
createjs.Renderer.prototype.getHeight = function() {
  /// <returns type="number"/>
  return this.height_;
};

/**
 * Returns the ratio of a point in this renderer to one of CSS.
 * @return {createjs.Point}
 * @const
 */
createjs.Renderer.prototype.getCSSRatio = function() {
  /// <returns type="createjs.Point"/>
  if (!this.cssRatio_) {
    this.calculateRatio_();
  }
  return this.cssRatio_;
};

/**
 * Sets an affine transformation.
 * @param {number} a
 * @param {number} b
 * @param {number} c
 * @param {number} d
 * @param {number} tx
 * @param {number} ty
 */
createjs.Renderer.prototype.setTransformation = function(a, b, c, d, tx, ty) {
  /// <param type="number" name="a"/>
  /// <param type="number" name="b"/>
  /// <param type="number" name="c"/>
  /// <param type="number" name="d"/>
  /// <param type="number" name="tx"/>
  /// <param type="number" name="ty"/>
  createjs.notReached();
};

/**
 * Sets the alpha value.
 * @param {number} alpha
 */
createjs.Renderer.prototype.setAlpha = function(alpha) {
  /// <param type="number" name="alpha"/>
  createjs.notReached();
};

/**
 * Sets the color matrix.
 * @param {Array.<number>} matrix
 */
createjs.Renderer.prototype.setColorMatrix = function(matrix) {
  /// <param type="Array" elementType="number" name="matrix"/>
};

/**
 * Sets the color-composition operation.
 * @param {number} operation
 */
createjs.Renderer.prototype.setComposition = function(operation) {
  /// <param type="number" name="operation"/>
  createjs.notReached();
};

/**
 * Draws an HTMLCanvasElement object to the specified rectangle.
 * @param {HTMLCanvasElement} canvas
 * @param {number} x
 * @param {number} y
 * @param {number} width
 * @param {number} height
 */
createjs.Renderer.prototype.drawCanvas = function(canvas, x, y, width, height) {
  /// <param type="HTMLCanvasElement" name="canvas"/>
  /// <param type="number" name="x"/>
  /// <param type="number" name="y"/>
  /// <param type="number" name="width"/>
  /// <param type="number" name="height"/>
  createjs.notReached();
};

/**
 * Returns a bit-mask representing the extensions supported by this renderer.
 * @return {number}
 */
createjs.Renderer.prototype.getExtensions = function() {
  /// <returns type="number"/>
  return createjs.Renderer.Extension.VIDEO;
};

/**
 * Draws an HTMLVideoElement object to the specified rectangle.
 * @param {HTMLVideoElement} video
 * @param {number} x
 * @param {number} y
 * @param {number} width
 * @param {number} height
 */
createjs.Renderer.prototype.drawVideo = function(video, x, y, width, height) {
  /// <param type="HTMLVideoElement" name="video"/>
  /// <param type="number" name="x"/>
  /// <param type="number" name="y"/>
  /// <param type="number" name="width"/>
  /// <param type="number" name="height"/>
  createjs.notReached();
};

/**
 * Draws a part of an HTMLImageElement object to the specified rectangle.
 * @param {HTMLImageElement} image
 * @param {number} srcX
 * @param {number} srcY
 * @param {number} srcWidth
 * @param {number} srcHeight
 * @param {number} x
 * @param {number} y
 * @param {number} width
 * @param {number} height
 */
createjs.Renderer.prototype.drawPartial =
    function(image, srcX, srcY, srcWidth, srcHeight, x, y, width, height) {
  /// <param type="HTMLImageElement" name="image"/>
  /// <param type="number" name="srcX"/>
  /// <param type="number" name="srcY"/>
  /// <param type="number" name="srcWidth"/>
  /// <param type="number" name="srcHeight"/>
  /// <param type="number" name="x"/>
  /// <param type="number" name="y"/>
  /// <param type="number" name="width"/>
  /// <param type="number" name="height"/>
  createjs.notReached();
};

/**
 * Adds an object to the rendering queue.
 * @param {createjs.Renderer.RenderObject} object
 */
createjs.Renderer.prototype.addObject = function(object) {
  /// <param type="createjs.Renderer.RenderObject" name="object"/>
  // This method is used for calculating clipping rectangles, i.e. this method
  // should not call createjs.notReached().
};

/**
 * Deletes the cache for the specified image.
 * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image
 */
createjs.Renderer.prototype.uncache = function(image) {
  /// <signature>
  ///   <param type="HTMLImageElement" name="image"/>
  /// </signature>
  /// <signature>
  ///   <param type="HTMLCanvasElement" name="canvas"/>
  /// </signature>
  /// <signature>
  ///   <param type="HTMLVideoElement" name="video"/>
  /// </signature>
};

/**
 * Starts paints objects.
 */
createjs.Renderer.prototype.begin = function() {
};

/**
 * Paints objects added to this renderer. This method returns true if this
 * renderer actually draws objects.
 * @param {number} time
 */
createjs.Renderer.prototype.paint = function(time) {
  /// <param type="number" name="time"/>
  createjs.notReached();
};

if (createjs.DEBUG) {
  /**
   * Adds a dirty object to another renderer.
   * @param {createjs.Renderer.RenderObject} object
   */
  createjs.Renderer.prototype.addDirtyObject = function(object) {
    /// <param type="createjs.Renderer.RenderObject" name="object"/>
  };
}


text:
const Turbolinks = require('turbolinks');
const feather = require('feather-icons');

document.addEventListener('turbolinks:load', function() {
  if (document.getElementById('toggle-menu')) {
    document.getElementById('toggle-menu').onclick = function () {
      document.getElementById('menu').style.display = document.getElementById('menu').style.display === 'block' ? 'none' : 'block';
    };
  }
  feather.replace();
  // Your application logic here
});

Turbolinks.start();


text:
import escher,escher.urls,json,os
from IPython.display import HTML

def show_map(sol,map_loc,color=0):
    ''' Returns an escher Builder object for solution 'sol', map 'map_loc' and the supplied color scheme.
        sol:        the solution object containing the simulation results.
        map_loc:    filename of the map json
        color:      color scheme to use
    '''

    # read css
    script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
    with open(script_dir+'/my_escher_stylesheet.css', 'r') as myfile:
        my_css=myfile.read().replace('\n', ' ')

    if color == 0: # grey to yellow to red
        colors = [{'type': 'min', 'color': '#cccccc', 'size': 5},
                  {'type': 'mean', 'color': '#FFFF00', 'size': 10},
                  {'type': 'max', 'color': '#FF0000', 'size': 20}]
    else:
        print('Color scheme not defined!')
        return

    if type(sol) != dict:
        try:
            d = sol.fluxes # it is a cobrapy solution object
        except:
            print('An empty solution was passed.')
            d = {}
    else:
        d = sol # shorthand

    d2 = {} # for some reason my types (from float 64 to float) were not updating and with a new dictionary they do
    for key in list(d.keys()): # remove output like this: 1.653e-15
        d2[key] = round(float(d[key]),6)

    network = escher.Builder(map_json=map_loc, reaction_data=d2,
                       reaction_styles=['color', 'size', 'abs', 'text'],
                       # change the default colors, blue to purple to red
                       reaction_scale=colors,
                       hide_secondary_metabolites=False,secondary_metabolite_radius=10,
                       highlight_missing=True,embedded_css=my_css)
    return network


text:
namespace Ethereum{namespace ABI{

Result::Result(const std::string &data) :
    _value((data[1]=='x'||data[1]=='X') ? data.substr(2) : data)
{}

std::string Result::toString() const
{
    size_t size = _value.size();
    if(size<64)
    {
        return "";
    }
    return _decoder.decodeString(_value.data()+64, size-64); //dynamic offset
}

std::string Result::toAddress() const
{
    return _decoder.decodeAddress(_value);
}

bool Result::toBool() const
{
    return _decoder.decodeBool(_value);
}

uint256_t Result::toUint() const
{
    return _decoder.decodeUint(_value);
}

int256_t Result::toInt() const
{
    return _decoder.decodeInt(_value);
}

decimal_t Result::toDecimal() const
{
    return _decoder.decodeDecimal(_value);
}

}}


text:
.network-details-view {
    background: rgb(203, 203, 203);
}

.network-close-button {
    margin: auto -1px auto 4px;
}

.network-details-view .network-item-view::shadow .tabbed-pane-header {
    flex: 0 0 23px;
    padding-top: 0;
    white-space: nowrap;
}

.network-details-view-tall-header .network-item-view::shadow .tabbed-pane-header {
    flex-basis: 31px;
    padding-top: 8px;
}

.network-item-view {
    display: none;
    background: white;
}

.network-item-view.visible {
    display: flex;
}

.network-item-view::shadow .tabbed-pane-header {
    border-bottom: 1px solid rgb(205, 205, 205);
    background-color: transparent;
}

.resource-timing-view {
    display: none;
    margin: 6px;
    color: rgb(30%, 30%, 30%);
}

/* Network timing is shared between popover and network item view pane */

.network-timing-table {
    width: 328px;
    border-spacing: 0;
    padding-left: 4px;
    padding-right: 4px;
}

.network-timing-table col.labels {
    width: 120px;
}

.network-timing-table td {
    padding: 2px 0;
}

.network-timing-table td.caution {
    font-weight: bold;
    color: rgb(255, 128, 0);
    padding: 2px 0;
}

.network-timing-table .footnote {
    border-top: 1px solid #eee;
}

.network-timing-row {
    position: relative;
    height: 15px;
}

.network-timing-bar {
    position: absolute;
    min-width: 1px;
    top: 0;
    bottom: 0;
}

.network-timing-bar-title {
    position: absolute;
    color: #222;
    padding: 0 3px;
    line-height: 15px;
}

.network-timing-bar.total {
    border: 1px solid rgba(0, 0, 0, 0.1);
}

.network-timing-bar.blocking {
    background-color: hsl(0, 0%, 80%);
}

.network-timing-bar.proxy {
    background-color: hsl(60, 80%, 80%);
}

.network-timing-bar.dns {
    background-color: hsl(180, 80%, 80%);
}

.network-timing-bar.connecting,
.network-timing-bar.serviceworker,
.network-timing-bar.serviceworker-preparation {
    background-color: hsl(30, 80%, 80%);
}

.network-timing-bar.ssl {
    background-color: hsl(270, 80%, 80%);
}

.network-timing-bar.sending,
.network-timing-bar.waiting {
    background-color: hsl(120, 80%, 80%);
}

.network-timing-bar.receiving {
    background-color: hsl(210, 80%, 80%);
}

.resource-timing-view.visible {
    display: block;
}

.resource-timing-view .network-timing-table {
    width: 100%;
}

.network-filters-header {
    flex: 0 0 23px;
    padding-right: 4px;
}

.network-filters-header .filter-text-filter {
    flex-grow: 1;
    max-width: 312px;
}

.request-view.json {
    padding: 5px;
}

.request-view.html iframe {
    width: 100%;
    height: 100%;
    position: absolute;
}


text:
import express from 'express'
import jwt from 'express-jwt'
import { assignIn } from 'lodash'
import { SECRET, SHOPIFY_API_KEY, SHOPIFY_PASSWORD, MAPBOX_ACCESS_TOKEN } from '../config'
import AWS from '../utils/AWS'
import Shopify from '../utils/Shopify'
import Kratelabs from '../utils/Kratelabs'
import { Product } from '../models'

const router = express.Router()
const aws = new AWS.S3({ bucket: 's3://api.kratelabs.com', recursive: true })
const shopify = new Shopify({
  apikey: SHOPIFY_API_KEY,
  password: SHOPIFY_PASSWORD
})
const kratelabs = new Kratelabs({
  access_token: MAPBOX_ACCESS_TOKEN,
  style: 'mapbox://styles/addxy/cim6u5lfi00k2cwm23exyzjim'
})

function validateProduct (request, response, next) {
  let product = new Product(request.body)
  let error = product.validateSync()
  if (error) {
    return response.status(400).json(assignIn(error, { ok: false, status: 400 }))
  }
  if (!request.body.id) {
    request.body.id = product._id
    console.log(request.body.id)
  }
  next()
}

function validateToken (request, response, next) {
  if (!request.user.email) {
    return response.status(401).json({
      ok: false,
      status: 401,
      message: 'Token invalid',
      error: 'Missing email from Token'
    })
  }
  next()
}

async function createMapProduct (request, response, next) {
  let product = new Product(request.body)
  let error = {
    status: 500,
    ok: false,
    message: 'Error creating product',
    error: 'Error Kratelabs CLI'
  }
  // Create Full Kratelab Style
  let full = await kratelabs.create({
    filename: `./uploads/products/${product.id}/${product.id}-full`,
    lat: product.lat,
    lng: product.lng,
    zoom: product.zoom,
    bearing: product.bearing,
    pitch: product.pitch,
    style: 'mapbox://styles/addxy/ciq40e6zx0010bkmbbo513b6s'
  })
  if (!full.ok) { return response.status(500).json(error) }

  // Create Water Kratelab Style
  let water = await kratelabs.create({
    filename: `./uploads/products/${product.id}/${product.id}-water`,
    lat: product.lat,
    lng: product.lng,
    zoom: product.zoom,
    bearing: product.bearing,
    pitch: product.pitch,
    style: 'mapbox://styles/addxy/ciq4i2skg000u7mnnpxcnpans'
  })
  if (!water.ok) { return response.status(500).json(error) }

  // Create Roads Kratelab Style
  let roads = await kratelabs.create({
    filename: `./uploads/products/${product.id}/${product.id}-roads`,
    lat: product.lat,
    lng: product.lng,
    zoom: product.zoom,
    bearing: product.bearing,
    pitch: product.pitch,
    style: 'mapbox://styles/addxy/ciqvrp80a0004bgnozxogrbcj'
  })
  if (!roads.ok) { return response.status(500).json(error) }

  // Create Buildings Kratelab Style
  let buildings = await kratelabs.create({
    filename: `./uploads/products/${product.id}/${product.id}-buildings`,
    lat: product.lat,
    lng: product.lng,
    zoom: product.zoom,
    bearing: product.bearing,
    pitch: product.pitch,
    style: 'mapbox://styles/addxy/ciq4i1vdo001jb2niy9z38i9a'
  })
  if (!buildings.ok) { return response.status(500).json(error) }
  next()
}

function uploadAWS (request, response, next) {
  let product = new Product(request.body)

  aws.cp({
    source: `./uploads/products/${product.id}`,
    target: `s3://api.kratelabs.com/products/${product.id}`,
    publicReadWrite: true
  })
    .then(
      data => { if (data) next() },
      error => {
        if (error) {
          response.status(500).json({
            status: 500,
            ok: false,
            message: 'Error creating product',
            error: 'Error AWS Upload'
          })
        }
      }
    )
}

function createShopifyProduct (request, response, next) {
  let product = new Product(request.body)

  shopify.createProduct({
    name: product.id,
    image: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}`
  })
    .then(
      data => {
        if (data) { request.body.shopify = data.product.id }
        next()
      },
      error => {
        if (error) {
          response.status(500).json({
            status: 500,
            ok: false,
            message: 'Error creating product',
            error: 'Error Shopify API'
          })
        }
      }
    )
}

router.route('/')
  .get((request, response) => {
    response.json({
      api: 'Product',
      ok: true,
      status: 200,
      message: 'Demonstrates the Product API',
      http: [
        {url: '/product', method: 'GET'},
        {url: '/product', method: 'POST', fields: ['lat', 'lng', 'zoom', 'bearing', 'pitch', 'email', 'location']},
        {url: '/product/:product_id', method: 'GET'},
        {url: '/product/:product_id', method: 'POST'},
        {url: '/product/:product_id', method: 'DELETE'}
      ]
    })
  })

  .post(jwt({ secret: SECRET, issuer: 'https://api.kratelabs.com' }), validateToken)
  .post(validateProduct)
  .post(createMapProduct)
  .post(uploadAWS)
  .post(createShopifyProduct)
  .post((request, response) => {
    let product = new Product(request.body)

    response.json({
      status: 200,
      ok: true,
      id: product.id,
      message: 'Product created',
      shopify: product.shopify,
      url: {
        svg: {
          full: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-full.svg`,
          roads: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-roads.svg`,
          water: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-water.svg`,
          buildings: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-buildings.svg`
        },
        shopify: 'https://kratelabs.com/products/' + product.id,
        api: 'https://api.kratelabs.addxy.com/product/' + product.id
      }
    })
  })

router.route('/:product_id')
  .get((request, response) => {
    let product_id = request.params.product_id
    Product.findOne({ id: product_id }, { _id: 0, __v: 0 }, (error, product) => {
      if (error) {
        return response.status(500).json({
          status: 500,
          ok: false,
          id: product_id,
          message: 'Error retrieving product',
          error: error
        })
      }
      if (!product) {
        return response.status(404).json({
          status: 404,
          ok: false,
          id: product_id,
          message: 'Product cannot be found',
          error: 'Product cannot be found',
        })
      }
      response.json({
        status: 200,
        ok: true,
        id: product.id,
        product: product,
        url: {
          svg: {
            full: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-full.svg`,
            roads: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-roads.svg`,
            water: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-water.svg`,
            buildings: `https://s3.amazonaws.com/api.kratelabs.com/products/${product.id}/${product.id}-buildings.svg`
          },
          shopify: 'https://kratelabs.com/products/' + product.id,
          api: 'https://api.kratelabs.addxy.com/product/' + product.id
        }
      })
    })
  })

  .delete(jwt({ secret: SECRET, issuer: 'https://api.kratelabs.com' }), (request, response) => {
    let product_id = request.params.product_id
    Product.findOne({id: product_id})
      .then(product => {
        if (!product) {
          return response.status(404).json({
            status: 404,
            ok: false,
            id: product_id,
            message: 'Product cannot be found',
            error: 'Product cannot be found'
          })
        }
        product.remove((error, removed) => {
          if (removed) {
            response.json({
              status: 200,
              ok: true,
              id: product_id,
              message: 'Product removed'
            })
          }
        })
      })
  })

  .post((request, response) => {
    let product_id = request.params.product_id
    Product.update({id: product_id}, request.body, (error, product) => {
      if (!product.ok) {
        return response.status(400).json({
          status: 400,
          ok: false,
          id: product_id,
          payload: request.body,
          message: 'Error updating product with payload',
          error: 'Error updating product'
        })
      }
      if (!product.n) {
        return response.status(404).json({
          status: 404,
          ok: false,
          id: product_id,
          message: 'Product cannot be found',
          error: 'Product cannot be found'
        })
      }
      if (error) {
        return response.status(500).json({
          status: 500,
          ok: false,
          id: product_id,
          message: 'Error updating product',
          error: error
        })
      }
      response.json({
        status: 200,
        ok: true,
        id: product_id,
        payload: request.body,
        message: 'Product updated'
      })
    })
  })

export default router


text:
<!DOCTYPE HTML>

<title>com.arjuna.wsc11.messaging (Narayana: narayana-full 5.13.1.Final API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-11-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Narayana: narayana-full 5.13.1.Final

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Package com.arjuna.wsc11.messaging

Class Summary

Class
Description

ActivationCoordinatorProcessorImpl

The Activation Coordinator processor.

MessageId

A simple message id generator, used when UID is inaccessible.

RegistrationCoordinatorProcessorImpl

The Registration Coordinator processor.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Narayana: narayana-full 5.13.1.Final

All Classes

JavaScript is disabled on your browser.

Copyright © 2022 JBoss by Red Hat. All rights reserved.


text:
Logger = require("./log");
log = new Logger(Logger.INFO);
optparser = require("./optparser");
net = require("net");
util=require("util");
BufferManager=require('./buffermanager').BufferManager;

SERVER_CMD_START=[0x00,0x01];
SERVER_CMD_END=[0xfe,0xff];

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout),
    prefix = 'httpproxy> ';
rl.setPrompt(prefix, prefix.length);

socket=net.createConnection(8080,'127.0.0.1');
socket.on("connect",function(){
    rl.prompt();
});
socket.on("close",function(){
    rl.close();
    process.stdin.destroy();
    console.log("connection closed");
    process.exit(255);
});

COMMAND_TABLE={
    list:function(){
            command_end();
        },
    info:function(){
            command_end();
        },
    loadconf:function(){
            command_end();
        },
    dnsshow:function(tokens){
            socket.on("data",function(buf){
                res=parse_response(buf)
                if(typeof res=='undefined'){
                    return;
                }
                console.log(util.inspect(res));
                command_end();
            });
            tokens.unshift('dnsshow');
            sendRequest(socket,tokens.join(" "));
        },
    dnsclean:function(){
            command_end();
        },
    help:function(){
            command_end();
        },
    quit:function(){
            rl.close();
            process.stdin.destroy();
        }
}
/**
 * windows env don't have this function
process.on('SIGINT', function () {
    command_end();
    console.log('Got SIGINT.  Press Control-D to exit.');
});
*/
rl.on('line', function(line) {
    var tokens=line.trim().split(/\s+/);
    var cmd=tokens[0].toLowerCase();
    if(typeof COMMAND_TABLE[cmd]=='function' && COMMAND_TABLE.hasOwnProperty(cmd)){
        COMMAND_TABLE[cmd](tokens.slice(1));
    }else{
        if(cmd.length>0){
            console.log(cmd+': command not found');
        }
        command_end();
    }
})
.on('close', function() {
    console.log();
    console.log('Have a great day!');
    process.exit(0);
});

function load_hosts(){

}
function command_end(){
    rl.prompt();
}

parse_response=(function(){
    var bm=new BufferManager();
    return function(buf){
        bm.add(buf);
        var start=bm.indexOf(SERVER_CMD_START);
        var end=bm.indexOf(SERVER_CMD_END);
        if(start==0 && end>0){
            var result=bm.slice(SERVER_CMD_START.length,end-SERVER_CMD_END.length).toString();
            result=JSON.parse(result);
            var rest=bm.slice(end+SERVER_CMD_END.length);
            bm.clear();
            bm.add(rest);
            return result;
        }else{
            return;
        }
    }
})();

function sendRequest(socket,cmd){
    var bm=new BufferManager();
    bm.add(SERVER_CMD_START);
    bm.add(cmd);
    bm.add(SERVER_CMD_END);
    socket.write(bm.toBuffer());
}


text:
<?php

namespace hipanel\modules\finance\models;

use hipanel\modules\finance\models\query\ChargeQuery;
use Yii;

/**
 * Class Charge.
 *
 * @author Dmytro Naumenko <d.naumenko.a@gmail.com>
 *
 * @property int $id
 * @property string $unit
 * @property string $quantity
 * @property int $parent_id
 * @property string $type
 * @property string $name
 * @property string $ftype
 * @property string $currency
 * @property float $sum
 * @property float $is_payed
 * @property int object_id
 * @property TargetObject $commonObject
 * @property TargetObject $latestCommonObject
 * @property Bill $bill
 */
class Charge extends Resource implements HasSumAndCurrencyAttributesInterface
{
    use \hipanel\base\ModelTrait;

    const SCENARIO_CREATE = 'create';
    const SCENARIO_UPDATE = 'update';

    private $isNewRecord;

    /**
     * @inheritDoc
     */
    public static function tableName()
    {
        return 'resource';
    }

    public function rules()
    {
        return [
            [['id', 'type_id', 'object_id', 'bill_id', 'parent_id', 'client_id', 'tariff_id', 'seller_id', 'order_id'], 'integer'],
            [['class', 'name', 'unit', 'tariff', 'order_name', 'client', 'seller', 'client_type'], 'string'],
            [['type', 'label', 'ftype', 'time', 'type_label', 'currency'], 'safe'],
            [['is_payed'], 'boolean'],
            [['sum', 'quantity', 'bill_quantity'], 'number'],
            [['unit'], 'default', 'value' => 'items', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
            [['object_id', 'sum', 'type', 'quantity', 'unit'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
            [['id'], 'safe', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_UPDATE]],
        ];
    }

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            'sum' => Yii::t('hipanel', 'Sum'),
            'type' => Yii::t('hipanel', 'Type'),
            'quantity' => Yii::t('hipanel:finance', 'Qty.'),
            'label' => Yii::t('hipanel', 'Description'),
            'time' => Yii::t('hipanel', 'Time'),
            'object_id' => Yii::t('hipanel', 'Object Id'),
            'order_id' => Yii::t('hipanel', 'Order'),
            'is_payed' => Yii::t('hipanel:finance', 'Is paid?'),
        ]);
    }

    public function markAsNotNew()
    {
        $this->isNewRecord = false;
    }

    public function getCommonObject()
    {
        return $this->hasOne(TargetObject::class, ['id' => 'id']);
    }

    public function getLatestCommonObject()
    {
        return $this->hasOne(TargetObject::class, ['id' => 'id']);
    }

    public function getIsNewRecord()
    {
        return $this->isNewRecord !== false && parent::getIsNewRecord();
    }

    public function getBill()
    {
        return $this->hasOne(Bill::class, ['id' => 'id'])->inverseOf('charges');
    }

    public function isMonthly(): bool
    {
        return strpos($this->ftype, 'monthly,') === 0;
    }

    /**
     * {@inheritdoc}
     * @return ChargeQuery
     */
    public static function find($options = [])
    {
        return new ChargeQuery(get_called_class(), [
            'options' => $options,
        ]);
    }
}


text:
"""Tests for test randomization."""

import random
import subprocess

from absl import flags
from absl.testing import _bazelize_command
from absl.testing import absltest
from absl.testing import parameterized
from absl.testing.tests import absltest_env

FLAGS = flags.FLAGS

class TestOrderRandomizationTest(parameterized.TestCase):
  """Integration tests: Runs a py_test binary with randomization.

  This is done by setting flags and environment variables.
  """

  def setUp(self):
    super(TestOrderRandomizationTest, self).setUp()
    self._test_name = 'absl/testing/tests/absltest_randomization_testcase'

  def _run_test(self, extra_argv, extra_env):
    """Runs the py_test binary in a subprocess, with the given args or env.

    Args:
      extra_argv: extra args to pass to the test
      extra_env: extra env vars to set when running the test

    Returns:
      (stdout, test_cases, exit_code) tuple of (str, list of strs, int).
    """
    env = absltest_env.inherited_env()
    # If *this* test is being run with this flag, we don't want to
    # automatically set it for all tests we run.
    env.pop('TEST_RANDOMIZE_ORDERING_SEED', '')
    if extra_env is not None:
      env.update(extra_env)

    command = (
        [_bazelize_command.get_executable_path(self._test_name)] + extra_argv)
    proc = subprocess.Popen(
        args=command,
        env=env,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True)

    stdout, _ = proc.communicate()

    test_lines = [l for l in stdout.splitlines() if l.startswith('class ')]
    return stdout, test_lines, proc.wait()

  def test_no_args(self):
    output, tests, exit_code = self._run_test([], None)
    self.assertEqual(0, exit_code, msg='command output: ' + output)
    self.assertNotIn('Randomizing test order with seed:', output)
    cases = ['class A test ' + t for t in ('A', 'B', 'C')]
    self.assertEqual(cases, tests)

  @parameterized.parameters(
      {
          'argv': ['--test_randomize_ordering_seed=random'],
          'env': None,
      },
      {
          'argv': [],
          'env': {
              'TEST_RANDOMIZE_ORDERING_SEED': 'random',
          },
      },)
  def test_simple_randomization(self, argv, env):
    output, tests, exit_code = self._run_test(argv, env)
    self.assertEqual(0, exit_code, msg='command output: ' + output)
    self.assertIn('Randomizing test order with seed: ', output)
    cases = ['class A test ' + t for t in ('A', 'B', 'C')]
    # This may come back in any order; we just know it'll be the same
    # set of elements.
    self.assertSameElements(cases, tests)

  @parameterized.parameters(
      {
          'argv': ['--test_randomize_ordering_seed=1'],
          'env': None,
      },
      {
          'argv': [],
          'env': {
              'TEST_RANDOMIZE_ORDERING_SEED': '1'
          },
      },
      {
          'argv': [],
          'env': {
              'LATE_SET_TEST_RANDOMIZE_ORDERING_SEED': '1'
          },
      },
  )
  def test_fixed_seed(self, argv, env):
    output, tests, exit_code = self._run_test(argv, env)
    self.assertEqual(0, exit_code, msg='command output: ' + output)
    self.assertIn('Randomizing test order with seed: 1', output)
    # Even though we know the seed, we need to shuffle the tests here, since
    # this behaves differently in Python2 vs Python3.
    shuffled_cases = ['A', 'B', 'C']
    random.Random(1).shuffle(shuffled_cases)
    cases = ['class A test ' + t for t in shuffled_cases]
    # We know what order this will come back for the random seed we've
    # specified.
    self.assertEqual(cases, tests)

  @parameterized.parameters(
      {
          'argv': ['--test_randomize_ordering_seed=0'],
          'env': {
              'TEST_RANDOMIZE_ORDERING_SEED': 'random'
          },
      },
      {
          'argv': [],
          'env': {
              'TEST_RANDOMIZE_ORDERING_SEED': '0'
          },
      },)
  def test_disabling_randomization(self, argv, env):
    output, tests, exit_code = self._run_test(argv, env)
    self.assertEqual(0, exit_code, msg='command output: ' + output)
    self.assertNotIn('Randomizing test order with seed:', output)
    cases = ['class A test ' + t for t in ('A', 'B', 'C')]
    self.assertEqual(cases, tests)

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


text:
package org.apache.hc.core5.http.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.ThreadingBehavior;
import org.apache.hc.core5.util.TextUtils;

/**
 * Generic registry of items keyed by low-case string ID.
 *
 * @since 4.3
 */
@Contract(threading = ThreadingBehavior.SAFE)
public final class Registry<I> implements Lookup<I> {

    private final Map<String, I> map;

    Registry(final Map<String, I> map) {
        super();
        this.map = new ConcurrentHashMap<>(map);
    }

    @Override
    public I lookup(final String key) {
        if (key == null) {
            return null;
        }
        return map.get(TextUtils.toLowerCase(key));
    }

    @Override
    public String toString() {
        return map.toString();
    }

}


text:
layout: post
name: Extreme-Learning
title: A really good way to make your learning more effective
date: 2015-06-13 10:00:00 +00:00
author: Toby Retallick
---

Last weekend I was lucky enough to attend [Socrates UK 2015](http://socratesuk.org), an annual international software craftsmanship gathering set in the scenic surroundings of Farnham, Oxfordshire. If you have not done so, I recommend attending this conference, either in England or the other Socrates events taking place across Europe (Germany, Belgium, France ...).

At the time of writing this post I am a software apprentice at [Codurance](http://www.codurance.com). My 'things to learn' list grows every day. Java fundamentals, SOLID principles, TDD practices, oh wait … some of the new developers on the project are now using Scala... I want to at least be able to understand their code. [Terraform](http://www.terraform.io) has been coming up in a number of discussions... I want to get my head around that. You get the idea right?

Given the volume of learning required, and having limited time available to do it, I was really grateful to [Matieu Adsuara](http://www.twitter.com/@demonh3x) from 8th Light, who lead an awesome workshop on Extreme Learning at the Socrates UK event this year.

If you want to get more bang for your buck when you study, then have a shot at this. The method outlined below is adapted from the workshop along with my own additions.

##Define your learning objective
Adopting the user story pattern will help you here. For example:

As a [Student? Experienced developer? Scrum Master?]

I want to [Learn Scala? Learn the Adapter Pattern?]

So that I can [Define your outcome here]

Defining a learning outcome ties all your hard work to something tangible. You can look back at the end of the process and decide whether the outcome was achieved or not and why. There is a great quote from Lewis Carroll's Alice in Wonderland that sums this up nicely.

> Cat: Where are you going?

> Alice: Which way should I go?

> Cat: That depends on where you are going.

> Alice: I don't know.

> Cat: Then it doesn't matter which way you go.

> ― Lewis Carroll, Alice in Wonderland

##Time-box your efforts
Give yourself 30 minutes to learn everything you can about the subject you have chosen. Bear in mind, attempting to learn a language in such a short space of time is perhaps asking a little too much. If your learning objective is substantial, break it down into smaller goals. Rather than learn a whole language in 30 minutes, instead narrow the scope of your learning objective. Perhaps get to grips with a particular library, API or even a few select methods.

How does time-boxing help? If you are time-poor, you are more likely to find 30 minute slots during your day (e.g. your lunch break, commute, before you go to work etc) to dedicate to study than say, an hour or more. Remember also, that the key to Extreme Learning is quality of learning, not quantity. 30 minutes of intense, uninterrupted high quality study is far better than 1 hour of unfocused, interrupted study (How many times do you catch yourself switching off and checking your emails?). That said, 30 minutes is not a long time. If you set a timer, the pressure of the ticking clock should help you perform that much better.

##Have something to show for it
The time you spend learning needs to result in some sort of output. At the workshop, Mathieu had us present a lightning talk to the group. This is a great option in a work situation - perhaps you can do something with colleagues over a lunch break. If you are flying solo, then a worthy alternative is to create a blog based on your findings.

How does creating an output help? I can't stress enough this aspect enough. Presenting a talk, a demo or writing a blog will allow you to verbalise your thought processes, help you retain information, and share your new-found knwoledge with other developers. The act of creating an output is advice regularly seen in a lot of self-help and technical books out there (e.g take a look at the [The Lean Startup](http://theleanstartup.com/) and the recommendation around creating a minimum viable product). The key is not to get too fixated on creating the perfect blog or presentation. Just get something out there, get feedback and improve as required.

If you develop a habit of learning in this way, you will find your abilities should improve over time.

##Recommended Reading
[Cal Newport's Study Hacks blog](http://calnewport.com/blog/about/)


text:
<com.tle.beans.mime.MimeEntry>
  <id>2016982</id>
  <institution>
    <id>2016849</id>
    <enabled>true</enabled>
  </institution>
  <extensions class="list">
    <string>dotx</string>
  </extensions>
  <type>application/vnd.openxmlformats-officedocument.wordprocessingml.template</type>
  <attributes>
    <entry>
      <string>PluginIconPath</string>
      <string>icons/binary.gif</string>
    </entry>
  </attributes>
</com.tle.beans.mime.MimeEntry>


text:
<VerticalLayout captionMargin="0" height="100%" style="tableContainer">
  <ValidationSettings formTitle="" withApply="true" withAttach="false" withPrint="true" />
  <GuiTree title="Recently Visited Menus" name="MENU_TREE" dataPath="DATAROOT" width="100%" height="100%" checkBox="true" addEnabled="false" deleteEnabled="false" openEnabled="false" pageLength="10" withFilter="false" refreshEnabled="false">
    <OpenForm containerWindow="same window" />
    <TableColumn name="TITLE" caption="Title" width="-1px" expandRatio="1" />
    <TableColumn name="EXTRA_ACTION_0" caption="Shortcut" width="-1px" style="link" />
  </GuiTree>
</VerticalLayout>


text:
<?php
namespace Vivo\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Session\Container;

/**
 * SessionManagerFactory
 */
class SessionManagerFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $config         = $serviceLocator->get('config');
        if (isset($config['session_config']['options'])) {
            $sessionConfigOptions  = $config['session_config']['options'];
        } else {
            $sessionConfigOptions  = array();
        }
        //Configure cookie according to the security
        if (isset($config['session_config']['security']['enabled'])
                && $config['session_config']['security']['enabled']) {
            $request    = $serviceLocator->get('request');
            if ($request instanceof \Zend\Http\PhpEnvironment\Request) {
                $headerName = $config['session_config']['security']['security_http_header'];
                if ($request->getHeader($headerName) || $_SERVER['HTTPS']) {
                    $sessionConfigOptions['cookie_httponly']    = false;
                    $sessionConfigOptions['cookie_secure']      = true;
                    $sessionConfigOptions['name']
                        = $config['session_config']['security']['secure_session_name'];
                } else {
                    $sessionConfigOptions['cookie_httponly']    = true;
                    $sessionConfigOptions['cookie_secure']      = false;
                }
            }
        }
        $sessionConfigObj   = new \Zend\Session\Config\SessionConfig();
        $sessionConfigObj->setOptions($sessionConfigOptions);
        $sessionManager     = new \Zend\Session\SessionManager($sessionConfigObj);
        //Start session
        if (isset($config['session_config']['start_session']) && $config['session_config']['start_session']) {
            $sessionManager->start();
        }
        //Regenerate ID
        if (isset($config['session_config']['regenerate_id']) && $config['session_config']['regenerate_id']) {
            $sessionManager->regenerateId(false);
        }
        Container::setDefaultManager($sessionManager);
        return $sessionManager;
    }
}


text:
package io.fabric8.kubernetes.jolokia;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;
import org.jolokia.client.J4pAuthenticator;

import java.io.IOException;

/**
 * Authenticator using the Bearer token.
 *
 * The token is expected to be provided in the pUser field of the {@link BearerTokenAuthenticator#authenticate(HttpClientBuilder, String, String)} method.
 */
public class BearerTokenAuthenticator implements J4pAuthenticator {

    public BearerTokenAuthenticator() {
    }

    /** {@inheritDoc} */
    public void authenticate(HttpClientBuilder pBuilder, String pUser, String pPassword) {
        pBuilder.addInterceptorFirst(new PreemptiveBearerInterceptor(pUser));
    }

    // =================================================================================================

    static class PreemptiveBearerInterceptor implements HttpRequestInterceptor {

        private String token;

        public PreemptiveBearerInterceptor(String token) {
            this.token = token;
        }

        /** {@inheritDoc} */
        public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            request.addHeader("Authorization", "Bearer " + token);
        }
    }
}


text:
package org.xsaas.xstat.web.action.manage.delete;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionSupport;

public class DeleteGradeStdRelationAction extends ActionSupport {

	/**
	 *
	 */
	private static final long serialVersionUID = 1294385167892001337L;
	private static Log logger = LogFactory.getLog(DeleteGradeStdRelationAction.class);

	@Override
	public String execute() throws Exception {

		return SUCCESS;
	}
}


text:
package com.solwars.game.units;

import com.solwars.game.GameInstance;
import com.solwars.game.managers.SquadManager;

import java.util.ArrayList;

public class Squad {
    private int team;

    private Unit leader = null;
    private ArrayList<Unit> members = new ArrayList<Unit>();
    private int sqCount;
    private float sqThreat;

    public Squad(Unit Leader, int team, ArrayList<Unit> members){
        SquadManager.getInstance().addSquad(this);
        this.leader = leader;
        System.out.println("leader set");
        leader.setSquad(this);
        if(members != null){
            this.members = members;
        }
    }
    public void addMember(Unit unit){
        this.members.add(unit);
        unit.setSquad(this);
    }

    public Squad(Unit leader, int team){
        SquadManager.getInstance().addSquad(this);
        this.leader = leader;
        System.out.println("leader set");
        leader.setSquad(this);
    }

    public int getTeam() {
        return team;
    }

    public Unit getLeader() {
        return leader;
    }

    public float getSqThreat() {
        return sqThreat;
    }
    public Squad getSquad() {
        return this;
    }
}


text:
import {expect} from 'chai';
import PulsePointAdapter from '../../../src/adapters/pulsepoint';
import bidManager from '../../../src/bidmanager';
import adLoader from '../../../src/adloader';

describe("PulsePoint Adapter Tests", () => {

  let pulsepointAdapter = new PulsePointAdapter();
  let slotConfigs;
  let requests = [];
  let responses = {};

  function initPulsepointLib() {
    /* Mocked PulsePoint library */
    window.pp = {
      requestActions: {
        BID: 0
      }
    };
    /* Ad object*/
    window.pp.Ad = function(config) {
      this.display = function() {
        requests.push(config);
        config.callback(responses[config.ct]);
      };
    };
  }

  function resetPulsepointLib() {
    window.pp = undefined;
  }

  beforeEach(() => {
    initPulsepointLib();
    sinon.stub(bidManager, 'addBidResponse');
    sinon.stub(adLoader, 'loadScript');

    slotConfigs = {
      bids: [
        {
          placementCode: "/DfpAccount1/slot1",
          bidder: "pulsepoint",
          bidId: 'bid12345',
          params: {
            cp: "p10000",
            ct: "t10000",
            cf: "300x250",
            param1: "value1",
            param2: 2
          }
        },{
          placementCode: "/DfpAccount2/slot2",
          bidder: "pulsepoint",
          bidId: 'bid23456',
          params: {
            cp: "p20000",
            ct: "t20000",
            cf: "728x90"
          }
        }
      ]
    };
  });

  afterEach(() => {
    bidManager.addBidResponse.restore();
    adLoader.loadScript.restore();
    requests = [];
    responses = {};
  });

  it('Verify requests sent to PulsePoint library', () => {
    pulsepointAdapter.callBids(slotConfigs);
    expect(requests).to.have.length(2);
    //slot 1
    expect(requests[0].cp).to.equal('p10000');
    expect(requests[0].ct).to.equal('t10000');
    expect(requests[0].cf).to.equal('300x250');
    expect(requests[0].ca).to.equal(0);
    expect(requests[0].cn).to.equal(1);
    expect(requests[0].cu).to.equal('http://bid.contextweb.com/header/tag');
    expect(requests[0].adUnitId).to.equal('/DfpAccount1/slot1');
    expect(requests[0]).to.have.property('callback');
    expect(requests[0].param1).to.equal('value1');
    expect(requests[0].param2).to.equal(2);
    // //slot 2
    expect(requests[1].cp).to.equal('p20000');
    expect(requests[1].ct).to.equal('t20000');
    expect(requests[1].cf).to.equal('728x90');
    expect(requests[1].ca).to.equal(0);
    expect(requests[1].cn).to.equal(1);
    expect(requests[1].cu).to.equal('http://bid.contextweb.com/header/tag');
    expect(requests[1].adUnitId).to.equal('/DfpAccount2/slot2');
    expect(requests[1]).to.have.property('callback');
  });

  it('Verify bid', () => {
    responses['t10000'] = {
      html: 'This is an Ad',
      bidCpm: 1.25
    };
    pulsepointAdapter.callBids(slotConfigs);
    let placement = bidManager.addBidResponse.firstCall.args[0];
    let bid = bidManager.addBidResponse.firstCall.args[1];
    expect(placement).to.equal('/DfpAccount1/slot1');
    expect(bid.bidderCode).to.equal('pulsepoint');
    expect(bid.cpm).to.equal(1.25);
    expect(bid.ad).to.equal('This is an Ad');
    expect(bid.width).to.equal('300');
    expect(bid.height).to.equal('250');
    expect(bid.adId).to.equal('bid12345');
  });

  it('Verify passback', () => {
    pulsepointAdapter.callBids(slotConfigs);
    let placement = bidManager.addBidResponse.firstCall.args[0];
    let bid = bidManager.addBidResponse.firstCall.args[1];
    expect(placement).to.equal('/DfpAccount1/slot1');
    expect(bid.bidderCode).to.equal('pulsepoint');
    expect(bid).to.not.have.property('ad');
    expect(bid).to.not.have.property('cpm');
    expect(bid.adId).to.equal('bid12345');
  });

  it('Verify PulsePoint library is downloaded if nessesary', () => {
    resetPulsepointLib();
    pulsepointAdapter.callBids(slotConfigs);
    let libraryLoadCall = adLoader.loadScript.firstCall.args[0];
    let callback = adLoader.loadScript.firstCall.args[1];
    expect(libraryLoadCall).to.equal('http://tag-st.contextweb.com/getjs.static.js');
    expect(callback).to.be.a('function');
  });

  it('Verify Bids get processed after PulsePoint library downloads', () => {
    resetPulsepointLib();
    pulsepointAdapter.callBids(slotConfigs);
    let callback = adLoader.loadScript.firstCall.args[1];
    let bidCall = bidManager.addBidResponse.firstCall;
    expect(callback).to.be.a('function');
    expect(bidCall).to.be.a('null');
    //the library load should initialize pulsepoint lib
    initPulsepointLib();
    callback();
    expect(requests.length).to.equal(2);
    bidCall = bidManager.addBidResponse.firstCall;
    expect(bidCall).to.be.a('object');
    expect(bidCall.args[0]).to.equal('/DfpAccount1/slot1');
    expect(bidCall.args[1]).to.be.a('object');
  });

  //related to issue https://github.com/prebid/Prebid.js/issues/866
  it('Verify Passbacks when window.pp is not available', () => {
    window.pp = function() {};
    pulsepointAdapter.callBids(slotConfigs);
    let placement = bidManager.addBidResponse.firstCall.args[0];
    let bid = bidManager.addBidResponse.firstCall.args[1];
    //verify that we passed back without exceptions, should window.pp be already taken.
    expect(placement).to.equal('/DfpAccount1/slot1');
    expect(bid.bidderCode).to.equal('pulsepoint');
    expect(bid).to.not.have.property('ad');
    expect(bid).to.not.have.property('cpm');
    expect(bid.adId).to.equal('bid12345');
  });

});


text:
 Extension methods to make working with IEnumerable<T> values easier.

**Namespace:** [OfficeDevPnP.Core.Extensions](OfficeDevPnP.Core.Extensions.md)
**Assembly:** OfficeDevPnP.Core.dll
## Inheritance Hierarchy
System.Object
## Syntax
```C#
public static class EnumerableExtensions
```
## Extension Methods
|**Name**|**Description**|
|:-----|:-----|
| [DeepEquals<T>(IEnumerable<T>, IEnumerable<T>)](OfficeDevPnP.Core.Extensions.EnumerableExtensions.cf939282.md) | Compares to instances of IEnumerable<T>
## See also
- [OfficeDevPnP.Core.Extensions](OfficeDevPnP.Core.Extensions.md)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__free_struct_static_16.c
Label Definition File: CWE590_Free_Memory_Not_on_Heap__free.label.xml
Template File: sources-sink-16.tmpl.c
*/
/*
 * @description
 * CWE: 590 Free Memory Not on Heap
 * BadSource: static Data buffer is declared static on the stack
 * GoodSource: Allocate memory on the heap
 * Sink:
 *    BadSink : Print then free data
 * Flow Variant: 16 Control flow: while(1)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE590_Free_Memory_Not_on_Heap__free_struct_static_16_bad()
{
    twoIntsStruct * data;
    data = NULL; /* Initialize data */
    while(1)
    {
        {
            /* FLAW: data is allocated on the stack and deallocated in the BadSink */
            static twoIntsStruct dataBuffer[100];
            {
                size_t i;
                for (i = 0; i < 100; i++)
                {
                    dataBuffer[i].intOne = 1;
                    dataBuffer[i].intTwo = 1;
                }
            }
            data = dataBuffer;
        }
        break;
    }
    printStructLine(&data[0]);
    /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
    free(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */
static void goodG2B()
{
    twoIntsStruct * data;
    data = NULL; /* Initialize data */
    while(1)
    {
        {
            /* FIX: data is allocated on the heap and deallocated in the BadSink */
            twoIntsStruct * dataBuffer = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct));
            if (dataBuffer == NULL)
            {
                printLine("malloc() failed");
                exit(1);
            }
            {
                size_t i;
                for (i = 0; i < 100; i++)
                {
                    dataBuffer[i].intOne = 1;
                    dataBuffer[i].intTwo = 1;
                }
            }
            data = dataBuffer;
        }
        break;
    }
    printStructLine(&data[0]);
    /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
    free(data);
}

void CWE590_Free_Memory_Not_on_Heap__free_struct_static_16_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE590_Free_Memory_Not_on_Heap__free_struct_static_16_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE590_Free_Memory_Not_on_Heap__free_struct_static_16_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<!doctype html>
<html lang="en" ng-app="myApp">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

    <link href="css/style.css" rel="stylesheet">
    <link href="css/bootstrap.css" rel="stylesheet">
    <link href="css/bootstrap-responsive.css" rel="stylesheet">
    <link href='css/xeditable.css'>
    <script src="lib/angular.js"></script>
    <script src="lib/angular-touch.js"></script>
    <script src="lib/angular-resource.js"></script>
    <script src="lib/angular-animate.js"></script>
    <script src="lib/angular-route.js"></script>
    <script src="lib/ui-bootstrap-tpls-0.6.0.min.js"></script>
    <script src="lib/jquery-1.7.1.js"></script>
    <script src="lib/bootstrap.js"></script>
    <script src='lib/xeditable.min.js'></script>
    <script src="lib/socket.io.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/rest-services.js"></script>
    <style>

    </style>
</head>

<body ng-controller="MainCtrl">
     <div ng-view class='row-fluid' ng-class=" slide"></div>
</body>

</html>
<script>
    //var header = document.querySelector('#header');
    //var origOffsetY = header.offsetTop;

    function onScroll(e) {
        //window.scrollY >= origOffsetY ? header.classList.add('sticky') :
           // header.classList.remove('sticky');
    }

    document.addEventListener('scroll', onScroll);
</script>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.jhaws.common</groupId>
		<artifactId>jhaws-modules</artifactId>
		<version>5.0.3-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>jhaws-ldap</artifactId>
	<name>ldap classes</name>
	<description>ldap classes</description>
	<repositories>
		<repository>
			<id>atlassian</id>
			<url>http://repository.atlassian.com/maven2</url>
		</repository>
	</repositories>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.jhaws.common</groupId>
				<artifactId>jhaws-spring-bom</artifactId>
				<version>${project.version}</version>
				<type>pom</type>
				<scope>import</scope>				<!--http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html -->
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.ldap</groupId>
			<artifactId>spring-ldap-core</artifactId>
		</dependency>
		<!-- you can find this lib here: http://repository.atlassian.com/maven2/ -->
		<!-- http://repository.atlassian.com/maven2/com/sun/jndi/ldap/ldapbp/1.0/ -->
		<dependency>
			<groupId>com.sun</groupId>
			<artifactId>ldapbp</artifactId>
		</dependency>
		<!-- when using spring's ldap template -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>jhaws-logging</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>jhaws-lang</artifactId>
			<version>${project.version}</version>
		</dependency>
	</dependencies>
</project>