text:
#ifndef _UWDM_

#define _UWDM_
#pragma once

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <windows.h>
#include <process.h>
#include "soratypes.h"

#define MmNonCached                                         0
#define MmCached                                            1
#define MmWriteCombined                                     2

#define PAGED_CODE()

#define PsCreateSystemThread(...)                           0
#define PsTerminateSystemThread(...)
#define MmMapIoSpace(...)                                   0
#define KeSetSystemAffinityThread(pmask)                    UNREFERENCED_PARAMETER(pmask)

#define KeDelayExecutionThread(...)
#define IoGetDeviceObjectPointer(...)                       0
#define KeInitializeEvent(...)
#define IoBuildDeviceIoControlRequest(...)                  0
#define KeWaitForSingleObject(...)

#ifdef _VERBOSE_
	#define KdPrint(x)                                          printf x
	#define DbgPrint                                            printf
#else
	#define KdPrint(x)
	#define DbgPrint
#endif

#define IoGetNextIrpStackLocation(...)                      0
#define RtlInitUnicodeString(...)
#define KeReleaseSpinLock(...)

#define IoCallDriver(...)                                   0
#define KeAcquireSpinLock(a, b)                             UNREFERENCED_PARAMETER(b)
#define KeInitializeSpinLock(...)
#define ObDereferenceObject(...)
#define ObReferenceObject(...)
#define MmUnmapIoSpace(...)                                 ((void*)0)  /* prevent warning C4390 */

#define IoCreateNotificationEvent(...)                      0
#define KeSetEvent(...)
#define ZwClose(...)                                        0

#define InitializeListHead(pHead)                 \
    do { (pHead)->Flink = (pHead); (pHead)->Blink = (pHead); } while(0);

#define IsListEmpty(pHead) \
    ((pHead)->Flink == (pHead))

__inline VOID
InsertTailList(
    IN PLIST_ENTRY ListHead,
    IN PLIST_ENTRY Entry
    )
{
    PLIST_ENTRY Blink;

    Blink = ListHead->Blink;
    Entry->Flink = ListHead;
    Entry->Blink = Blink;
    Blink->Flink = Entry;
    ListHead->Blink = Entry;

}

__inline PLIST_ENTRY RemoveHeadList(IN PLIST_ENTRY ListHead)
{
    PLIST_ENTRY Flink;
    PLIST_ENTRY Entry;

    Entry = ListHead->Flink;
    Flink = Entry->Flink;
    ListHead->Flink = Flink;
    Flink->Blink = ListHead;
    return Entry;
}
__inline VOID InsertHeadList(
            IN PLIST_ENTRY ListHead,
            IN PLIST_ENTRY Entry
           )
{
    PLIST_ENTRY Flink;

    Flink = ListHead->Flink;
    Entry->Flink = Flink;
    Entry->Blink = ListHead;
    Flink->Blink = Entry;
    ListHead->Flink = Entry;
}

__inline BOOLEAN
RemoveEntryList(
    IN PLIST_ENTRY Entry
    )
{
    PLIST_ENTRY Blink;
    PLIST_ENTRY Flink;

    Flink = Entry->Flink;
    Blink = Entry->Blink;
    Blink->Flink = Flink;
    Flink->Blink = Blink;
    return (BOOLEAN)(Flink == Blink);
}

#define ASSERT(x)                       (assert(x))

#define IN
#define OUT
#define KernelMode

#define FALSE                           0
#define TRUE                            1

typedef VOID (*PKSTART_ROUTINE) (IN PVOID Context);

#define KIRQL                           long
#define VOID                            void

#define KSPIN_LOCK                      long
#define PHYSICAL_ADDRESS                LARGE_INTEGER

#define NTSTATUS                        long

#define STATUS_SUCCESS                  0
#define STATUS_UNSUCCESSFUL             ((NTSTATUS)0xC0000001L)

#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)

#define READ_REGISTER_ULONG(Register)          (*(volatile ULONG *)(Register))
#define WRITE_REGISTER_ULONG(Register, Value)  (*(volatile ULONG *)(Register) = (Value))

#define CONTAINING_RECORD(address, type, field) ((type *)( \
                                                  (PCHAR)(address) - \
                                                  (ULONG_PTR)(&((type *)0)->field)))
#define PRKTHREAD                       ULONG
#define KeGetCurrentThread(...)         (0)
#define KeSetPriorityThread(...)        (0)
#define KeBugCheck(...)
#define ExInitializeNPagedLookasideList(...)

#define ExDeleteNPagedLookasideList(...)
#define ExInitializeFastMutex(...)
#define KeGetCurrentIrql()            0

typedef struct _FAST_MUTEX
{
    unsigned __int32    unknown[8];
} FAST_MUTEX, *PFAST_MUTEX;

typedef struct _MDL
{
    struct _MDL *Next;
    short MdlSize;
    short MdlFlags;
    void * Process;
    ULONG *MappedSystemVa;
    ULONG *StartVa;
    ULONG ByteCount;
    ULONG ByteOffset;
} MDL;
typedef MDL *PMDL;

#ifdef _M_X64
typedef unsigned __int64 ULONG_PTR;
#else
typedef unsigned long   ULONG_PTR;
#endif

typedef ULONG NPAGED_LOOKASIDE_LIST, *PNPAGED_LOOKASIDE_LIST;

typedef char            *PCHAR;
typedef unsigned char   *PUCHAR;
typedef unsigned long   *PULONG;
typedef void            *PVOID;
typedef unsigned char   UCHAR;
typedef unsigned short  USHORT;

typedef unsigned long   ULONG;
typedef unsigned long   DWORD;
typedef long            LONG;
typedef long            *PFILE_OBJECT;
typedef long            *PDEVICE_OBJECT;
typedef unsigned short  *UNICODE_STRING;
typedef HANDLE          KEVENT;
typedef long            IRP, *PIRP;

typedef PVOID           PKEVENT;
typedef struct __IO_STACK_LOCATION
{
    void        *FileObject;
}IO_STACK_LOCATION, *PIO_STACK_LOCATION;

typedef struct __IO_STATUS_BLOCK
{
    long Status;
}IO_STATUS_BLOCK;

 typedef HANDLE 	 KMUTEX;
 typedef HANDLE 	 KSEMAPHORE;
 typedef int		 KPRIORITY;
 typedef PVOID		 POBJECT_ATTRIBUTES;

 __inline PHYSICAL_ADDRESS MmGetPhysicalAddress(PVOID va)
 {
     PHYSICAL_ADDRESS    PhysicalAddress      = {0, 0};
     UNREFERENCED_PARAMETER(va);
     PhysicalAddress.QuadPart = (UPOINTER)va;
     return PhysicalAddress;
 }

__inline PVOID ExAllocateFromNPagedLookasideList(PVOID p)
{
    UNREFERENCED_PARAMETER(p);
    return malloc(1024);
}

__inline void ExFreeToNPagedLookasideList(PVOID p, PVOID q)
{
    UNREFERENCED_PARAMETER(p);
    free(q);
}

__inline PVOID MmAllocateContiguousMemorySpecifyCache(ULONG size, ...)
{
    return malloc(size);
}
__inline void MmFreeContiguousMemorySpecifyCache(PVOID base, ...)
{
    free(base);
}

__inline void DbgBreakPoint(){}
#endif


text:
require 'spec_helper'

describe TemplateFileSerializer do
  let(:template_model) { Template.new }

  it 'exposes the attributes to be jsonified' do
    serialized = described_class.new(template_model).as_json
    expected_keys = [
      :name,
      :description,
      :keywords,
      :type,
      :documentation,
      :images
    ]
    expect(serialized.keys).to match_array expected_keys
  end

  describe '#to_yaml' do

    let(:template_model) do

      Template.new(
        name: 'foo',
        description: 'bar',
        keywords: 'fizz, bin',
        type: 'wordpress',
        documentation: "This\n\is\nthe\ndocumentation",
        images: [
          Image.new(
            name: 'abc',
            source: 'def',
            type: 'ghi',
            categories: ['jkl'],
            expose: [8000],
            environment: [{ 'variable' => 'mno', 'value' => 'pqr' }],
            volumes: [{ 'host_path' => '/tmp/foo', 'container_path' => '/tmp/bar' }],
            volumes_from: [{ 'service' => 'baz' }],
            deployment: { 'count' => 2 }
          )
        ]
      )
    end

    it 'yamlizes the model appropriately' do
      response = described_class.new(template_model).to_yaml

      expect(response).to eq <<-EXPECTED
---
name: foo
description: bar
keywords: fizz, bin
type: wordpress
documentation: |-
  This
  is
  the
  documentation
images:
- name: abc
  source: def
  category: jkl
  type: ghi
  expose:
  - 8000
  environment:
  - variable: mno
    value: pqr
  volumes:
  - host_path: "/tmp/foo"
    container_path: "/tmp/bar"
  volumes_from:
  - service: baz
  deployment:
    count: 2
      EXPECTED
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta name="viewport" content="width=device-width" />
    <meta charset="utf-8">
    <base href="https://wordbit.com">
    <title> Ten years of wordbit </title>
    <link rel="canonical" href="https://wordbit.com/posts/wordbit-ten-anniversary/">

<link rel="stylesheet" href="/css/poole.css">

<link rel="stylesheet" href="/css/lanyon.css">
<link rel="stylesheet" href="/css/custom.css">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox"
       xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">

    Home
    All Blog Posts
    Status Updates
    About

      © 2021. All rights reserved.

      wordbit

Ten years of wordbit

 Thu Feb 16, 2017

Ten years ago today, wordbit joined the blogosphere. A few years after that, the term blogosphere joined other buzzwords such as web 2.0 in the internet fad graveyard. I’m hoping social media will be joining them at some point.

But ten years ago, social media was still fun and innocent. Heck - ten years ago, there were no smartphones. The iPhone was to debut about four months later in a defining moment that changed the trajectory of the internet forever. Three years later, in 2010, Wired Magazine declared that “the Web is dead”. The Web, in case you didn’t know, meaning the World Wide Web (WWW) - a collection of html pages served up in desktop browsers. The Web’s death was greatly exaggerated of course - you can thank responsive web design for that.

Then again, there are millions of people who use Facebook but have no idea that Facebook exists on the Internet. Zuckerberg hooked even the most technophobic on the Internet without them even knowing it.

Yes, the world is a different place - but where does that leave the humble blog?

There is no easy answer to that question. In fact, I would argue that the question does not matter.

You’ve probably heard some rendition of “the blog is dead” for many years now. Perhaps that is concerning for those with money at stake. When blogs started generating traffic, along came metrics, advertising, blog rolls, comments, SEO, google analytics, and so on. Without these trappings, you could argue that a blog is nothing but a pulpit in the wilderness. But that is exactly what blogs started out as. That is what a blog really is, in its purest essence.

Here is the world’s first web page. It is nothing more than some text and links - the ultimate content delivery medium (second only to the paper page of a book, a content delivery platform honed over hundreds of years).

Why is it that writers crave a content authoring GUI on the back-end that is clean, simple, and clutter-free? It is ostensibly so that they can focus on their writing without distraction. How hypocritical then, that we save the clutter for the front-end - for the user. Who is the user? It is blindingly simple. When it comes to blogs, the user is only one thing - the user is a reader.

Always respect the reader.

If you’re writing on the web to make a living, then you have my sympathies. In all likelihood, you have moved on to serving bite-sized content for social media junkies to snack on. But for writers who just want to write, there is simply no better medium than the blog - preferably a good old html page served up in under one second.

In under one second you say? Seems like a good time to list the tools I use to accomplish this. As I’ve previously mentioned, I’ve moved on to a static site generator, Hugo, instead of wasting precious seconds with a database call, as you would with Wordpress. The site is hosted on Github, a tool which software developers use as a code respository with version control. I author in Markdown. I use StackEdit as an online markdown editor, mostly because it syncs so nicely with files in Google Drive. I should mention that this authoring setup is gaining favour in the technical writing world as well. In progressive circles at least.

So, wordbit’s design has evolved to meet my ideal of ultimate reader friendliness, and I’m proud of that. But coming up with content is as challenging as its always been. No writer should assume that people have nothing better to do than read their writing, because these days people have plenty to occupy their time. The toughest part for any writer is coming up with a big idea, then staying on point and writing a focused piece of work that doesn’t ramble and stray from the topic. Blogs are a fickle beast because they started as online diaries and have evolved into many things, including legitimate journalism. At best, a blog post is simply an editorial that is interesting to read. If you keep coming back then it is the voice of the writer that appeals to you.

Anyway, I’ve long since given up on pandering to anyone, and mostly just write for my own benefit. But writing in a public medium is always a struggle between maintaining a degree of privacy, being honest, and staying relevant. After all, ten years ago I was at a different stage of life. My priorities have changed, the topics I’m comfortable writing about have changed, and the goals for my blog has changed.

What hasn’t changed is that I still have that compulsion to write that plagues writers everywhere, and that’s not going to end while I’m still breathing. So, here’s to another decade of wordbit. I’ve made it this far - why stop now?

      « Previous: Gratitude

    Next:    A foray into fitness tracking »


text:
import os
import sys
import json
import argparse
import glob
from munch import Munch
import re
from ortools.linear_solver import pywraplp
import math
from pathlib import Path
import datetime

# TODO: only upload slow stats
# TODO: allow non-optimal solutions

parser = argparse.ArgumentParser()
parser.add_argument('-b', '--bins', required=True)
parser.add_argument('-d', '--durations', required=True)
parser.add_argument('-m', '--minutes', type=int, required=True) # one hour of test time becomes 6 builds
parser.add_argument(      '--beta', default=False, action='store_true')
parser.add_argument('-s', '--slow', default=False, action='store_true')
args = parser.parse_args()

def publish(var, value):
  with open(os.environ['GITHUB_ENV'], 'a') as f:
    print(f"{var}={value}")
    print(f"{var}={value}", file=f)

class NoTestError(Exception):
  pass
class FailedError(Exception):
  pass
class Tests:
  def __init__(self):
    self.tests = []

  def load(self, timings):
    with open(timings) as f:
      tests = json.load(f, object_hook=Munch.fromDict)
      for name, test in tests.items():
        test.name = name
      self.tests = tests.values()

  def balance(self):
    tests = [test for test in self.tests if not test.slow or args.slow]
    self.seconds = sum([test.seconds for test in tests])
    solver = pywraplp.Solver.CreateSolver('SCIP')

    data = Munch(
      weights = [test.seconds for test in tests],
      tests = list(range(len(tests))),
      bins = list(range(len(tests))),
      bin_capacity = math.ceil(max([test.seconds for test in tests] + [ args.minutes * 60 ]))
    )
    print('Total test time:', str(datetime.timedelta(seconds=sum(data.weights))))
    # https://developers.google.com/optimization/bin/bin_packing
    # x[i, j] = 1 if item i is packed in bin j.
    x = {
      (i, j): solver.IntVar(0, 1, f'x_{i}_{j}')
      for i in data.tests
      for j in data.bins
    }
    # y[j] = 1 if bin j is used.
    y = {
      j: solver.IntVar(0, 1, 'y[%i]' % j)
      for j in data.bins
    }
    # constraints
    # Each item must be in exactly one bin.
    for i in data.tests:
      solver.Add(sum(x[i, j] for j in data.bins) == 1)
    # The amount packed in each bin cannot exceed its capacity.
    for j in data.bins:
      solver.Add(sum(x[(i, j)] * data.weights[i] for i in data.tests) <= y[j] * data.bin_capacity)
    # Objective: minimize the number of bins used.
    solver.Minimize(solver.Sum([y[j] for j in data.bins]))

    solution = solver.Solve()
    if solution != pywraplp.Solver.OPTIMAL:
      raise ValueError('No optimal solution')
    bins = {}
    slow = {}
    for j in data.bins:
      if y[j].solution_value() == 1:
        bin_tests = []
        bin_weight = 0
        for i in data.tests:
          if x[i, j].solution_value() > 0:
            bin_tests.append(tests[i])
            bin_weight += data.weights[i]
        if bin_weight > 0:
          slow[j] = [test.name for test in bin_tests if test.slow]
          if len(slow[j]) == 0:
            del slow[j]
          bins[j] = bin_tests
    # put shortest bin first, since bin 0 will also get all tests not already assigned to a bin
    self.bins = sorted(bins.values(), key=lambda cluster: sum([test.seconds for test in cluster]))
    print('Time: ', math.ceil(solver.WallTime()/ 1000), 'seconds')
    print('Bins:', [ str(datetime.timedelta(seconds=sum([test.seconds for test in cluster]))) for cluster in self.bins ])
    if len(slow):
      print('Slow:')
      for _bin, tests in slow.items():
        for test in tests:
          print(' ', _bin, ':', test)

    Path(os.path.dirname(args.bins)).mkdir(parents=True, exist_ok=True)
    with open(args.bins, 'w') as f:
      json.dump([[test.name for test in cluster] for cluster in self.bins], f, indent='  ')

Tests = Tests()
Tests.load(args.durations)
Tests.balance()
publish('test_bins', json.dumps(list(range(len(Tests.bins)))))

clients = ['zotero', 'jurism']
if args.beta:
  clients += [client + '-beta' for client in clients]

publish('test_clients', json.dumps(clients))


text:
//           Copyright Matthew Pulver 2018 - 2019.
// Distributed under the Boost Software License, Version 1.0.
//      (See accompanying file LICENSE_1_0.txt or copy at
//           https://www.boost.org/LICENSE_1_0.txt)

#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>

template <typename T>
T fourth_power(T const& x) {
  T x4 = x * x;  // retval in operator*() uses x4's memory via NRVO.
  x4 *= x4;      // No copies of x4 are made within operator*=() even when squaring.
  return x4;     // x4 uses y's memory in main() via NRVO.
}

int main() {
  using namespace boost::math::differentiation;

  constexpr unsigned Order = 5;                  // Highest order derivative to be calculated.
  auto const x = make_fvar<double, Order>(2.0);  // Find derivatives at x=2.
  auto const y = fourth_power(x);
  for (unsigned i = 0; i <= Order; ++i)
    std::cout << "y.derivative(" << i << ") = " << y.derivative(i) << std::endl;
  return 0;
}
/*
Output:
y.derivative(0) = 16
y.derivative(1) = 32
y.derivative(2) = 48
y.derivative(3) = 48
y.derivative(4) = 24
y.derivative(5) = 0
**/


text:
* [Components](basics/components.md)
* [Layouts](basics/layouts.md)
* [Utilities](basics/utilities.md)


text:
@interface DYContinuation : NSObject
{
    struct dispatch_queue_s *queue;
    CDUnknownBlockType block;
    _Bool cancelled;
}

- (void)dispatch;
- (void)dealloc;
- (id)initWithQueue:(struct dispatch_queue_s *)arg1 block:(CDUnknownBlockType)arg2;
- (id)init;

@end


text:
FactoryGirl.define do
  factory :user do
    sequence(:email) {|i| "john+#{i}@factories.example.com" }
    sequence(:password) {|i| "my-password-#{i}" }
  end

  factory :test do
    association(:user)
    sequence(:url) {|i| "https://#{i}.example.com/test" }
    breed 'get'
  end

  factory :test_run do
    association(:user)
    association(:test)
  end

  factory :check do
    association(:test)
  end

  factory :hook do
    association(:test)
    url "https://www.example.com/test"
    name "A Hook Name"
  end

end


text:
using System;

/// <summary>
/// Char.IsLetter(Char)
/// Indicates whether the specified Unicode character is categorized as a letter.
/// </summary>
public class CharIsLetter
{
    public static int Main()
    {
        CharIsLetter testObj = new CharIsLetter();

        TestLibrary.TestFramework.BeginTestCase("for method: Char.IsLetter(Char)");
        if (testObj.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }

    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;

        return retVal;
    }
    #region Positive tests
    public bool PosTest1()
    {
        //Generate the character for validate
        char ch = 'a';

        return this.DoTest("PosTest1: Letter character",
                                  "P001", "001", "002", ch, true);
    }

    public bool PosTest2()
    {
        //Generate a non  character for validate
        char ch = TestLibrary.Generator.GetCharNumber(-55);
        return this.DoTest("PosTest2: Non letter character.",
                                  "P002", "003", "004", ch, false);
    }
    #endregion

    #region Helper method for positive tests
    private bool DoTest(string testDesc,
                                string testId,
                                string errorNum1,
                                string errorNum2,
                                char ch,
                                bool expectedResult)
    {
        bool retVal = true;
        string errorDesc;

        TestLibrary.TestFramework.BeginScenario(testDesc);
        try
        {
            bool actualResult = char.IsLetter(ch);
            if (expectedResult != actualResult)
            {
                if (expectedResult)
                {
                    errorDesc = string.Format("Character \\u{0:x} should belong to letter characters.", (int)ch);
                }
                else
                {
                    errorDesc = string.Format("Character \\u{0:x} does not belong to letter characters.", (int)ch);
                }

                TestLibrary.TestFramework.LogError(errorNum1+ " TestId-" + testId, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            errorDesc = "Unexpected exception: " + e;
            errorDesc += string.Format("\nCharacter is \\u{0:x}", ch);
            TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
            retVal = false;
        }

        return retVal;
    }
    #endregion
}


text:
<!DOCTYPE html>

    <title>Activate tools example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
    <meta name="mobile-web-app-capable" content="yes" />

    <gmf-map id="map" gmf-map-map="ctrl.map"></gmf-map>

      <button ngeo-btn class="btn btn-primary" ng-model="ctrl.drawPoint.active">Point</button>
      <button ngeo-btn class="btn btn-primary" ng-model="ctrl.drawLine.active">Line</button>
      <button ngeo-btn class="btn btn-primary" ng-model="ctrl.drawPolygon.active">Polygon</button>

      This example shows how to use
      ngeo.misc.ToolActivate
      objects with the
      ngeo.misc.ToolActivateMgrto active only one map control at once. If none draw control is choose, the click on the map is
      enabled.


text:
// This file was GENERATED by command:
//     pump.py callback.h.pump
// DO NOT EDIT BY HAND!!!

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_CALLBACK_H_
#define BASE_CALLBACK_H_
#pragma once

#include "base/callback_forward.h"
#include "base/callback_internal.h"
#include "base/template_util.h"

// NOTE: Header files that do not require the full definition of Callback or
// Closure should #include "base/callback_forward.h" instead of this file.

// WHAT IS THIS:
//
// The templated Callback class is a generalized function object. Together
// with the Bind() function in bind.h, they provide a type-safe method for
// performing currying of arguments, and creating a "closure."
//
// In programming languages, a closure is a first-class function where all its
// parameters have been bound (usually via currying).  Closures are well
// suited for representing, and passing around a unit of delayed execution.
// They are used in Chromium code to schedule tasks on different MessageLoops.
//
//
// MEMORY MANAGEMENT AND PASSING
//
// The Callback objects themselves should be passed by const-reference, and
// stored by copy. They internally store their state via a refcounted class
// and thus do not need to be deleted.
//
// The reason to pass via a const-reference is to avoid unnecessary
// AddRef/Release pairs to the internal state.
//
//
// EXAMPLE USAGE:
//
// /* Binding a normal function. */
// int Return5() { return 5; }
// base::Callback<int(void)> func_cb = base::Bind(&Return5);
// LOG(INFO) << func_cb.Run();  // Prints 5.
//
// void PrintHi() { LOG(INFO) << "hi."; }
// base::Closure void_func_cb = base::Bind(&PrintHi);
// void_func_cb.Run();  // Prints: hi.
//
// /* Binding a class method. */
// class Ref : public RefCountedThreadSafe<Ref> {
//  public:
//   int Foo() { return 3; }
//   void PrintBye() { LOG(INFO) << "bye."; }
// };
// scoped_refptr<Ref> ref = new Ref();
// base::Callback<int(void)> ref_cb = base::Bind(&Ref::Foo, ref.get());
// LOG(INFO) << ref_cb.Run();  // Prints out 3.
//
// base::Closure void_ref_cb = base::Bind(&Ref::PrintBye, ref.get());
// void_ref_cb.Run();  // Prints: bye.
//
// /* Binding a class method in a non-refcounted class.
//  *
//  * WARNING: You must be sure the referee outlives the callback!
//  *          This is particularly important if you post a closure to a
//  *          MessageLoop because then it becomes hard to know what the
//  *          lifetime of the referee needs to be.
//  */
// class NoRef {
//  public:
//   int Foo() { return 4; }
//   void PrintWhy() { LOG(INFO) << "why???"; }
// };
// NoRef no_ref;
// base::Callback<int(void)> base::no_ref_cb =
//     base::Bind(&NoRef::Foo, base::Unretained(&no_ref));
// LOG(INFO) << ref_cb.Run();  // Prints out 4.
//
// base::Closure void_no_ref_cb =
//     base::Bind(&NoRef::PrintWhy, base::Unretained(no_ref));
// void_no_ref_cb.Run();  // Prints: why???
//
// /* Binding a reference. */
// int Identity(int n) { return n; }
// int value = 1;
// base::Callback<int(void)> bound_copy_cb = base::Bind(&Identity, value);
// base::Callback<int(void)> bound_ref_cb =
//     base::Bind(&Identity, base::ConstRef(value));
// LOG(INFO) << bound_copy_cb.Run();  // Prints 1.
// LOG(INFO) << bound_ref_cb.Run();  // Prints 1.
// value = 2;
// LOG(INFO) << bound_copy_cb.Run();  // Prints 1.
// LOG(INFO) << bound_ref_cb.Run();  // Prints 2.
//
// /* Currying parameters. This also works for methods. */
// int Sum(int a, int b, int c) {
//   return a + b + c;
// }
// base::Callback<int(int, int)> sum3_cb = base::Bind(&Sum, 3);
// LOG(INFO) << sum3_cb.Run(4, 5);  // Prints 12.
//
// base::Callback<int(int)> sum7_cb = base::Bind(&Sum, 3, 4);
// LOG(INFO) << sum7_cb.Run(10);  // Prints 17.
//
//
// WHERE IS THIS DESIGN FROM:
//
// The design Callback and Bind is heavily influenced by C++'s
// tr1::function/tr1::bind, and by the "Google Callback" system used inside
// Google.
//
//
// HOW THE IMPLEMENTATION WORKS:
//
// There are three main components to the system:
//   1) The Callback classes.
//   2) The Bind() functions.
//   3) The arguments wrappers (e.g., Unretained() and ConstRef()).
//
// The Callback classes represent a generic function pointer. Internally,
// it stores a refcounted piece of state that represents the target function
// and all its bound parameters.  Each Callback specialization has a templated
// constructor that takes an BindState<>*.  In the context of the constructor,
// the static type of this BindState<> pointer uniquely identifies the
// function it is representing, all its bound parameters, and a Run() method
// that is capable of invoking the target.
//
// Callback's constructor takes the BindState<>* that has the full static type
// and erases the target function type as well as the types of the bound
// parameters.  It does this by storing a pointer to the specific Run()
// function, and upcasting the state of BindState<>* to a
// BindStateBase*. This is safe as long as this BindStateBase pointer
// is only used with the stored Run() pointer.
//
// To BindState<> objects are created inside the Bind() functions.
// These functions, along with a set of internal templates, are responsible for
//
//  - Unwrapping the function signature into return type, and parameters
//  - Determining the number of parameters that are bound
//  - Creating the BindState storing the bound parameters
//  - Performing compile-time asserts to avoid error-prone behavior
//  - Returning an Callback<> with an arity matching the number of unbound
//    parameters and that knows the correct refcounting semantics for the
//    target object if we are binding a method.
//
// The Bind functions do the above using type-inference, and template
// specializations.
//
// By default Bind() will store copies of all bound parameters, and attempt
// to refcount a target object if the function being bound is a class method.
//
// To change this behavior, we introduce a set of argument wrappers
// (e.g., Unretained(), and ConstRef()).  These are simple container templates
// that are passed by value, and wrap a pointer to argument.  See the
// file-level comment in base/bind_helpers.h for more info.
//
// These types are passed to the Unwrap() functions, and the MaybeRefcount()
// functions respectively to modify the behavior of Bind().  The Unwrap()
// and MaybeRefcount() functions change behavior by doing partial
// specialization based on whether or not a parameter is a wrapper type.
//
// ConstRef() is similar to tr1::cref.  Unretained() is specific to Chromium.
//
//
// WHY NOT TR1 FUNCTION/BIND?
//
// Direct use of tr1::function and tr1::bind was considered, but ultimately
// rejected because of the number of copy constructors invocations involved
// in the binding of arguments during construction, and the forwarding of
// arguments during invocation.  These copies will no longer be an issue in
// C++0x because C++0x will support rvalue reference allowing for the compiler
// to avoid these copies.  However, waiting for C++0x is not an option.
//
// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
// tr1::bind call itself will invoke a non-trivial copy constructor three times
// for each bound parameter.  Also, each when passing a tr1::function, each
// bound argument will be copied again.
//
// In addition to the copies taken at binding and invocation, copying a
// tr1::function causes a copy to be made of all the bound parameters and
// state.
//
// Furthermore, in Chromium, it is desirable for the Callback to take a
// reference on a target object when representing a class method call.  This
// is not supported by tr1.
//
// Lastly, tr1::function and tr1::bind has a more general and flexible API.
// This includes things like argument reordering by use of
// tr1::bind::placeholder, support for non-const reference parameters, and some
// limited amount of subtyping of the tr1::function object (e.g.,
// tr1::function<int(int)> is convertible to tr1::function<void(int)>).
//
// These are not features that are required in Chromium. Some of them, such as
// allowing for reference parameters, and subtyping of functions, may actually
// become a source of errors. Removing support for these features actually
// allows for a simpler implementation, and a terser Currying API.
//
//
// WHY NOT GOOGLE CALLBACKS?
//
// The Google callback system also does not support refcounting.  Furthermore,
// its implementation has a number of strange edge cases with respect to type
// conversion of its arguments.  In particular, the argument's constness must
// at times match exactly the function signature, or the type-inference might
// break.  Given the above, writing a custom solution was easier.
//
//
// MISSING FUNCTIONALITY
//  - Invoking the return of Bind.  Bind(&foo).Run() does not work;
//  - Binding arrays to functions that take a non-const pointer.
//    Example:
//      void Foo(const char* ptr);
//      void Bar(char* ptr);
//      Bind(&Foo, "test");
//      Bind(&Bar, "test");  // This fails because ptr is not const.

namespace base {

// First, we forward declare the Callback class template. This informs the
// compiler that the template only has 1 type parameter which is the function
// signature that the Callback is representing.
//
// After this, create template specializations for 0-7 parameters. Note that
// even though the template typelist grows, the specialization still
// only has one type: the function signature.
//
// If you are thinking of forward declaring Callback in your own header file,
// please include "base/callback_forward.h" instead.
template <typename Sig>
class Callback;

namespace internal {
template <typename Runnable, typename RunType, typename BoundArgsType>
struct BindState;
}  // namespace internal

template <typename R>
class Callback<R(void)> : public internal::CallbackBase {
 public:
  typedef R(RunType)();

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run() const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get());
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*);

};

template <typename R, typename A1>
class Callback<R(A1)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType);

};

template <typename R, typename A1, typename A2>
class Callback<R(A1, A2)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType);

};

template <typename R, typename A1, typename A2, typename A3>
class Callback<R(A1, A2, A3)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2, A3);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2,
        typename internal::CallbackParamTraits<A3>::ForwardType a3) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2),
             internal::CallbackForward(a3));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType,
          typename internal::CallbackParamTraits<A3>::ForwardType);

};

template <typename R, typename A1, typename A2, typename A3, typename A4>
class Callback<R(A1, A2, A3, A4)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2, A3, A4);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2,
        typename internal::CallbackParamTraits<A3>::ForwardType a3,
        typename internal::CallbackParamTraits<A4>::ForwardType a4) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2),
             internal::CallbackForward(a3),
             internal::CallbackForward(a4));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType,
          typename internal::CallbackParamTraits<A3>::ForwardType,
          typename internal::CallbackParamTraits<A4>::ForwardType);

};

template <typename R, typename A1, typename A2, typename A3, typename A4,
    typename A5>
class Callback<R(A1, A2, A3, A4, A5)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2, A3, A4, A5);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2,
        typename internal::CallbackParamTraits<A3>::ForwardType a3,
        typename internal::CallbackParamTraits<A4>::ForwardType a4,
        typename internal::CallbackParamTraits<A5>::ForwardType a5) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2),
             internal::CallbackForward(a3),
             internal::CallbackForward(a4),
             internal::CallbackForward(a5));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType,
          typename internal::CallbackParamTraits<A3>::ForwardType,
          typename internal::CallbackParamTraits<A4>::ForwardType,
          typename internal::CallbackParamTraits<A5>::ForwardType);

};

template <typename R, typename A1, typename A2, typename A3, typename A4,
    typename A5, typename A6>
class Callback<R(A1, A2, A3, A4, A5, A6)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2, A3, A4, A5, A6);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2,
        typename internal::CallbackParamTraits<A3>::ForwardType a3,
        typename internal::CallbackParamTraits<A4>::ForwardType a4,
        typename internal::CallbackParamTraits<A5>::ForwardType a5,
        typename internal::CallbackParamTraits<A6>::ForwardType a6) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2),
             internal::CallbackForward(a3),
             internal::CallbackForward(a4),
             internal::CallbackForward(a5),
             internal::CallbackForward(a6));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType,
          typename internal::CallbackParamTraits<A3>::ForwardType,
          typename internal::CallbackParamTraits<A4>::ForwardType,
          typename internal::CallbackParamTraits<A5>::ForwardType,
          typename internal::CallbackParamTraits<A6>::ForwardType);

};

template <typename R, typename A1, typename A2, typename A3, typename A4,
    typename A5, typename A6, typename A7>
class Callback<R(A1, A2, A3, A4, A5, A6, A7)> : public internal::CallbackBase {
 public:
  typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7);

  Callback() : CallbackBase(NULL) { }

  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
  // return the exact Callback<> type.  See base/bind.h for details.
  template <typename Runnable, typename RunType, typename BoundArgsType>
  Callback(internal::BindState<Runnable, RunType, BoundArgsType>* bind_state)
      : CallbackBase(bind_state) {

    // Force the assignment to a local variable of PolymorphicInvoke
    // so the compiler will typecheck that the passed in Run() method has
    // the correct type.
    PolymorphicInvoke invoke_func =
        &internal::BindState<Runnable, RunType, BoundArgsType>
            ::InvokerType::Run;
    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
  }

  bool Equals(const Callback& other) const {
    return CallbackBase::Equals(other);
  }

  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
        typename internal::CallbackParamTraits<A2>::ForwardType a2,
        typename internal::CallbackParamTraits<A3>::ForwardType a3,
        typename internal::CallbackParamTraits<A4>::ForwardType a4,
        typename internal::CallbackParamTraits<A5>::ForwardType a5,
        typename internal::CallbackParamTraits<A6>::ForwardType a6,
        typename internal::CallbackParamTraits<A7>::ForwardType a7) const {
    PolymorphicInvoke f =
        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);

    return f(bind_state_.get(), internal::CallbackForward(a1),
             internal::CallbackForward(a2),
             internal::CallbackForward(a3),
             internal::CallbackForward(a4),
             internal::CallbackForward(a5),
             internal::CallbackForward(a6),
             internal::CallbackForward(a7));
  }

 private:
  typedef R(*PolymorphicInvoke)(
      internal::BindStateBase*,
          typename internal::CallbackParamTraits<A1>::ForwardType,
          typename internal::CallbackParamTraits<A2>::ForwardType,
          typename internal::CallbackParamTraits<A3>::ForwardType,
          typename internal::CallbackParamTraits<A4>::ForwardType,
          typename internal::CallbackParamTraits<A5>::ForwardType,
          typename internal::CallbackParamTraits<A6>::ForwardType,
          typename internal::CallbackParamTraits<A7>::ForwardType);

};

// Syntactic sugar to make Callbacks<void(void)> easier to declare since it
// will be used in a lot of APIs with delayed execution.
typedef Callback<void(void)> Closure;

}  // namespace base

#endif  // BASE_CALLBACK_H


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Text } from '../Text'
import { Image } from '../Image'
import { Link } from '../Link'

const Diory = ({onClick, children, ...diory}) => {
  const {text, image, link, style = {}} = diory
  const {image: imageStyle, text: textStyle, link: linkStyle, ...dioryStyle} = style
  return (
    <div
      style={dioryStyle}
      onClick={event => onClick && onClick({diory, event})}
    >
      <div style={{position: 'relative', height: '100%'}}>
        {image && <Image image={image} style={imageStyle}/>}
        {text && <Text text={text} style={textStyle} />}
        {link && <Link {...{link}} style={linkStyle}/>}
        {children}
      </div>
    </div>
  )
}

Diory.propTypes = {
  text: PropTypes.string,
  image: PropTypes.string,
  link: PropTypes.string,
  style: PropTypes.shape({
    diory: PropTypes.object,
    image: PropTypes.object,
    text: PropTypes.object,
    link: PropTypes.object,
  }),
  onClick: PropTypes.func,
  children: PropTypes.node,
}

export default Diory


text:
<?php include('MyFunctions.inc.php');

$step = $_POST["step"];
echo ("Step is $step");
if($step != '1')
{

  if (isset($_GET["id"])) $id = $_GET["id"]; else $id = "";
  if (!empty($id))
  {
    // We modify an existing reminder
    $result = mysql_query( "SELECT * FROM `skmadmins` where `id`='$id'" )
			or die (mysql_error()."
Couldn't execute query: $query");
    $row = mysql_fetch_array( $result );
    $login = $row["login"];
    $firstname = $row["firstname"];
    $lastname = $row["lastname"];
    echo ("$login\n");
  }
?>

<TITLE>Add Modify skmadmins</TITLE>
<LINK REL=STYLESHEET HREF="skm.css" TYPE="text/css">

<?php start_main_frame(" SKM  > Add/Modify Admins"); ?>
<?php start_left_pane(); ?>
<?php display_menu(); ?>
<?php end_left_pane(); ?>
<?php start_right_pane(); ?>

    <form name="skmadmins_setup" action="skmadmins_setup.php" method="post">
    <fieldset><legend>Add / Modify SKM admin account</legend>

        First name :

        <input name="firstname" size="50" type="text" maxlength="255" value="<?php echo("$firstname"); ?>">

        Last name :

        <input name="lastname" size="50" type="text" maxlength="255" value="<?php echo("$lastname"); ?>">

        Login name :

        <input name="login" size="50" type="text" maxlength="255" value="<?php echo("$login"); ?>">

        Password :

        <input name="password" type="password" class="textfield" id="password" />

      </fieldset>

      <input name="step" type="hidden" value="1">
      <input name="id" type="hidden" value="<?php echo("$id");?>">
      <input name="submit" type="submit" value="submit">

    </form>

<? end_right_pane(); ?>
<? end_main_frame(); ?>

<?php
}
else
{
    $id = $_POST['id'];
   	$login = $_POST['login'];
   	$passwd = $_POST['password'];
   	$firstname = $_POST['firstname'];
   	$lastname = $_POST['lastname'];

    if(empty($id)){
    // this is a new account
      $query = "INSERT INTO `skmadmins` (`login`,`passwd`,`firstname`,`lastname` ) VALUES('$login','".md5($_POST['password'])."','$firstname','$lastname')";
      mysql_query( $query ) or die(mysql_error()."
Couldn't execute query: $query");
      header("Location:skmadmins.php");
      echo ("Account Added, redirecting...");
      exit ();
    } else {
      $query = "UPDATE `skmadmins` SET `login` = '$login', `passwd`='".md5($_POST['password'])."', `firstname`='$firstname', `lastname`='$lastname'  WHERE `id` = '$id' " ;
      mysql_query( $query ) or die(mysql_error()."
Couldn't execute query: $query");
      // Let's go to the Reminder List page
      header("Location:skmadmins.php");
      echo ("Account Modified, redirecting...");
      exit ();
    }

}
?>


text:
package org.broadinstitute.hellbender.tools.dataflow.transforms.bqsr;

import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.ParDo;
import com.google.cloud.dataflow.sdk.values.PCollection;
import htsjdk.samtools.SAMFileHeader;
import org.broadinstitute.hellbender.engine.filters.ReadFilter;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.read.GATKRead;

import java.io.Serializable;

/**
 * A simple filter for reads on dataflow
 */
public final class DataflowReadFilter extends PTransform<PCollection<GATKRead>, PCollection<GATKRead>> {
    private static final long serialVersionUID = 1L;

    private final ReadFilter readFilter;
    private final SAMFileHeader header;

    /**
     * ReadsFilter will use the given header to interpret each read, and then let the Read through
     * if the passed filter accepts it.
     */
    public DataflowReadFilter( final ReadFilter filterToApply, final SAMFileHeader header ) {
        Utils.nonNull(filterToApply);
        Utils.nonNull(header);

        this.readFilter = filterToApply;
        this.header = header;
    }

    /**
     * Filter out reads we don't want.
     */
    @Override
    public PCollection<GATKRead> apply(PCollection<GATKRead> in) {
        return in.apply(ParDo
                .named(readFilter.getClass().getSimpleName())
                .of(new DoFn<GATKRead, GATKRead>() {
                    private static final long serialVersionUID = 1L;
                    @Override
                    public void processElement(DoFn<GATKRead,GATKRead>.ProcessContext c) throws Exception {
                        GATKRead read = c.element();
                        if (readFilter.test(read)) {
                            c.output(read);
                        }
                    }
                }));
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
                android:layout_height="wrap_content"
              android:gravity="center"
    >
    <!--<LinearLayout-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!-->-->
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="4dp"
            android:src="@drawable/arrow_down"
            android:contentDescription="@null"
            />
        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="36dp"
            android:layout_height="36dp"
            android:padding="4dp"
            />
    <!--</LinearLayout>-->
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:text="@string/app_name"
        android:textColor="@color/color_999"
        android:layout_marginStart="5dp"
        android:layout_marginLeft="5dp"
        />
</LinearLayout>


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.
using Sce.Atf.Dom;

using VisualScript;
using VisualScript.VisualScriptBasicSchema;
using Sce.Atf.Controls.Adaptable.Graphs.CircuitBasicSchema;

namespace VisualScriptEditor
{
    ///
    /// Editing context for prototypes in the circuit document; this is the context that is
    /// bound to the PrototypeLister when a circuit document becomes the active context. This
    /// context implements instancing differently than the CircuitContext. It can insert modules
    /// and connections, converting them into prototypes. It can only copy and delete prototypes.
    public class PrototypingContext : Sce.Atf.Controls.Adaptable.Graphs.PrototypingContext
    {
        ///
        /// Gets ChildInfo for prototype folders in prototype folder
        protected override ChildInfo PrototypeFolderChildInfo
        {
            get { return visualScriptDocumentType.prototypeFolderChild; }
        }

        ///
        /// Gets type of prototype
        protected override DomNodeType PrototypeType
        {
            get { return prototypeType.Type; }
        }
    }
}


text:
class GpsInfo
{
	public:
		GpsInfo();
		Glib::Dispatcher dataReady;

		void getData(double& lat, double& lng, double& speed);

	protected:
		Glib::Thread *thread;
		void watch();
		Glib::Mutex mutex;
		double latitude, longitude, speed;
};

#endif


text:
//
//  RKEntityCache.h
//  RestKit
//
//  Created by Blake Watters on 5/2/12.
//  Copyright (c) 2012 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import <CoreData/CoreData.h>

@class RKEntityByAttributeCache;

/**
 Instances of RKInMemoryEntityCache provide an in-memory caching mechanism for
 objects in a Core Data managed object context. Managed objects can be cached by
 attribute for fast retrieval without repeatedly hitting the Core Data persistent store.
 This can provide a substantial speed advantage over issuing fetch requests
 in cases where repeated look-ups of the same data are performed using a small set
 of attributes as the query key. Internally, the cache entries are maintained as
 references to the NSManagedObjectID of corresponding cached objects.
 */
@interface RKEntityCache : NSObject

///-----------------------------------------------------------------------------
/// @name Initializing the Cache
///-----------------------------------------------------------------------------

/**
 Initializes the receiver with a managed object context containing the entity instances to be cached.

 @param context The managed object context containing objects to be cached.
 @returns self, initialized with context.
 */
- (id)initWithManagedObjectContext:(NSManagedObjectContext *)context;

/**
 The managed object context with which the receiver is associated.
 */
@property (nonatomic, strong, readonly) NSManagedObjectContext *managedObjectContext;

///------------------------------------
/// @name Caching Objects by Attributes
///------------------------------------

/**
 Caches all instances of an entity using the value for an attribute as the cache key.

 @param entity The entity to cache all instances of.
 @param attributeNames The attributes to cache the instances by.
 */
- (void)cacheObjectsForEntity:(NSEntityDescription *)entity byAttributes:(NSArray *)attributeNames;

/**
 Returns a Boolean value indicating if all instances of an entity have been cached by a given attribute name.

 @param entity The entity to check the cache status of.
 @param attributeNames The attributes to check the cache status with.
 @return YES if the cache has been loaded with instances with the given attribute, else NO.
 */
- (BOOL)isEntity:(NSEntityDescription *)entity cachedByAttributes:(NSArray *)attributeNames;

/**
 Retrieves the first cached instance of a given entity where the specified attribute matches the given value.

 @param entity The entity to search the cache for instances of.
 @param attributeValues The attribute values return a match for.
 @param context The managed object from which to retrieve the cached results.
 @return A matching managed object instance or nil.
 @raise NSInvalidArgumentException Raised if instances of the entity and attribute have not been cached.
 */
- (NSManagedObject *)objectForEntity:(NSEntityDescription *)entity withAttributeValues:(NSDictionary *)attributeValues inContext:(NSManagedObjectContext *)context;

/**
 Retrieves all cached instances of a given entity where the specified attribute matches the given value.

 @param entity The entity to search the cache for instances of.
 @param attributeValues The attribute values return a match for.
 @param context The managed object from which to retrieve the cached results.
 @return All matching managed object instances or nil.
 @raise NSInvalidArgumentException Raised if instances of the entity and attribute have not been cached.
 */
- (NSSet *)objectsForEntity:(NSEntityDescription *)entity withAttributeValues:(NSDictionary *)attributeValues inContext:(NSManagedObjectContext *)context;

///-----------------------------------------------------------------------------
// @name Accessing Underlying Caches
///-----------------------------------------------------------------------------

/**
 Retrieves the underlying entity attribute cache for a given entity and attribute.

 @param entity The entity to retrieve the entity attribute cache object for.
 @param attributeName  The attribute to retrieve the entity attribute cache object for.
 @return The entity attribute cache for the given entity and attribute, or nil if none was found.
 */
- (RKEntityByAttributeCache *)attributeCacheForEntity:(NSEntityDescription *)entity attributes:(NSArray *)attributeNames;

/**
 Retrieves all entity attributes caches for a given entity.

 @param entity The entity to retrieve the collection of entity attribute caches for.
 @return An array of entity attribute cache objects for the given entity or an empty array if none were found.
 */
- (NSArray *)attributeCachesForEntity:(NSEntityDescription *)entity;

///-----------------------------------------------------------------------------
// @name Managing the Cache
///-----------------------------------------------------------------------------

/**
 Flushes the entity cache by sending a flush message to each entity attribute cache
 contained within the receiver.

 @see [RKEntityByAttributeCache flush]
 */
- (void)flush;

/**
 Adds a given object to all entity attribute caches for the object's entity contained
 within the receiver.

 @param object The object to add to the appropriate entity attribute caches.
 */
- (void)addObject:(NSManagedObject *)object;

/**
 Removed a given object from all entity attribute caches for the object's entity contained
 within the receiver.

 @param object The object to remove from the appropriate entity attribute caches.
 */
- (void)removeObject:(NSManagedObject *)object;

@end


text:
from keras.callbacks import Callback
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from sklearn.metrics import confusion_matrix
import itertools
import numpy as np

class AccLossPlotter(Callback):
    """Plot training Accuracy and Loss values on a Matplotlib graph.

    The graph is updated by the 'on_epoch_end' event of the Keras Callback class

    # Arguments
        graphs: list with some or all of ('acc', 'loss')
        save_graph: Save graph as an image on Keras Callback 'on_train_end' event

    """

    def __init__(self, graphs=['acc', 'loss'], save_graph=False):
        self.graphs = graphs
        self.num_subplots = len(graphs)
        self.save_graph = save_graph

    def on_train_begin(self, logs={}):
        self.acc = []
        self.val_acc = []
        self.loss = []
        self.val_loss = []
        self.epoch_count = 0
        plt.ion()
        plt.show()

    def on_epoch_end(self, epoch, logs={}):
        self.epoch_count += 1
        self.val_acc.append(logs.get('val_acc'))
        self.acc.append(logs.get('acc'))
        self.loss.append(logs.get('loss'))
        self.val_loss.append(logs.get('val_loss'))
        epochs = [x for x in range(self.epoch_count)]

        count_subplots = 0

        if 'acc' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Accuracy')
            #plt.axis([0,100,0,1])
            plt.plot(epochs, self.val_acc, color='r')
            plt.plot(epochs, self.acc, color='b')
            plt.ylabel('accuracy')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)

        if 'loss' in self.graphs:
            count_subplots += 1
            plt.subplot(self.num_subplots, 1, count_subplots)
            plt.title('Loss')
            #plt.axis([0,100,0,5])
            plt.plot(epochs, self.val_loss, color='r')
            plt.plot(epochs, self.loss, color='b')
            plt.ylabel('loss')

            red_patch = mpatches.Patch(color='red', label='Test')
            blue_patch = mpatches.Patch(color='blue', label='Train')

            plt.legend(handles=[red_patch, blue_patch], loc=4)

        plt.draw()
        plt.pause(0.001)

    def on_train_end(self, logs={}):
        if self.save_graph:
            plt.savefig('training_acc_loss.png')

class ConfusionMatrixPlotter(Callback):
    """Plot the confusion matrix on a graph and update after each epoch

    # Arguments
        X_val: The input values
        Y_val: The expected output values
        classes: The categories as a list of string names
        normalize: True - normalize to [0,1], False - keep as is
        cmap: Specify matplotlib colour map
        title: Graph Title

    """
    def __init__(self, X_val, Y_val, classes, normalize=False, cmap=plt.cm.Blues, title='Confusion Matrix'):
        self.X_val = X_val
        self.Y_val = Y_val
        self.title = title
        self.classes = classes
        self.normalize = normalize
        self.cmap = cmap
        plt.ion()
        #plt.show()
        plt.figure()

        plt.title(self.title)

    def on_train_begin(self, logs={}):
        pass

    def on_epoch_end(self, epoch, logs={}):
        plt.clf()
        pred = self.model.predict(self.X_val)
        max_pred = np.argmax(pred, axis=1)
        max_y = np.argmax(self.Y_val, axis=1)
        cnf_mat = confusion_matrix(max_y, max_pred)

        if self.normalize:
            cnf_mat = cnf_mat.astype('float') / cnf_mat.sum(axis=1)[:, np.newaxis]

        thresh = cnf_mat.max() / 2.
        for i, j in itertools.product(range(cnf_mat.shape[0]), range(cnf_mat.shape[1])):
            plt.text(j, i, cnf_mat[i, j],
                         horizontalalignment="center",
                         color="white" if cnf_mat[i, j] > thresh else "black")

        plt.imshow(cnf_mat, interpolation='nearest', cmap=self.cmap)

        # Labels
        tick_marks = np.arange(len(self.classes))
        plt.xticks(tick_marks, self.classes, rotation=45)
        plt.yticks(tick_marks, self.classes)

        plt.colorbar()

        plt.tight_layout()
        plt.ylabel('True label')
        plt.xlabel('Predicted label')
        #plt.draw()
        plt.show()
        plt.pause(0.001)


text:
@protocol PSHeaderFooterView
- (id)initWithSpecifier:(id)arg1;

@optional
- (double)preferredHeightForWidth:(double)arg1 inTableView:(id)arg2;
- (double)preferredHeightForWidth:(double)arg1;
@end


text:
#include "pmac_cell.h"

#include "boost/numeric/ublas/matrix.hpp"
#include <cmath>
#include <float.h>

Pmac_cell::Pmac_cell()
    : occupied_count(DBL_MIN), free_count(DBL_MIN), entry(DBL_MIN), exit(DBL_MIN),
      prev_occ_prob(0.5), lastObservedTime(0.0), last_exit_cnt(DBL_MIN), last_entry_cnt(DBL_MIN),
      old_entry_cnt(DBL_MIN), old_exit_cnt(DBL_MIN), last_entry_residue(0.0), last_exit_residue(0.0),
      old_exit_residue(0.0), old_entry_residue(0.0), estimated_occupancy_prob(0.5)
{
}

void Pmac_cell::addProbability(double occ_prob, double timeStamp)
{
    lastObservedTime = timeStamp;

    if(occ_prob > 0.5)
    {
        double occupied_prob = (occ_prob - 0.5) * 2;
        occupied_count += occupied_prob;
        // occ state
        if(prev_occ_prob <= 0.5)
        {
            last_exit_residue = 0;
            last_exit_cnt = 0;
            double old_entry_residue_avg = old_entry_residue / old_entry_cnt;
            double current_entry_residue_avg = last_entry_residue / last_entry_cnt;

            if(current_entry_residue_avg > old_entry_residue_avg)
            {
                last_entry_residue = current_entry_residue_avg;
                old_entry_residue = 0.0;
                old_entry_cnt = 0.0;
            }
            else {
                last_entry_residue = old_entry_residue_avg;
            }
            last_transition = timeStamp;
        }

        // start counting the exit max up
        last_exit_residue += occupied_prob;
        ++last_exit_cnt;
        old_exit_residue += occupied_prob;
        ++old_exit_cnt;

        // increment entry event
        if(last_entry_residue > 0.0)
        {
            double next_entry_cnt = std::min(occupied_prob,last_entry_residue);
            entry += next_entry_cnt;
            last_entry_residue -= next_entry_cnt;
            old_entry_residue -= next_entry_cnt;
        }
    }
    else
    {
        double free_prob = (0.5 - occ_prob) * 2;
        free_count += free_prob;

        if(prev_occ_prob > 0.5)
        {
            last_entry_residue = 0;
            last_entry_cnt = 0;
            double old_exit_residue_avg = old_exit_residue / old_exit_cnt;
            double current_exit_residue_avg = last_exit_residue / last_exit_cnt;

            if(current_exit_residue_avg > old_exit_residue_avg)
            {
                last_exit_residue = current_exit_residue_avg;
                old_exit_residue = 0.0;
                old_exit_cnt = 0.0;
            }
            else {
                last_exit_residue = old_exit_residue_avg;
            }
            last_transition = timeStamp;
        }
        last_entry_residue += free_prob;
        ++last_entry_cnt;
        old_entry_residue += free_prob;
        ++old_entry_cnt;
        if(last_exit_residue > 0.0)
        {
            double next_exit_cnt = std::min(free_prob,last_exit_residue);
            exit += next_exit_cnt;
            last_exit_residue -= next_exit_cnt;
            old_exit_residue -= next_exit_cnt;
        }
    }
    prev_occ_prob = occ_prob;
    /*
    // recency weightning
    if(current_is_occupied)
    {
        // Adjust active state
        if(occupied_count > MAX_NO_OF_OBS)
        {
            exit *= double(MAX_NO_OF_OBS) / occupied_count;
            occupied_count = MAX_NO_OF_OBS;
        }
        // Adjust inactive state
        free_count= DBL_MIN + (free_count-DBL_MIN) * FORGET_FACTOR;
        exit = DBL_MIN + (exit-DBL_MIN) * FORGET_FACTOR;
    }
    else
    {
        // Adjust active state
        if(free_count > MAX_NO_OF_OBS)
        {
            entry *= double(MAX_NO_OF_OBS) / free_count;
            free_count = MAX_NO_OF_OBS;
        }
        // Adjust inactive state
        occupied_count = DBL_MIN + (occupied_count-DBL_MIN) * FORGET_FACTOR;
        entry = DBL_MIN + (entry-DBL_MIN) * FORGET_FACTOR;
    }
    */
    // Update estimated occupancy probability

    //correct
    estimated_occupancy_prob += 2*std::abs(occ_prob - 0.5)*(occ_prob - estimated_occupancy_prob);
}

double Pmac_cell::getLambdaExit()
{
    return exit / occupied_count; // a(2,1)
}

double Pmac_cell::getLambdaEntry()
{
    return entry / free_count; // a(1,2)
}

double Pmac_cell::getLongTermOccupancyProb()
{
    double lambda_entry = entry / free_count; // a(1,2)
    double lambda_exit = exit / occupied_count; // a(2,1)
    double occupancy_prob;
    if(lambda_exit < LAMBDA_EXIT_FOR_STATIC_OCCUPIED && occupied_count > free_count * OCC_FREE_RATION_FOR_STATIC_OCCUPIED)
    {
        occupancy_prob = STATIC_OCCUPIED_VALUE;
    }
    else
    {
        occupancy_prob = 1.0 / (lambda_exit + lambda_entry) * lambda_entry;
    }
    return occupancy_prob;
}

double Pmac_cell::getProjectedOccupancyProbability(unsigned noOfProjections)
{
    //predict
    double lambda_entry = entry / free_count; // a(1,2)
    double lambda_exit = exit / occupied_count; // a(2,1)

    double occupancy_prob;
    if(lambda_exit < LAMBDA_EXIT_FOR_STATIC_OCCUPIED && occupied_count > free_count * OCC_FREE_RATION_FOR_STATIC_OCCUPIED)
    {
        occupancy_prob = STATIC_OCCUPIED_VALUE;
    }
    else
    {
        for (int i = 0; i < noOfProjections; ++i) {
            estimated_occupancy_prob = (estimated_occupancy_prob*(1-lambda_exit) + (1-estimated_occupancy_prob)*lambda_entry);
        }
        occupancy_prob = estimated_occupancy_prob;
    }
    return occupancy_prob;
/*
    boost::numeric::ublas::matrix<double> marchovM(2,2);
    marchovM(0,0) = 1-lambda_exit;
    marchovM(0,1) = lambda_exit;
    marchovM(1,0) = lambda_entry;
    marchovM(1,1) = 1 - lambda_entry;

    boost::numeric::ublas::matrix<double> states(1,2);
    states(0,0) = 0.5;//prev_occ_prob;
    states(0,1) = 0.5;//1 - prev_occ_prob;

    for(unsigned i = 0; i < noOfProjections; i++){
        states = boost::numeric::ublas::prod(states, marchovM);
    }
    return states(0,0);
    */
}

double Pmac_cell::getTemporalPrediction(int forward_steps)
{
    /*
    double lambda_entry = (entry + 1) / (free_count + 1); // a(1,2)
    double lambda_exit = (exit + 1) / (occupied_count + 1); // a(2,1)

    lambda_entry = (lambda_entry > 1 ? 1 : lambda_entry);
    lambda_exit = (lambda_exit > 1 ? 1 : lambda_exit);

    int free_time = 1.0 / (1.0- lambda_entry);
    int occ_time = 1.0 / (1.0-lambda_exit);
    double weight = forward_steps / (free_time+occ_time);
    forward_steps %= (free_time+occ_time);
    double occ_value = 0;
    if(previous_is_occupied)
    {
        if(forward_steps > occ_time)
            occ_value = 0;
        else
            occ_value = 1;
    }
    else
    {
        if(occupied_count > 2)
        {
            if(forward_steps > free_time)
                occ_value = 1;
            else
                occ_value = 0;
        }
        else
            occ_value = 0;
    }

    occ_value *= 1.0/weight;

    return occ_value;
    */
    return -1;
}

double Pmac_cell::getLastTransitionTime()
{
    return last_transition;
}

void Pmac_cell::init(double initialOccupancy, double initialFree)
{
    prev_occ_prob = 0.5;
    if(initialOccupancy > initialFree)
    {
        occupied_count += initialOccupancy;
        exit = initialOccupancy/100;
    }
    else
    {
        free_count += initialFree;
        entry = initialFree/100;
    }
}

double Pmac_cell::observationSum()
{
    return free_count + occupied_count;
}

double Pmac_cell::getLastObservationTime()
{
    return lastObservedTime;
}

unsigned Pmac_cell::getMixingTime()
{
    double lambda_entry = entry / free_count; // a(1,2)
    double lambda_exit = exit / occupied_count; // a(2,1)

    return std::log(0.001*(lambda_entry/(lambda_entry+lambda_exit))) / (log(std::fabs(1-lambda_exit-lambda_entry)));
}

bool Pmac_cell::deserialize(const std::vector<double>& values)
{
    bool returnVal = false;
    if(values.size() == 5)
    {
        occupied_count = values[0];
        free_count = values[1];
        entry = values[2];
        exit = values[3];
        prev_occ_prob = values[4];
        lastObservedTime = 0;
        returnVal = true;
    }
    return returnVal;
}

std::vector<double> Pmac_cell::serialize()
{
    std::vector<double> result(5);
    result[0] = occupied_count;
    result[1] = free_count;
    result[2] = entry;
    result[3] = exit;
    result[4] = prev_occ_prob;
    return result;
}


text:
package org.motechproject.csd.service;

import org.joda.time.DateTime;
import org.motechproject.csd.domain.Facility;

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

/**
 * See {@link org.motechproject.csd.domain.Facility}
 */
public interface FacilityService {

    List<Facility> allFacilities();

    void deleteAll();

    Facility getFacilityByEntityID(String entityID);

    void update(Facility facility);

    void delete(String entityID);

    void update(Set<Facility> facilities);

    Set<Facility> getModifiedAfter(DateTime date);
}


text:
XBridgeTransactionsModel::XBridgeTransactionsModel()
{
    m_columns << trUtf8("TOTAL")
              << trUtf8("SIZE")
              << trUtf8("BID")
              << trUtf8("STATE")
              << trUtf8("FEE");

    xuiConnector.NotifyXBridgePendingTransactionReceived.connect
            (boost::bind(&XBridgeTransactionsModel::onTransactionReceived, this, _1));

    xuiConnector.NotifyXBridgeTransactionStateChanged.connect
            (boost::bind(&XBridgeTransactionsModel::onTransactionStateChanged, this, _1, _2));
    xuiConnector.NotifyXBridgeTransactionCancelled.connect
            (boost::bind(&XBridgeTransactionsModel::onTransactionCancelled, this, _1, _2, _3));

    VERIFY(connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimer())));
    m_timer.start(3000);
}

//******************************************************************************
//******************************************************************************
XBridgeTransactionsModel::~XBridgeTransactionsModel()
{
    xuiConnector.NotifyXBridgePendingTransactionReceived.disconnect
            (boost::bind(&XBridgeTransactionsModel::onTransactionReceived, this, _1));

    xuiConnector.NotifyXBridgeTransactionStateChanged.disconnect
            (boost::bind(&XBridgeTransactionsModel::onTransactionStateChanged, this, _1, _2));

    xuiConnector.NotifyXBridgeTransactionCancelled.disconnect
            (boost::bind(&XBridgeTransactionsModel::onTransactionCancelled, this, _1, _2, _3));
}

//******************************************************************************
//******************************************************************************
int XBridgeTransactionsModel::rowCount(const QModelIndex &) const
{
    return m_transactions.size();
}

//******************************************************************************
//******************************************************************************
int XBridgeTransactionsModel::columnCount(const QModelIndex &) const
{
    return m_columns.size();
}

//******************************************************************************
//******************************************************************************
QVariant XBridgeTransactionsModel::data(const QModelIndex & idx, int role) const
{
    if (!idx.isValid())
    {
        return QVariant();
    }

    if (idx.row() < 0 || idx.row() >= static_cast<int>(m_transactions.size()))
    {
        return QVariant();
    }

    const XBridgeTransactionDescr & d = m_transactions[idx.row()];

    if (role == Qt::DisplayRole)
    {
        switch (idx.column())
        {
            case Total:
            {
                double amount = (double)d.fromAmount / XBridgeTransactionDescr::COIN;
                QString text = QString("%1 %2").arg(QString::number(amount), QString::fromStdString(d.fromCurrency));
                return QVariant(text);
            }
            case Size:
            {
                double amount = (double)d.toAmount / XBridgeTransactionDescr::COIN;
                QString text = QString("%1 %2").arg(QString::number(amount), QString::fromStdString(d.toCurrency));
                return QVariant(text);
            }
            case BID:
            {
                double amountTotal = (double)d.fromAmount / XBridgeTransactionDescr::COIN;
                double amountSize = (double)d.toAmount / XBridgeTransactionDescr::COIN;
                double bid = amountTotal / amountSize;

                return QString::number(bid, 'g', 10);
            }
            case State:
            {
                return QVariant(transactionState(d.state));
            }
            case Fee:
            {
                return QString("%1%").arg(QString::number((double)d.tax / 1000, 10, 2));
            }

            default:
                return QVariant();
        }
    }

    if(role == rawStateRole)
    {
        if(idx.column() == State)
            return QVariant(d.state);
        else
            return QVariant();
    }

    return QVariant();
}

//******************************************************************************
//******************************************************************************
QVariant XBridgeTransactionsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Horizontal)
    {
        if (role == Qt::DisplayRole)
        {
            return m_columns[section];
        }
    }
    return QVariant();
}

//******************************************************************************
//******************************************************************************
XBridgeTransactionDescr XBridgeTransactionsModel::item(const unsigned int index) const
{
    if (index >= m_transactions.size())
    {
        XBridgeTransactionDescr dummy;
        dummy.state = XBridgeTransactionDescr::trInvalid;
        return dummy;
    }

    return m_transactions[index];
}

//******************************************************************************
//******************************************************************************
bool XBridgeTransactionsModel::isMyTransaction(const unsigned int index) const
{
    if (index >= m_transactions.size())
    {
        return false;
    }

    return m_transactions[index].from.size();
}

//******************************************************************************
//******************************************************************************
bool XBridgeTransactionsModel::newTransaction(const std::string & from,
                                              const std::string & to,
                                              const std::string & fromCurrency,
                                              const std::string & toCurrency,
                                              const double fromAmount,
                                              const double toAmount)
{
    XBridgeApp & app = XBridgeApp::instance();
    XBridgeSessionPtr ptr = app.sessionByCurrency(fromCurrency);
    if (ptr && ptr->minAmount() > fromAmount)
    {
        return false;
    }

    // TODO check amount
    uint256 id = XBridgeApp::instance().sendXBridgeTransaction
            (from, fromCurrency, (uint64_t)(fromAmount * XBridgeTransactionDescr::COIN),
             to,   toCurrency,   (uint64_t)(toAmount * XBridgeTransactionDescr::COIN));

    if (id != uint256())
    {
        XBridgeTransactionDescr d;
        d.id           = id;
        d.from         = from;
        d.to           = to;
        d.fromCurrency = fromCurrency;
        d.toCurrency   = toCurrency;
        d.fromAmount   = (boost::uint64_t)(fromAmount * XBridgeTransactionDescr::COIN);
        d.toAmount     = (boost::uint64_t)(toAmount * XBridgeTransactionDescr::COIN);
        d.txtime       = boost::posix_time::second_clock::universal_time();

        onTransactionReceived(d);
    }

    return true;
}

//******************************************************************************
//******************************************************************************
bool XBridgeTransactionsModel::newTransactionFromPending(const uint256 & id,
                                                         const std::vector<unsigned char> & hub,
                                                         const std::string & from,
                                                         const std::string & to)
{
    unsigned int i = 0;
    for (; i < m_transactions.size(); ++i)
    {
        if (m_transactions[i].id == id && m_transactions[i].hubAddress == hub)
        {
            // found
            XBridgeTransactionDescr & d = m_transactions[i];
            d.from  = from;
            d.to    = to;
            d.state = XBridgeTransactionDescr::trAccepting;
            std::swap(d.fromCurrency, d.toCurrency);
            std::swap(d.fromAmount, d.toAmount);

            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));

            // send tx
            d.id = XBridgeApp::instance().acceptXBridgeTransaction(d.id, from, to);

            d.txtime = boost::posix_time::second_clock::universal_time();

            break;
        }
    }

    if (i == m_transactions.size())
    {
        // not found...assert ?
        return false;
    }

    // remove all other tx with this id
    for (unsigned int i = 0; i < m_transactions.size(); ++i)
    {
        if (m_transactions[i].id == id && m_transactions[i].hubAddress != hub)
        {
            emit beginRemoveRows(QModelIndex(), i, i);
            m_transactions.erase(m_transactions.begin() + i);
            emit endRemoveRows();

            --i;
        }
    }

    return true;
}

//******************************************************************************
//******************************************************************************
bool XBridgeTransactionsModel::cancelTransaction(const uint256 & id)
{
    if (XBridgeApp::instance().cancelXBridgeTransaction(id, crUserRequest))
    {
        for (unsigned int i = 0; i < m_transactions.size(); ++i)
        {
            if (m_transactions[i].id == id)
            {
                // found
                m_transactions[i].state = XBridgeTransactionDescr::trCancelled;
                emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
            }
        }
        return true;
    }

    return false;
}

//******************************************************************************
//******************************************************************************
void XBridgeTransactionsModel::onTimer()
{
    // check pending transactions
    for (unsigned int i = 0; i < m_transactions.size(); ++i)
    {
        boost::posix_time::time_duration td =
                boost::posix_time::second_clock::universal_time() -
                m_transactions[i].txtime;

        if (m_transactions[i].state == XBridgeTransactionDescr::trNew &&
                td.total_seconds() > XBridgeTransaction::TTL/60)
        {
            m_transactions[i].state = XBridgeTransactionDescr::trOffline;
            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        }
        else if (m_transactions[i].state == XBridgeTransactionDescr::trPending &&
                td.total_seconds() > XBridgeTransaction::TTL/6)
        {
            m_transactions[i].state = XBridgeTransactionDescr::trExpired;
            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        }
        else if ((m_transactions[i].state == XBridgeTransactionDescr::trExpired ||
                  m_transactions[i].state == XBridgeTransactionDescr::trOffline) &&
                         td.total_seconds() < XBridgeTransaction::TTL/6)
        {
            m_transactions[i].state = XBridgeTransactionDescr::trPending;
            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        }
        else if (m_transactions[i].state == XBridgeTransactionDescr::trExpired &&
                td.total_seconds() > XBridgeTransaction::TTL)
        {
            emit beginRemoveRows(QModelIndex(), i, i);
            m_transactions.erase(m_transactions.begin()+i);
            emit endRemoveRows();
            --i;
        }
    }
}

//******************************************************************************
//******************************************************************************
void XBridgeTransactionsModel::onTransactionReceived(const XBridgeTransactionDescr & tx)
{
    for (unsigned int i = 0; i < m_transactions.size(); ++i)
    {
        const XBridgeTransactionDescr & descr = m_transactions.at(i);
        if (descr.id != tx.id)
        {
            continue;
        }

        if (isMyTransaction(i))
        {
            // transaction with id - is owned, not processed more
            return;
        }

        if (descr.hubAddress != tx.hubAddress)
        {
            continue;
        }

        // found
        if (descr.from.size() == 0)
        {
            m_transactions[i] = tx;
        }

        else if (descr.state < tx.state)
        {
            m_transactions[i].state = tx.state;
        }

        // update timestamp
        m_transactions[i].txtime = tx.txtime;

        emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        return;
    }

    // skip tx with other currencies
    // std::string tmp = thisCurrency().toStdString();
    // if (tx.fromCurrency != tmp && tx.toCurrency != tmp)
    // {
    //     return;
    // }

    emit beginInsertRows(QModelIndex(), 0, 0);
    m_transactions.insert(m_transactions.begin(), 1, tx);
    // std::sort(m_transactions.begin(), m_transactions.end(), std::greater<XBridgeTransactionDescr>());
    emit endInsertRows();
}

//******************************************************************************
//******************************************************************************
void XBridgeTransactionsModel::onTransactionStateChanged(const uint256 & id,
                                                         const uint32_t state)
{
    for (unsigned int i = 0; i < m_transactions.size(); ++i)
    {
        if (m_transactions[i].id == id)
        {
            // found
            m_transactions[i].state = static_cast<XBridgeTransactionDescr::State>(state);
            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        }
    }
}

//******************************************************************************
//******************************************************************************
void XBridgeTransactionsModel::onTransactionCancelled(const uint256 & id,
                                                      const uint32_t state,
                                                      const uint32_t reason)
{
    uint32_t i = 0;
    for (XBridgeTransactionDescr & tx : m_transactions)
    {
        if (tx.id == id)
        {
            // found
            tx.state = static_cast<XBridgeTransactionDescr::State>(state);
            tx.reason = reason;
            emit dataChanged(index(i, FirstColumn), index(i, LastColumn));
        }

        ++i;
    }
}

//******************************************************************************
//******************************************************************************
QString XBridgeTransactionsModel::transactionState(const XBridgeTransactionDescr::State state) const
{
    switch (state)
    {
        case XBridgeTransactionDescr::trInvalid:   return trUtf8("Invalid");
        case XBridgeTransactionDescr::trNew:       return trUtf8("New");
        case XBridgeTransactionDescr::trPending:   return trUtf8("Open");
        case XBridgeTransactionDescr::trAccepting: return trUtf8("Accepting");
        case XBridgeTransactionDescr::trHold:      return trUtf8("Hold");
        case XBridgeTransactionDescr::trCreated:   return trUtf8("Created");
        case XBridgeTransactionDescr::trSigned:    return trUtf8("Signed");
        case XBridgeTransactionDescr::trCommited:  return trUtf8("Commited");
        case XBridgeTransactionDescr::trFinished:  return trUtf8("Finished");
        case XBridgeTransactionDescr::trCancelled: return trUtf8("Cancelled");
        case XBridgeTransactionDescr::trRollback:  return trUtf8("Rolled Back");
        case XBridgeTransactionDescr::trDropped:   return trUtf8("Dropped");
        case XBridgeTransactionDescr::trExpired:   return trUtf8("Expired");
        case XBridgeTransactionDescr::trOffline:   return trUtf8("Offline");
        default:                                   return trUtf8("Unknown");
    }
}


text:
All notable changes to this project will be documented in this file.

The format is loosely based on [Keep a Changelog] and this project adheres to
[Semantic Versioning].

  [Keep a Changelog]: http://keepachangelog.com/
  [Semantic Versioning]: http://semver.org/


text:
/**
 * Created by Gabriel Recinos on 5/12/14.
 */

function getAllDeals()
{
    $.mobile.loading( 'show', {
        text: 'Cargando...',
        textVisible: true,
        theme: 'b',
        html: ""
    });

    $.ajax(
        {
            url: urlGlobal + "Ofertas?idMall="+idMallGlobal,
            type: "GET",
            dataType: "json"
        }).done(function (data) {
            if (data.Success) {
                $.mobile.changePage('#Ofertas');
                setTimeout(createListDeals(data.Value), 600);

            }
        }).fail(function (data) {
            $.mobile.hidePageLoadingMsg();

        });

}

function createListDeals(data){

//

//
6:24PM

//
//
//
//
//
Sólo por hoy 19 de Febrero aprovecha un 15% de
//            Descuento en todos los zapatos y un 20% en tennis...Te esperamos.

//
//
//
//
//

    var ul = jQuery('#ListDeals');
    ul.listview();
    ul.empty();

    if(data.length>0)
    {

        var div;
        var li;
        var img;
        var p;
        var strong;
        var separador;// = jQuery('');
//
6:24PM

        for (var i = 0; i < data.length; i++) {
            strong = jQuery('')
            li = jQuery('
');
            img = jQuery('');
            div = jQuery('
');
            p = jQuery('
');
            separador = jQuery('');

            var fechaInicio = data[i].FechaInicio.FromWCFDate();
            var fechaFinal  = data[i].FechaFin.FromWCFDate();
            var mesInicio = fechaInicio.getMonth() +1
            var mesFinal = fechaFinal.getMonth() +1
            strong.text('Desde: ' + fechaInicio.getDate() +'/'+ mesInicio +'/'+fechaInicio.getFullYear() + ' Hasta: ' +  fechaFinal.getDate() +'/'+ mesFinal +'/'+fechaFinal.getFullYear())

            img.attr('id','imgDealMall'+i).attr('src','').attr('style','margin-left: 8px');
            separador.attr('id','separadorImg'+i);

            div.text(data[i].Descripcion);
            p.append(strong);
            li.append(p);
            li.append(img);
            li.append(div);

            ul.append(li);
            ul.append(separador);
        }
        //

        var imgList;
        var imgSeparador;
        for (var i = 0; i < data.length; i++) {

            imgList = document.getElementById('imgDealMall'+i);
            imgList.src  = 'data:image/jpeg;base64,'+data[i].Logo;

            imgSeparador = document.getElementById('separadorImg'+i);
            imgSeparador.src = 'images/ofertas/separadorofertas.png';

        }
        ul.listview('refresh',true);

       // ul.listview('refresh');

    }
    ul.listview('refresh',true);
    $.mobile.hidePageLoadingMsg();

}


text:
namespace gpos
{

	//---------------------------------------------------------------------------
	//	@class:
	//		CAutoTrace
	//
	//	@doc:
    //		Auto object for creating trace messages;
	//		creates a stream over a dynamic string and uses it to print objects;
	//		at destruction the string is written to the log as a trace msg;
	//
	//---------------------------------------------------------------------------
	class CAutoTrace : public CStackObject
	{

		private:

			// dynamic string buffer
			CWStringDynamic m_wstr;

			// string stream
			COstreamString m_os;

			// private copy ctor
			CAutoTrace(const CAutoTrace &);

		public:

			// ctor
			explicit
			CAutoTrace(CMemoryPool *mp);

			// dtor
			~CAutoTrace();

			// stream accessor
			IOstream& Os()
			{
				return m_os;
			}

	}; // class CAutoTrace
}

#endif // !GPOS_CAutoTrace_H

// EOF