text:
\hypertarget{category_g_f_geometry_07_geo_j_s_o_n_08}{}\section{G\+F\+Geometry(Geo\+J\+S\+O\+N) Category Reference}
\label{category_g_f_geometry_07_geo_j_s_o_n_08}\index{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)@{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)}}

Geo\+J\+S\+O\+N interface to \hyperlink{interface_g_f_geometry}{G\+F\+Geometry}.

{\ttfamily \#import $<$Geo\+Features/\+G\+F\+Geometry.\+h$>$}

\subsection*{Instance Methods}
\begin{DoxyCompactItemize}
\item
(N\+S\+Dictionary $\ast$) -\/ \hyperlink{category_g_f_geometry_07_geo_j_s_o_n_08_a89a1dd53c1d9a51fd5b933fde28be5b7}{to\+Geo\+J\+S\+O\+N\+Geometry}
\end{DoxyCompactItemize}
\subsection*{Class Methods}
\begin{DoxyCompactItemize}
\item
(instancetype) + \hyperlink{category_g_f_geometry_07_geo_j_s_o_n_08_a5b730dcea33fc8b2c156199400e3014e}{geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:}
\end{DoxyCompactItemize}

\subsection{Detailed Description}
Geo\+J\+S\+O\+N interface to \hyperlink{interface_g_f_geometry}{G\+F\+Geometry}.

\begin{DoxyAuthor}{Author}
Tony Stone
\end{DoxyAuthor}
\begin{DoxyDate}{Date}
6/14/15
\end{DoxyDate}

\subsection{Method Documentation}
\hypertarget{category_g_f_geometry_07_geo_j_s_o_n_08_a5b730dcea33fc8b2c156199400e3014e}{}\index{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)@{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)}!geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:@{geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:}}
\index{geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:@{geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:}!G\+F\+Geometry(\+Geo\+J\+S\+O\+N)@{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)}}
\subsubsection[{geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:(\+N\+S\+Dictionary $\ast$geo\+J\+S\+O\+N\+Geometry\+Dictionary)}]{\setlength{\rightskip}{0pt plus 5cm}+ (instancetype) geometry\+With\+Geo\+J\+S\+O\+N\+Geometry\+:
\begin{DoxyParamCaption}
\item[{(N\+S\+Dictionary $\ast$)}]{geo\+J\+S\+O\+N\+Geometry\+Dictionary}
\end{DoxyParamCaption}
}\label{category_g_f_geometry_07_geo_j_s_o_n_08_a5b730dcea33fc8b2c156199400e3014e}
Creates a \hyperlink{interface_g_f_geometry}{G\+F\+Geometry} from the Geo\+J\+S\+O\+N dictionary supplied.

\begin{DoxyNote}{Note}
You must pass the geometry portion of the Geo\+J\+S\+O\+N structure and not the entire Geo\+J\+S\+O\+N object.

Given the following Geo\+J\+S\+O\+N\+:
\begin{DoxyCode}
\{
      \textcolor{stringliteral}{"type"}: \textcolor{stringliteral}{"Feature"},

      \textcolor{stringliteral}{"geometry"}:  \{
          \textcolor{stringliteral}{"type"}: \textcolor{stringliteral}{"Box"},
          \textcolor{stringliteral}{"coordinates"}: [[100.0, 0.0], [101.0, 1.0]]
      \}
 \}
\end{DoxyCode}

You would pass the geometry section below to the init method.
\begin{DoxyCode}
\{
    \textcolor{stringliteral}{"type"}: \textcolor{stringliteral}{"Box"},
    \textcolor{stringliteral}{"coordinates"}: [[100.0, 0.0], [101.0, 1.0]]
\}
\end{DoxyCode}

\end{DoxyNote}

Example\+:
\begin{DoxyCode}
\{
    NSString * jsonString = \textcolor{stringliteral}{@"\{ \(\backslash\)"}type\(\backslash\)\textcolor{stringliteral}{": \(\backslash\)"Polygon\(\backslash\)","}
                             \textcolor{stringliteral}{"    \(\backslash\)"coordinates\(\backslash\)": ["}
                             \textcolor{stringliteral}{"      [ [100.0, 0.0], [200.0, 0.0], [200.0, 100.0], [100.0, 1.0], [100.0,
       0.0] ],"}
                             \textcolor{stringliteral}{"      [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]
       ]"}
                             \textcolor{stringliteral}{"      ]"}
                             \textcolor{stringliteral}{"   \}"}

    NSDictionary * geometryDictionary = [NSJSONSerialization JSONObjectWithData: [jsonString
      dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: nil];

    \hyperlink{interface_g_f_geometry}{GFGeometry} * geometry = [\hyperlink{interface_g_f_geometry}{GFGeometry} geometryWithGeoJSONGeometry: geometryDictionary
       ]

\}
\end{DoxyCode}

\begin{DoxyExceptions}{Exceptions}
{\em N\+S\+Exception} & This method will throw an exception if the geo json is invalid. \\
\hline
\end{DoxyExceptions}

Extends class \hyperlink{interface_g_f_geometry_a5b730dcea33fc8b2c156199400e3014e}{G\+F\+Geometry}.

\hypertarget{category_g_f_geometry_07_geo_j_s_o_n_08_a89a1dd53c1d9a51fd5b933fde28be5b7}{}\index{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)@{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)}!to\+Geo\+J\+S\+O\+N\+Geometry@{to\+Geo\+J\+S\+O\+N\+Geometry}}
\index{to\+Geo\+J\+S\+O\+N\+Geometry@{to\+Geo\+J\+S\+O\+N\+Geometry}!G\+F\+Geometry(\+Geo\+J\+S\+O\+N)@{G\+F\+Geometry(\+Geo\+J\+S\+O\+N)}}
\subsubsection[{to\+Geo\+J\+S\+O\+N\+Geometry()}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (N\+S\+Dictionary $\ast$) to\+Geo\+J\+S\+O\+N\+Geometry
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
}\label{category_g_f_geometry_07_geo_j_s_o_n_08_a89a1dd53c1d9a51fd5b933fde28be5b7}
Converts the Geometry to a Geo\+J\+S\+O\+N object.

\begin{DoxyExceptions}{Exceptions}
{\em N\+S\+Exception} & \\
\hline
\end{DoxyExceptions}
\begin{DoxyReturn}{Returns}
A N\+S\+Dictionary Geo\+J\+S\+O\+N representation of self.
\end{DoxyReturn}

Extends class \hyperlink{interface_g_f_geometry_a89a1dd53c1d9a51fd5b933fde28be5b7}{G\+F\+Geometry}.

The documentation for this category was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Geo\+Features/G\+F\+Geometry.\+h\end{DoxyCompactItemize}

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.opsworks.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.opsworks.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * EbsBlockDeviceMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class EbsBlockDeviceMarshaller {

    private static final MarshallingInfo<String> SNAPSHOTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SnapshotId").build();
    private static final MarshallingInfo<Integer> IOPS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Iops").build();
    private static final MarshallingInfo<Integer> VOLUMESIZE_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("VolumeSize").build();
    private static final MarshallingInfo<String> VOLUMETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("VolumeType").build();
    private static final MarshallingInfo<Boolean> DELETEONTERMINATION_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("DeleteOnTermination").build();

    private static final EbsBlockDeviceMarshaller instance = new EbsBlockDeviceMarshaller();

    public static EbsBlockDeviceMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(EbsBlockDevice ebsBlockDevice, ProtocolMarshaller protocolMarshaller) {

        if (ebsBlockDevice == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(ebsBlockDevice.getSnapshotId(), SNAPSHOTID_BINDING);
            protocolMarshaller.marshall(ebsBlockDevice.getIops(), IOPS_BINDING);
            protocolMarshaller.marshall(ebsBlockDevice.getVolumeSize(), VOLUMESIZE_BINDING);
            protocolMarshaller.marshall(ebsBlockDevice.getVolumeType(), VOLUMETYPE_BINDING);
            protocolMarshaller.marshall(ebsBlockDevice.getDeleteOnTermination(), DELETEONTERMINATION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package com.grayfox.server.test.dao.foursquare;

import javax.inject.Inject;

import com.grayfox.server.test.util.HttpStatus;
import com.grayfox.server.test.util.Utils;
import com.squareup.okhttp.mockwebserver.MockResponse;

import com.foursquare4j.FoursquareApi;
import com.grayfox.server.dao.foursquare.FoursquareProfileDao;
import com.grayfox.server.domain.User;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import org.springframework.stereotype.Repository;

@Repository("foursquareProfileDao")
public class MockFoursquareProfileDao extends FoursquareProfileDao {

    @Inject private MockWebServer mockWebServer;
    @Inject private FoursquareApi foursquareApi;

    @Override
    public User collectUserData(String accessToken) {
        if (!"fakeToken".equals(accessToken)) {
            mockWebServer.enqueue(new MockResponse()
                .setStatus(HttpStatus.OK.toString())
                .setBody(Utils.getContentFromFileInClasspath("responses/generic_error.json")));
        } else {
            mockWebServer.enqueue(new MockResponse()
                .setStatus(HttpStatus.OK.toString())
                .setBody(Utils.getContentFromFileInClasspath("responses/user.json")));
            mockWebServer.enqueue(new MockResponse()
                .setStatus(HttpStatus.OK.toString())
                .setBody(Utils.getContentFromFileInClasspath("responses/venuelikes_self.json")));
            mockWebServer.enqueue(new MockResponse()
                .setStatus(HttpStatus.OK.toString())
                .setBody(Utils.getContentFromFileInClasspath("responses/friends.json")));
            mockWebServer.enqueue(new MockResponse()
                .setStatus(HttpStatus.OK.toString())
                .setBody(Utils.getContentFromFileInClasspath("responses/venuelikes_friends.json")));
        }
        return collectUserData(foursquareApi);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>TinySTM: mod_stats.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

TinySTM
    1.0.4

Main Page

Data Structures

Files

File List

Globals

include

Functions

mod_stats.h File Reference

Module for gathering statistics about transactions.
More...

Go to the source code of this file.

Functions

int 	stm_get_global_stats (const char *name, void *val)

 	Get various statistics about the transactions of all threads.

int 	stm_get_local_stats (const char *name, void *val)

 	Get various statistics about the transactions of the current thread.

void 	mod_stats_init (void)

 	Initialize the module.

Detailed Description

Module for gathering statistics about transactions.

This module maintains both aggregate statistics about all threads (aggregates are updated upon thread cleanup) and per-thread statistics. The built-in statistics of the core STM library are more efficient and detailed but this module is useful in case the library is compiled without support for statistics.

Author

Pascal Felber pasca.nosp@m.l.fe.nosp@m.lber@.nosp@m.unin.nosp@m.e.ch Patrick Marlier patri.nosp@m.ck.m.nosp@m.arlie.nosp@m.r@un.nosp@m.ine.c.nosp@m.h

Date

2007-2012

Function Documentation

          void mod_stats_init
          (
          void
          	)

Initialize the module.

This function must be called once, from the main thread, after initializing the STM library and before performing any transactional operation.

          int stm_get_global_stats
          (
          const char *
          name,

          void *
          val

          )

Get various statistics about the transactions of all threads.

See the source code (mod_stats.c) for a list of supported statistics.

Parameters

name	Name of the statistics.

val	Pointer to the variable that should hold the value of the statistics.

Returns

1 upon success, 0 otherwise.

          int stm_get_local_stats
          (
          const char *
          name,

          void *
          val

          )

Get various statistics about the transactions of the current thread.

See the source code (mod_stats.c) for a list of supported statistics.

Parameters

name	Name of the statistics.

val	Pointer to the variable that should hold the value of the statistics.

Returns

1 upon success, 0 otherwise.

<address class="footer">
Generated on Tue Jan 29 2013 14:30:49 for TinySTM by

 1.8.1.2
</address>


text:
import { assert } from 'chai';

import { NO_ADDITIONAL_NODES_PRESET } from '../../../../../../src/options/presets/NoCustomNodes';

import { getRegExpMatch } from '../../../../../helpers/getRegExpMatch';
import { readFileAsString } from '../../../../../helpers/readFileAsString';
import { stubNodeTransformers } from '../../../../../helpers/stubNodeTransformers';

import { JavaScriptObfuscator } from '../../../../../../src/JavaScriptObfuscatorFacade';
import { ObjectPatternPropertiesTransformer } from '../../../../../../src/node-transformers/converting-transformers/ObjectPatternPropertiesTransformer';

describe('ScopeIdentifiersTransformer CatchClause identifiers', () => {
    let obfuscatedCode: string;

    describe('Variant #1: base transform of catch clause parameter', () => {
        const paramNameRegExp: RegExp = /catch *\((_0x([a-f0-9]){4,6})\) *\{/;
        const bodyParamNameRegExp: RegExp = /console\['log'\]\((_0x([a-f0-9]){4,6})\);/;

        let firstMatch: string | undefined,
            secondMatch: string | undefined;

        before(() => {
            const code: string = readFileAsString(__dirname + '/fixtures/input.js');

            obfuscatedCode = JavaScriptObfuscator.obfuscate(
                code,
                {
                    ...NO_ADDITIONAL_NODES_PRESET
                }
            ).getObfuscatedCode();
            firstMatch = getRegExpMatch(obfuscatedCode, paramNameRegExp);
            secondMatch = getRegExpMatch(obfuscatedCode, bodyParamNameRegExp);
        });

        it('match #1: should transform catch clause node', () => {
            assert.match(obfuscatedCode, paramNameRegExp);
        });

        it('match #2: should transform catch clause node', () => {
            assert.match(obfuscatedCode, bodyParamNameRegExp);
        });

        it('catch clause arguments param name and param name in body should be same', () => {
            assert.equal(firstMatch, secondMatch);
        });
    });

    describe('Variant #2: object pattern as parameter', () => {
        stubNodeTransformers([ObjectPatternPropertiesTransformer]);

        const functionParameterMatch: RegExp = /\} *catch *\(\{ *name *\}\) *\{/;
        const functionBodyMatch: RegExp = /return *name;/;

        before(() => {
            const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter.js');

            obfuscatedCode = JavaScriptObfuscator.obfuscate(
                code,
                {
                    ...NO_ADDITIONAL_NODES_PRESET
                }
            ).getObfuscatedCode();
        });

        it('match #1: shouldn\'t transform function parameter object pattern identifier', () => {
            assert.match(obfuscatedCode, functionParameterMatch);
        });

        it('match #2: shouldn\'t transform function parameter object pattern identifier', () => {
            assert.match(obfuscatedCode, functionBodyMatch);
        });
    });

    describe('Variant #3: optional catch binding support', () => {
        const optionalCatchClauseRegExp: RegExp = /} *catch *\{/;
        const bodyParamNameRegExp: RegExp = /console\['log'\]\(0x1\);/;

        before(() => {
            const code: string = readFileAsString(__dirname + '/fixtures/optional-catch-binding.js');

            obfuscatedCode = JavaScriptObfuscator.obfuscate(
                code,
                {
                    ...NO_ADDITIONAL_NODES_PRESET
                }
            ).getObfuscatedCode();
        });

        it('match #1: should transform catch clause node', () => {
            assert.match(obfuscatedCode, optionalCatchClauseRegExp);
        });

        it('match #2: should transform catch clause node', () => {
            assert.match(obfuscatedCode, bodyParamNameRegExp);
        });
    });

    describe('Variant #4: global variable scope', () => {
        describe('Variant #1: `renameGlobals` is disabled', () => {
            const globalVariableRegExp: RegExp = /var test *= *0x1;/;

            before(() => {
                const code: string = readFileAsString(__dirname + '/fixtures/global-variable-scope.js');

                obfuscatedCode = JavaScriptObfuscator.obfuscate(
                    code,
                    {
                        ...NO_ADDITIONAL_NODES_PRESET
                    }
                ).getObfuscatedCode();
            });

            it('match #1: shouldn\'t transform variable identifier if `renameGlobals` option is disabled', () => {
                assert.match(obfuscatedCode, globalVariableRegExp);
            });
        });

        describe('Variant #2: `renameGlobals` is enabled', () => {
            const globalVariableRegExp: RegExp = /var _0x([a-f0-9]){4,6} *= *0x1;/;

            before(() => {
                const code: string = readFileAsString(__dirname + '/fixtures/global-variable-scope.js');

                obfuscatedCode = JavaScriptObfuscator.obfuscate(
                    code,
                    {
                        ...NO_ADDITIONAL_NODES_PRESET,
                        renameGlobals: true
                    }
                ).getObfuscatedCode();
            });

            it('match #1: should transform variable identifier if `renameGlobals` option is enabled', () => {
                assert.match(obfuscatedCode, globalVariableRegExp);
            });
        });
    });
});


text:
module Everything
  module AddPiecesToPieceRefinement
    refine Everything::Piece do
      attr_reader :parent

      def parent=(parent_piece)
        @parent = parent_piece
      end

      def public_pieces
        pieces.select do |piece|
          piece.public?
        end
      end

      def pieces
        file_paths_under_piece = Dir.glob(File.join(full_path, '*'))

        sub_pieces_paths = file_paths_under_piece
          .select do |file_path_under_piece|
            File.directory?(file_path_under_piece)
          end

        sub_pieces_paths.map do |sub_piece_path|
          metadata_file_path = File.join(sub_piece_path, 'index.yaml')
          next unless File.file?(metadata_file_path)

          Piece.new(sub_piece_path)
            .tap {|p| p.parent = self }
        end
          .compact
      end
    end
  end
end


text:
<?php

/**
 * Notes on a particular contact
 *
 * @author ilateral
 * @package Contacts
 */
class Note extends DataObject
{

    private static $db = array(
        "Content" => "Text",
        "Flag" => "boolean"
    );

    private static $has_one = array(
        "Contact" => "Contact"
    );

    private static $casting = array(
        'FlaggedNice' => 'Boolean'
    );

    private static $summary_fields = array(
        "FlaggedNice" => "Flagged",
        "Content.Summary" => "Content",
        "Created" => "Created"
    );

    public function getFlaggedNice()
    {
        $obj = HTMLText::create();
        $obj->setValue(($this->Flag)? '✱' : '');
        return $obj;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<apiPackage id="mx.rpc.http.mxml"><apiName>mx.rpc.http.mxml</apiName><apiDetail/><apiClassifier id="mx.rpc.http.mxml:HTTPService"><apiName>HTTPService</apiName><shortdesc>
 &lt;mx:HTTPService&gt; タグは、MXML ファイル内で HTTPService オブジェクトを表すために使用します。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion></asMetadata><asCustoms><mxml><![CDATA[

 The <mx:HTTPService> tag accepts the following tag attributes:

 <mx:HTTPService
 Properties
 concurrency="multiple|single|last"
 contentType="application/x-www-form-urlencoded|application/xml"
 destination="DefaultHTTP"
 id="No default."
 method="GET|POST|HEAD|OPTIONS|PUT|TRACE|DELETE"
 resultFormat="object|array|xml|e4x|flashvars|text"
 showBusyCursor="false|true"
 makeObjectsBindable="false|true"
 url="No default."
 useProxy="false|true"
 xmlEncode="No default."
 xmlDecode="No default."

 Events
 fault="No default."
 result="No default."
 />

 The <mx:HTTPService> tag can have a single <mx:request> tag under which the parameters can be specified.

 ]]></mxml></asCustoms></prolog><apiClassifierDetail><apiClassifierDef><apiAccess value="public"/><apiStatic/><apiBaseInterface>mx.rpc.mxml:IMXMLSupport</apiBaseInterface><apiBaseInterface>mx.core:IMXMLObject</apiBaseInterface><apiBaseClassifier>mx.rpc.http:HTTPService</apiBaseClassifier></apiClassifierDef><apiDesc>
 <codeph><mx:HTTPService></codeph> タグは、MXML ファイル内で HTTPService オブジェクトを表すために使用します。 HTTPService オブジェクトの <codeph>send()</codeph> メソッドを呼び出すと、指定した URL に対して HTTP 要求が実行され、HTTP 応答が返されます。 指定する URL にパラメーターを渡すこともできます。 サーバーベースのプロキシサービスを経由しない場合は、HTTP GET メソッドまたは POST メソッドだけを使用できます。 useProxy プロパティを true に設定し、サーバーベースのプロキシサービスを使用する場合は、HTTP の HEAD、OPTIONS、TRACE および DELETE メソッドも使用できます。

メモ:ソフトウェアの制約により、HTTPService で GET 要求を使用した場合、ユーザーフレンドリーなエラーメッセージは生成されません。

 </apiDesc><example conref="HTTPServiceExample.mxml"/></apiClassifierDetail><related-links><link href="mx.rpc.http.xml#HTTPService"><linktext>mx.rpc.http.HTTPService</linktext></link><link href="" invalidHref="mx.validators.Validator.xml"><linktext>mx.validators.Validator</linktext></link><link href="" invalidHref="mx.managers.CursorManager.xml"><linktext>mx.managers.CursorManager</linktext></link></related-links><apiConstructor id="mx.rpc.http.mxml:HTTPService:HTTPService"><apiName>HTTPService</apiName><shortdesc>
     新しい HTTPService を作成します。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion></asMetadata></prolog><apiConstructorDetail><apiConstructorDef><apiAccess value="public"/><apiParam><apiItemName>rootURL</apiItemName><apiType value="String"/><apiData>null</apiData><apiDesc>相対 URL を計算するときに、HTTPService が使用する必要のある URL です。

     </apiDesc></apiParam><apiParam><apiItemName>destination</apiItemName><apiType value="String"/><apiData>null</apiData><apiDesc>service-config.xml ファイル内の HTTPService 宛先名です。

      </apiDesc></apiParam></apiConstructorDef><apiDesc>
     新しい HTTPService を作成します。このコンストラクターは通常、MXML ドキュメントの生成済みコードで呼び出されます。 ActionScript で HTTPService を作成するには、通常は mx.rpc.http.HTTPService クラスを使用します。

     </apiDesc></apiConstructorDetail></apiConstructor><apiOperation id="mx.rpc.http.mxml:HTTPService:initialized"><apiName>initialized</apiName><shortdesc>
     実装オブジェクトが作成され、MXML タグに指定されたすべてのコンポーネントプロパティが初期化された後に呼び出されます。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion></asMetadata></prolog><apiOperationDetail><apiOperationDef><apiAccess value="public"/><apiReturn><apiType value="void"/></apiReturn><apiParam><apiItemName>document</apiItemName><apiType value="Object"/><apiDesc>このオブジェクトを作成した MXML ドキュメントです。

     </apiDesc></apiParam><apiParam><apiItemName>id</apiItemName><apiType value="String"/><apiDesc><codeph>document</codeph> がこのオブジェクトを参照するために使用する識別子です。オブジェクトがドキュメントの deep プロパティである場合、<codeph>id</codeph> は null になります。

      </apiDesc></apiParam></apiOperationDef><apiDesc>
     実装オブジェクトが作成され、MXML タグに指定されたすべてのコンポーネントプロパティが初期化された後に呼び出されます。このクラスを ActionScript で作成し、検証で機能させるには、このメソッドを呼び出して、MXML ドキュメントと HTTPService の <codeph>id</codeph> を渡す必要があります。

     </apiDesc></apiOperationDetail></apiOperation></apiClassifier><apiClassifier id="mx.rpc.http.mxml:HTTPMultiService"><apiName>HTTPMultiService</apiName><shortdesc>
 &lt;mx:HTTPMultiService&gt; タグは、MXML ファイル内で HTTPMultiService オブジェクトを表すために使用します。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion><DefaultProperty name="operationList"/></asMetadata></prolog><apiClassifierDetail><apiClassifierDef><apiAccess value="public"/><apiDynamic/><apiBaseInterface>mx.rpc.mxml:IMXMLSupport</apiBaseInterface><apiBaseInterface>mx.core:IMXMLObject</apiBaseInterface><apiBaseClassifier>mx.rpc.http:HTTPMultiService</apiBaseClassifier></apiClassifierDef><apiDesc>
 <codeph><mx:HTTPMultiService></codeph> タグは、MXML ファイル内で HTTPMultiService オブジェクトを表すために使用します。HTTPMultiService は、個々のタグごとに複数の操作をサポートする点を除いて、HTTPService と同様の機能を持ちます。

メモ:ソフトウェアの制約により、HTTPService で GET 要求を使用した場合、ユーザーフレンドリーなエラーメッセージは生成されません。

 </apiDesc></apiClassifierDetail><related-links><link href="mx.rpc.http.xml#HTTPMultiService"><linktext>mx.rpc.http.HTTPMultiService</linktext></link></related-links><apiConstructor id="mx.rpc.http.mxml:HTTPMultiService:HTTPMultiService"><apiName>HTTPMultiService</apiName><shortdesc>
     新しい HTTPMultiService を作成します。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion></asMetadata></prolog><apiConstructorDetail><apiConstructorDef><apiAccess value="public"/><apiParam><apiItemName>rootURL</apiItemName><apiType value="String"/><apiData>null</apiData><apiDesc>相対 URL を計算するときに、HTTPService が使用する必要のある URL です。

     </apiDesc></apiParam><apiParam><apiItemName>destination</apiItemName><apiType value="String"/><apiData>null</apiData><apiDesc>service-config.xml ファイル内の HTTPService 宛先名です。

      </apiDesc></apiParam></apiConstructorDef><apiDesc>
     新しい HTTPMultiService を作成します。このコンストラクターは通常、MXML ドキュメントの生成済みコードで呼び出されます。 ActionScript で HTTPService を作成するには、通常は mx.rpc.http.HTTPService クラスを使用します。

     </apiDesc></apiConstructorDetail></apiConstructor><apiOperation id="mx.rpc.http.mxml:HTTPMultiService:initialized"><apiName>initialized</apiName><shortdesc>
     実装オブジェクトが作成され、MXML タグに指定されたすべてのコンポーネントプロパティが初期化された後に呼び出されます。</shortdesc><prolog><asMetadata><apiVersion><apiLanguage version="3.0"/><apiPlatform description="" name="Flash" version="9"/><apiPlatform description="" name="AIR" version="1.1"/><apiTool description="" name="Flex" version="3"/></apiVersion></asMetadata></prolog><apiOperationDetail><apiOperationDef><apiAccess value="public"/><apiReturn><apiType value="void"/></apiReturn><apiParam><apiItemName>document</apiItemName><apiType value="Object"/><apiDesc>このオブジェクトを作成した MXML ドキュメントです。

     </apiDesc></apiParam><apiParam><apiItemName>id</apiItemName><apiType value="String"/><apiDesc><codeph>document</codeph> がこのオブジェクトを参照するために使用する識別子です。オブジェクトがドキュメントの deep プロパティである場合、<codeph>id</codeph> は null になります。

      </apiDesc></apiParam></apiOperationDef><apiDesc>
     実装オブジェクトが作成され、MXML タグに指定されたすべてのコンポーネントプロパティが初期化された後に呼び出されます。このクラスを ActionScript で作成し、検証で機能させるには、このメソッドを呼び出して、MXML ドキュメントと HTTPService の <codeph>id</codeph> を渡す必要があります。

     </apiDesc></apiOperationDetail></apiOperation></apiClassifier></apiPackage>


text:
require 'spree_core'
require 'lizenzo_importer_hooks'

module LizenzoImporter
  class Engine < Rails::Engine

    config.autoload_paths += %W(#{config.root}/lib)

    def self.activate
      Dir.glob(File.join(File.dirname(__FILE__), "../app/**/*_decorator*.rb")) do |c|
        Rails.env.production? ? require(c) : load(c)
      end

      UserMailer.send(:include, LizenzoImporter::UserMailerExt)

    end

    config.to_prepare &method(:activate).to_proc
  end
end


text:
//
//  ========================================================================
//  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.websocket.jsr356.decoders;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

/**
 * Decode Time
 */
public class TimeDecoder implements Decoder.Text<Date>
{
    @Override
    public Date decode(String s) throws DecodeException
    {
        try
        {
            return new SimpleDateFormat("HH:mm:ss z").parse(s);
        }
        catch (ParseException e)
        {
            throw new DecodeException(s,e.getMessage(),e);
        }
    }

    @Override
    public void destroy()
    {
    }

    @Override
    public void init(EndpointConfig config)
    {
    }

    @Override
    public boolean willDecode(String s)
    {
        return true;
    }
}


text:
import { sideEffect } from 'redux-action-object';

const RowUtils = {
    clone: function (row) {
        return Object.assign({}, row);
    },

    sameFields: function (a, b) {
        const aProps = Object.keys(a);
        const bProps = Object.keys(b);

        if (aProps.length != bProps.length) return false;

        for (let i = 0; i < aProps.length; i++) {
            const propName = aProps[i];

            if (a[propName] !== b[propName]) return false;
        }

        return true;
    }
};

/**
 * Instances of this type will be sent server side to sync backend model
 *
 * @param {string} type Operation type, one of CREATE, UPDATE, DELETE
 * @param {string} table name
 * @param {Object} fields for the operation
 * @constructor
 */
function DataOp(type:String, table:String, fields:Object) {
    this.type = type;
    this.table = table;
    this.fields = fields;
}

DataOp.CREATE = 'CREATE';
DataOp.UPDATE = 'UPDATE';
DataOp.DELETE = 'DELETE';

/**
 * Provides access to entities of specific type in a session.
 *
 * Instances of Table are constructed on session start.
 * Entities retreived via Table are flushed on session end.
 *
 * @param {Array} rows from the store state
 * @param {string} tableName
 * @constructor
 */
function Table(rows, tableName) {
    let trackedRows = {};

    function tracked(row) {
        if (typeof row.id == 'undefined') throw 'Required property id is missing for ' + row;

        if (trackedRows.hasOwnProperty(row.id))
            return trackedRows[row.id];

        const trackedRow = RowUtils.clone(row);
        trackedRows[row.id] = trackedRow;

        return trackedRow;
    }

    function byId(id) {
        return tracked(rows.find(row => row.id == id));
    }

    function filter(f = {}) {
        const predicate = row => {
            for (let key of Object.keys(f))
                if (f[key] != row[key])
                    return false;

            return true;
        };

        return rows.filter(predicate)
            .map(row => tracked(row));
    }

    function remove(row) {
        trackedRows[row.id] = null;
    }

    function create(newRow) {
        if (typeof newRow.id == 'undefined') throw 'Required property "id" is missing in ' + newRow;

        if (trackedRows.hasOwnProperty(newRow.id)) throw 'A row with id ' + newRow.id + ' already exist';

        for (const row of rows) {
            if (row.id == newRow.id)
                throw 'A row with id ' + newRow.id + ' already exist';
        }

        trackedRows[newRow.id] = newRow;
    }

    /** Return updated data */
    function commit() {
        let r = rows, ops = [];

        Object.keys(trackedRows).forEach(rowId => {
            const trackedRow = trackedRows[rowId];

            for (let i = 0; i < r.length; i ++) {
                const row = r[i];

                if (row.id == rowId) {
                    if (trackedRow == null) { // deleted
                        r = r.slice(0, i).concat(r.slice(i + 1, r.length));
                        ops.push(new DataOp(DataOp.DELETE, tableName, row));
                        return;
                    }

                    if (!RowUtils.sameFields(row, trackedRow)) { // updated
                        r = r.slice(0, i).concat([trackedRow], r.slice(i + 1, r.length));
                        ops.push(new DataOp(DataOp.UPDATE, tableName, trackedRow));
                        return;
                    }

                    // no changes made
                    return;
                }
            }

            // no such row - created
            if (r === rows) r = rows.slice(0); // create a copy

            r.push(trackedRow);
            ops.push(new DataOp(DataOp.CREATE, tableName, trackedRow));
        });

        return { rows: r, ops };
    }

    return {
        commit, // private API (for session)
        byId, filter, remove, create // public API
    }
}

/**
 * Interface for retreiving relational data from the store.
 *
 * Session instance is passed to the reducer functions annotated with @data.
 * Each
 */
export function Session(data) {
    function createTables() {
        const r = {};

        for (let tableName of Object.keys(data))
            r[tableName] = new Table(data[tableName], tableName);

        return r;
    }

    function commit() {
        const dataUpdates = {}, mergedOps = [];

        for (let tableName of Object.keys(data)) {
            const { rows, ops } = tables[tableName].commit();

            if (rows !== data[tableName])
                dataUpdates[tableName] = rows;

            mergedOps.push(...ops);
        }

        return { dataUpdates, ops: mergedOps };
    }

    const tables = createTables();

    return {
        commit,
        ...tables
    }
}

export const REMOTE_BEGIN = {
    type: '@@redux-entity-store/BEGIN'
};

export const REMOTE_END = {
    type: '@@redux-entity-store/END'
};

export const REMOTE_FAIL = {
    type: '@@redux-entity-store/FAIL'
};

function confirmSuccessResponse(response) {
    if (response.status == 200) return response;

    let error = new Error(response.statusText);
    error.response = response;
    throw error;
}

let serverUrl;

export function useServer(s) {
    serverUrl = s;
}

/**
 * Mark reducer action impl as data, so it would be wrapped in restore.Sesssion call
 * To be used with actionObject
 *
 * ActionObject should have item name data
 */
export function data(target, name, descriptor) {
    const action = descriptor.value;

    return {
        configurable: true,
        get() {
            // what for this?
            if (this === target.prototype || this.hasOwnProperty(name))
                return action;

            function actionWrapper(...args) {
                if (typeof this.data == 'undefined') throw 'State do not have "data" property';

                const session = new Session(this.data);

                const ret = action.apply(this, [session, ...args]) || {}; // save return in case actionImpl will change smth besides data

                const { dataUpdates, ops } = session.commit();

                if (Object.keys(dataUpdates).length > 0) {
                    ret.data = Object.assign({}, this.data, dataUpdates);

                    if (serverUrl) {
                        sideEffect(function (dispatch) {
                            dispatch(REMOTE_BEGIN);

                            return fetch(serverUrl, {
                                method: 'POST',
                                headers: {
                                    'Accept': 'application/json',
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify(ops)
                            }).then(confirmSuccessResponse)
                                .then(() => dispatch(REMOTE_END))
                                .catch(() => dispatch(REMOTE_FAIL));
                        });
                    }
                }

                return ret;
            }

            // what for this?
            Object.defineProperty(this, name, {
                value: actionWrapper,
                configurable: true,
                writable: true
            });

            return actionWrapper;
        }
    };
}

/** Load initial data into state */
export async function loadData(model) {
    return fetch('/data', {
        method: 'GET',
        headers: {
            'Accept': 'application/json'
        }
    }).then(r => {
        return r.json();
    }).then(data => {
        model.data = data;
    });
}


text:
package skin.support.content.res;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;

import skin.support.SkinCompatManager;

public class SkinCompatResources {
    private static volatile SkinCompatResources sInstance;
    private final Context mAppContext;
    private Resources mResources;
    private String mSkinPkgName;
    private String mSkinName;
    private SkinCompatManager.SkinLoaderStrategy mStrategy;
    private boolean isDefaultSkin;

    private SkinCompatResources(Context context) {
        mAppContext = context.getApplicationContext();
        reset();
    }

    public static void init(Context context) {
        if (sInstance == null) {
            synchronized (SkinCompatResources.class) {
                sInstance = new SkinCompatResources(context);
            }
        }
    }

    public static SkinCompatResources getInstance() {
        return sInstance;
    }

    public void reset() {
        mResources = mAppContext.getResources();
        mSkinPkgName = mAppContext.getPackageName();
        mSkinName = "";
        mStrategy = null;
        isDefaultSkin = true;
    }

    @Deprecated
    public void setSkinResource(Resources resources, String pkgName) {
        mResources = resources;
        mSkinPkgName = pkgName;
        mSkinName = "";
        mStrategy = null;
        isDefaultSkin = mAppContext.getPackageName().equals(pkgName);
    }

    public void setupSkin(Resources resources, String pkgName, String skinName, SkinCompatManager.SkinLoaderStrategy strategy) {
        mResources = resources;
        mSkinPkgName = pkgName;
        mSkinName = skinName;
        mStrategy = strategy;
        isDefaultSkin = TextUtils.isEmpty(skinName);
    }

    public Resources getSkinResources() {
        return mResources;
    }

    public String getSkinPkgName() {
        return mSkinPkgName;
    }

    public boolean isDefaultSkin() {
        return isDefaultSkin;
    }

    public int getColor(int resId) {
        int originColor = ContextCompat.getColor(mAppContext, resId);
        if (isDefaultSkin) {
            return originColor;
        }

        int targetResId = getTargetResId(resId);
        return targetResId == 0 ? originColor : mResources.getColor(targetResId);
    }

    public Drawable getDrawable(int resId) {
        Drawable originDrawable = ContextCompat.getDrawable(mAppContext, resId);
        if (isDefaultSkin) {
            return originDrawable;
        }

        int targetResId = getTargetResId(resId);
        return targetResId == 0 ? originDrawable : mResources.getDrawable(targetResId);
    }

    public ColorStateList getColorStateList(int resId) {
        ColorStateList colorStateList = ContextCompat.getColorStateList(mAppContext, resId);
        if (isDefaultSkin) {
            return colorStateList;
        }

        int targetResId = getTargetResId(resId);
        return targetResId == 0 ? colorStateList : mResources.getColorStateList(targetResId);
    }

    private int getTargetResId(int resId) {
        try {
            String resName = null;
            if (mStrategy != null) {
                resName = mStrategy.getTargetResourceEntryName(mAppContext, mSkinName, resId);
            }
            if (TextUtils.isEmpty(resName)) {
                resName = mAppContext.getResources().getResourceEntryName(resId);
            }
            String type = mAppContext.getResources().getResourceTypeName(resId);
            return mResources.getIdentifier(resName, type, mSkinPkgName);
        } catch (Exception e) {
            // 换肤失败不至于应用崩溃.
            return 0;
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>PlaceNode2</title>
<meta name="date" content="2015-09-10">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

weka.gui.treevisualizer

Class PlaceNode2

java.lang.Object

weka.gui.treevisualizer.PlaceNode2

All Implemented Interfaces:

NodePlace

public class PlaceNode2
extends java.lang.Object
implements NodePlace

This class will place the Nodes of a tree.

 It will place these nodes so that they fall at evenly below their parent. It
 will then go through and look for places where nodes fall on the wrong side
 of other nodes when it finds one it will trace back up the tree to find the
 first common sibling group these two nodes have And it will adjust the
 spacing between these two siblings so that the two nodes no longer overlap.
 This is nasty to calculate with , and takes a while with the current
 algorithm I am using to do this.

Version:

$Revision: 10222 $

Author:

Malcolm Ware (mfw4@cs.waikato.ac.nz)

Constructor Summary

Constructors

Constructor and Description

PlaceNode2()

Method Summary

Methods

Modifier and Type
Method and Description

void
place(Node r)

The Funtion to call to have the nodes arranged.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

PlaceNode2

public PlaceNode2()

Method Detail

place

public void place(Node r)

The Funtion to call to have the nodes arranged.

Specified by:

place in interface NodePlace

Parameters:

r - The top node of the tree to arrange.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require "gga4r"

class GeneticAlgorithm
  def logger
    @logger
  end
  def generations
    @generations
  end
  def population
    @population
  end

  def top_combined(n)
    res_sum = Hash.new { |h,k| h[k] = 0.0 }
    best_fitted(n).each do |obj|
      obj.bankroll_hash.each do |parlay_name,roll_perc|
        res_sum[parlay_name] += roll_perc
      end
    end

    res = {}
    res_sum.each do |parlay_name,perc_sum|
      res[parlay_name] = perc_sum / n.to_f
    end

    ParlayPercs.new(:bankroll_hash => res)
  end
end

class Array
  def rand_el
    i = (rand()*size.to_f).to_i
    self[i]
  end
end

class ParlayPercs
  include FromHash
  attr_accessor :bankroll_hash

  def fitness
    @fitness ||= sims.profit(bankroll_hash)
  end

  def actual_profit
    @actual_profit ||= sims.profit(bankroll_hash, :actual => true)
  end

  def to_s_fitness
    "#{fitness.to_i}/#{actual_profit.to_i}"
  end

  def recombine(other)
    res = {}

    my_weight = 0.5 # rand*0.7 + 0.15
    other_weight = 1.0-my_weight
    bankroll_hash.each do |parlay_name,roll_perc|
      other_perc = other.bankroll_hash[parlay_name]
      raise "bad" unless other_perc
      combined_perc = roll_perc*my_weight + other_perc*other_weight
      res[parlay_name] = combined_perc
    end
    self.class.new(:bankroll_hash => res)
  end

  def mutate_one
    increase_parlay = parlays.rand_el
    decrease_parlay = (parlays - [increase_parlay]).rand_el

    increase_room = (0.4 - bankroll_hash[increase_parlay.name])
    decrease_room = bankroll_hash[decrease_parlay.name] - 0.02
    room = [increase_room,decrease_room].min
    room = 0 if room < 0

    adjustment_amount = [rand()*0.02,room].min

    if adjustment_amount > 0
      bankroll_hash[increase_parlay.name] += adjustment_amount
      bankroll_hash[decrease_parlay.name] -= adjustment_amount
      @fitness = nil
      true
    else
      false
    end
  end

  def mutate
    20.times do
      return if mutate_one
    end
    raise "can't mutate"
  end

  class << self
    def make_rand
      nums = parlays.size.of { rand() }

      nums = nums.map_centered_on_sum(1)
      nums = nums.map_restrict_to_range(0.05..0.25)
      nums = nums.map_centered_on_sum(1)

      res = {}
      parlays.each_with_index do |parlay,i|
        res[parlay.name] = nums[i]
      end
      new(:bankroll_hash => res)
    end
  end
end

class Array
  def map_centered_on_sum(target_sum)
    self_sum = sum
    map { |x| x.to_f / self_sum.to_f * target_sum.to_f }
  end
  def map_restrict_to_range(r)
    map do |n|
      if n > r.end
        r.end
      elsif n < r.begin
        r.begin
      else
        n
      end
    end
  end
end

class Array
  def to_s_bankroll_percs
    arrs = []
    arrs << map { |x| x.fitness }.sort.reverse
    arrs << map { |x| x.actual_profit }.sort.reverse

    arrs.map do |arr|
      sub = [arr[0],arr[-1]]
      sub.inspect
    end.join(" ")
  end
end

def run_genetic
  population = 100.of { ParlayPercs.make_rand }
  ga = GeneticAlgorithm.new(population, :max_population => 10000)
  ga.logger.level = Logger::FATAL

  puts "Initial Fitness: #{population.to_s_bankroll_percs}"

  500.times do |i|
    print "#{i} #{Time.now}" if i%1 == 0 && i > 0
    ga.evolve
    print " Size: #{ga.population.size}" if i%1 == 0 && i > 0
    best = ga.best_fit
    best_combined = ga.top_combined(100)
    puts " Fitness: #{best.to_s_fitness}" if i%1 == 0 && i > 0
    if i%1 == 0 && i > 0
      puts "Top"
      best.bankroll_hash.each do |name,perc|
        puts "#{name}: #{perc.to_s_perc}"
      end
      puts "\n\nCombined"
      best_combined.bankroll_hash.each do |name,perc|
        puts "#{name}: #{perc.to_s_perc}"
      end
      puts "\n\n"
    end

  end

  best = ga.best_fit
  best_combined = ga.top_combined(100)
  puts "Final Fitness: #{best.to_s_fitness}"
  puts "Final Fitness Combined: #{best_combined.to_s_fitness}"

  best.bankroll_hash.each do |name,perc|
    puts "#{name}: #{perc}"
  end

  ga
end

run_genetic

def run_prof
  profile_result = RubyProf.profile do
    run_genetic
  end

  File.open("profile2.html","w") do |f|
    printer = RubyProf::GraphHtmlPrinter.new(profile_result)
    printer.print(f, {})
  end
end


text:
PySAL UCGIS Workshop 2016
==========================
Serge Rey

Levi Wolf

May 23, 2016
Scottsdale, AZ

[![Binder](http://mybinder.org/badge.svg)](http://mybinder.org/repo/ljwolf/ucgis_workshop_2016)

This workshop will cover effective methods for spatial data processing,
analysis, visualization, and documentation of results. In addition, the workshop
will cover how to use well-known Python packages for data analysis, like Pandas
& IPython/Jupyter, with PySAL. Some up-and-coming packages that make spatial
data analysis workflows easier will also be introduced. Participants will learn
how to conduct a full exploratory spatial analysis workflow in this workshop

Requirements
----------------------
We request that attendees bring their own laptop. In addition, we ask that all
attendees install the following python software packages before attending the
workshop:

- PySAL 1.11
- Pandas
- Numexpr
- SciPy
- Numpy
- Jupyter Notebook
- Seaborn

Installation Instructions:
--------------------------

- Download and install Python 2.7 from [Anaconda](https://www.continuum.io/downloads). If you are on Windows, please install the 32-bit version.
- Open Terminal.app (Mac) or Powershell (Windows)
- At the prompt, make sure your installation is up to date by running the
  command: `conda update conda`. Press `y` if asked to confirm.
- Next, run `conda update mkl scipy numpy`.
- Once that finishes, install the dependencies required for the workshop by
  running `conda install pandas numexpr seaborn`.
- Then, run `pip install -U pysal` and confirm if asked.
- After `pysal` is installed, please run the following:
    - `pip install -U folium`
    - `pip install -U geojson`
- Finally, run `conda update jupyter`

Verifying Your Installation:
-----------------------------
At the same prompt you used to set up your terminal, type: `ipython` and hit
enter. It may take a second, but a new prompt should start. This is the ipython
& jupyter command-line interface. To make sure your environment is configured
correctly, run each of these commands at the interpreter:
- `import scipy.stats`
- `import numpy`
- `import pysal`
- `import pandas`
- `import numexpr`
- `import matplotlib`
- `import seaborn`

For windows users, if the first command fails with a message like : `DLL load
failed. The specified module could not be found`, please uninstall Anaconda and
be sure to install the 32-bit version.

Instructors:
-------------
Sergio J. Rey is Professor of Geographical Sciences and core faculty member of
the GeoDa Center of Geospatial Analysis and Computation at Arizona State
University.  He is a Fellow of the Spatial Econometrics Association. Dr. Rey is
project director for PySAL and the creator of the open source package STARS:
Space-Time Analysis of Regional Systems.

Levi John Wolf is a PhD candidate in the GeoDa Center of Geospatial Analysis and
Computation at Arizona State University. His focus is in spatial statistics for
polimetrics and quantitative social science. He has also consulted on statistics
and geospatial software engineering for startups, like CartoDB and Nextdoor.


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mysql.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** The properties that can be updated for a server. */
@Fluent
public final class ServerUpgradeParametersProperties {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(ServerUpgradeParametersProperties.class);

    /*
     * Represents an server storage profile.
     */
    @JsonProperty(value = "targetServerVersion")
    private String targetServerVersion;

    /**
     * Get the targetServerVersion property: Represents an server storage profile.
     *
     * @return the targetServerVersion value.
     */
    public String targetServerVersion() {
        return this.targetServerVersion;
    }

    /**
     * Set the targetServerVersion property: Represents an server storage profile.
     *
     * @param targetServerVersion the targetServerVersion value to set.
     * @return the ServerUpgradeParametersProperties object itself.
     */
    public ServerUpgradeParametersProperties withTargetServerVersion(String targetServerVersion) {
        this.targetServerVersion = targetServerVersion;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
<exporter>
	<name>lime-json</name>
	<displayName>Phaser (JSON)</displayName>
    <description>Exporter for Phaser, JSON</description>
	<version>1.0</version>
	<yAxisDirection>down</yAxisDirection>
	<physicsEngine>box2d</physicsEngine>
	<template>phaser.json</template>
	<fileExtension>json</fileExtension>
	<anchorPoint>
		<enabled>no</enabled>
	</anchorPoint>
	<origin>
    <type>fixed</type>
    <relX>0.0</relX>
	  <relY>1.0</relY>
  </origin>
    <supportsCircles>yes</supportsCircles>
	<body>
	</body>
	<fixture>
        <parameter>
            <name>isSensor</name>
            <displayName>Is Sensor</displayName>
            <description>If set the physial </description>
            <type>bool</type>
            <default>false</default>
        </parameter>

        <parameter>
            <name>filter_groupIndex</name>
            <displayName>Group</displayName>
            <description>Collision group.</description>
            <shortDescription></shortDescription>
            <type>int</type>
            <default>0</default>
        </parameter>

        <parameter>
            <name>filter_bitfield</name>
            <type>bitfield</type>
            <size>16</size>
        </parameter>

        <parameter>
            <name>filter_categoryBits</name>
            <displayName>Cat.</displayName>
            <description>Collision category</description>
            <shortDescription>Collision category</shortDescription>
            <type>uint16</type>
            <default>1</default>
            <bitfield>yes</bitfield>
        </parameter>
        <parameter>
            <name>filter_maskBits</name>
            <displayName>Mask</displayName>
            <description>Collision mask</description>
            <shortDescription>Collision mask</shortDescription>
            <type>uint16</type>
            <default>65535</default>
            <bitfield>yes</bitfield>
        </parameter>
    </fixture>
</exporter>


text:
//If you want to use this on linux, remove the #define statement
#define FASTHASH
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace crypt
{
    public class NotClosingCryptoStream : CryptoStream
    {
        public NotClosingCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
            : base(stream, transform, mode)
        {
        }

        protected override void Dispose(bool disposing)
        {
            if (!HasFlushedFinalBlock)
                FlushFinalBlock();

            base.Dispose(false);
        }
    }

    public struct CryptHeader
    {
        public string Header;
        public byte[] Salt, IV, KeyHash, FileHash;
        public bool Valid;
        public int Cycles;

        public void ReadFrom(Stream S)
        {
            using (var BR = new BinaryReader(S, Encoding.UTF8, true))
            {
                Header = Encoding.UTF8.GetString(BR.ReadBytes(Crypt.HEADER.Length));
                Valid = Crypt.HEADER == Header;
                if (Valid)
                {
                    Salt = BR.ReadBytes(BR.ReadInt32());
                    KeyHash = BR.ReadBytes(BR.ReadInt32());
                    IV = BR.ReadBytes(BR.ReadInt32());
                    FileHash = BR.ReadBytes(BR.ReadInt32());
                    Cycles = BR.ReadInt32();
                }
            }
        }
        public void WriteTo(Stream S)
        {
            using (BinaryWriter BW = new BinaryWriter(S, Encoding.UTF8, true))
            {
                BW.Write(Encoding.UTF8.GetBytes(Header = Crypt.HEADER));
                BW.Write(Salt.Length);
                BW.Write(Salt);
                BW.Write(KeyHash.Length);
                BW.Write(KeyHash);
                BW.Write(IV.Length);
                BW.Write(IV);
                BW.Write(FileHash.Length);
                BW.Write(FileHash);
                BW.Write(Cycles);
                BW.Flush();
            }
        }

        public int GetSize()
        {
            return Encoding.UTF8.GetByteCount(Header) + //Length of header string
                sizeof(int) + Salt.Length +     //byte array + prefix
                sizeof(int) + IV.Length +       //byte array + prefix
                sizeof(int) + KeyHash.Length +  //byte array + prefix
                sizeof(int) + FileHash.Length + //byte array + prefix
                sizeof(int); //Cycles
        }
    }

    /// <summary>
    /// provides File encryption and decryption capabilities
    /// </summary>
    public class Crypt
    {
        [Flags]
        public enum CryptResult : int
        {
            /// <summary>
            /// Operation successful
            /// </summary>
            Success = 0,
            /// <summary>
            /// Generic error
            /// </summary>
            Error = 1,
            /// <summary>
            /// Source stream is not readable
            /// </summary>
            StreamCantRead = 2 | Error,
            /// <summary>
            /// Output stream is not writeable
            /// </summary>
            StreamCantWrite = 4 | Error,
            /// <summary>
            /// Password is invalid.
            /// Either it's wrong for decryption or not supplied for encryption
            /// </summary>
            PasswordInvalid = 8 | Error,
            /// <summary>
            /// File hash did not verify
            /// </summary>
            FileHashInvalid = 16 | Error,
            /// <summary>
            /// File state is invalid. Reasons:
            /// - Attempting to decrypt unencrypted file
            /// - Encrypt already encrypted file.
            /// This error can be resolved by just copying/moving the file.
            /// </summary>
            InvalidFileState = 32 | Error,
            /// <summary>
            /// The cryptographic stream is damaged
            /// </summary>
            CryptoStreamError = 64 | Error,
            /// <summary>
            /// Generic error when reading or writing to file
            /// </summary>
            IOError = 128 | Error,
        }

#if FASTHASH
        /// <summary>
        /// Compares the first count characters of the objects pointed to by b1 and b2.
        /// The comparison is done lexicographically.
        /// </summary>
        /// <param name="b1">Region 1</param>
        /// <param name="b2">Region 2</param>
        /// <param name="count">Length of Region 1 or 2 (use lower of both numbers)</param>
        /// <returns>
        /// Negative value if b1 appears before b2 in lexicographical order.
        /// Zero if b1 and b2 compare equal, or if count is zero.
        /// Positive value if b1 appears after b2 in lexicographical order.</returns>
        /// <see cref="http://en.cppreference.com/w/c/string/byte/memcmp"/>
        /// <remarks>
        /// Needs the "FASTHASH" compiler directive defined to be present and used.
        /// Compare the lengths of the arrays and if either one is null. If they differ you don't need to call this function.
        /// The behavior is undefined if access occurs beyond the end of either object pointed to by b1 and b2.
        /// The behavior is undefined if either b1 or b2 is a null pointer.
        /// </remarks>
        [System.Runtime.InteropServices.DllImport("msvcrt.dll", CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
        private static extern int memcmp(byte[] b1, byte[] b2, long count);
#endif
        /// <summary>
        /// Hash algorithm to use. Do not change
        /// </summary>
        public const string HASHALG = "SHA256";
        /// <summary>
        /// Header value. Do not change
        /// </summary>
        public const string HEADER = "ACRYPT";

#if DEBUG
        /// <summary>
        /// Creates the Hash of a stream.
        /// </summary>
        /// <param name="S">Input stream</param>
        /// <returns>SHA256</returns>
        public static byte[] Hash(Stream S)
        {
            using (var Hasher = (SHA256)HashAlgorithm.Create(HASHALG))
            {
                byte[] Hash = Hasher.ComputeHash(S);
                return Hash;
            }
        }
#endif

        private byte[] Salt;
        private byte[] Key;
        private int Difficulty;
        private readonly static int MaxKeySize;

        static Crypt()
        {
            using (var R = Rijndael.Create())
            {
                MaxKeySize = R.LegalKeySizes.OrderByDescending(m => m.MaxSize).First().MaxSize / 8;
            }
        }

        public Crypt()
        {
        }

        public void GenerateSalt()
        {
            Salt = RandomBytes(MaxKeySize);
            Key = null;
        }

        public void GeneratePassword(string Password, int Difficulty = 50000)
        {
            this.Difficulty = Difficulty;
            if (Salt == null)
            {
                GenerateSalt();
            }
            Key = DeriveBytes(Password, MaxKeySize, Salt, Difficulty);
        }

        /// <summary>
        /// Encrypts a stream
        /// </summary>
        /// <param name="Input">Source stream</param>
        /// <param name="Output">Output stream</param>
        /// <returns>true, if successfull</returns>
        /// <remarks>Output stream must be seekable</remarks>
        public CryptResult Encrypt(Stream Input, Stream Output)
        {
            if (Key == null || Salt == null)
            {
                return CryptResult.PasswordInvalid;
            }
            if (!Input.CanRead)
            {
                return CryptResult.StreamCantRead;
            }
            if (!Output.CanWrite)
            {
                return CryptResult.StreamCantWrite;
            }
            if (!Output.CanSeek)
            {
                return CryptResult.IOError;
            }
            else
            {
                using (Rijndael R = Rijndael.Create())
                {
                    var Header = new CryptHeader();
                    Header.Valid = true;
                    Header.Cycles = Difficulty;
                    R.GenerateIV();
                    Header.IV = R.IV;
                    //Randomly generate a salt for each encryption task.
                    //This makes the password different for each file even if the source file and password are identical.
                    Header.Salt = Salt;
                    //Get Hash for password verification.
                    //This hash allows us to check if a user supplied the correct password for decryption.
                    //This should not be insecure as it still goes through the password generator and thus is very slow.
                    Header.KeyHash = GetPasswordByteHash(Key);
                    //Placeholder for the File hash. When decrypting, this is used to verify integrity.
                    Header.FileHash = new byte[256 / 8];
                    long HashPos = 0;
                    NotClosingCryptoStream CS;

                    Header.WriteTo(Output);
                    HashPos = Output.Position - Header.FileHash.Length - sizeof(int)/*Header.Cycles*/;

                    try
                    {
                        CS = new NotClosingCryptoStream(Output, R.CreateEncryptor(Key, R.IV), CryptoStreamMode.Write);
                    }
                    catch
                    {
                        return CryptResult.CryptoStreamError;
                    }

                    using (CS)
                    {
                        using (var Hasher = (SHA256)HashAlgorithm.Create(HASHALG))
                        {
                            int readed = 0;
                            byte[] Buffer = new byte[R.BlockSize * 10];
                            do
                            {
                                try
                                {
                                    readed = Input.Read(Buffer, 0, Buffer.Length);
                                }
                                catch
                                {
                                    return CryptResult.IOError;
                                }
                                if (readed > 0)
                                {
                                    try
                                    {
                                        CS.Write(Buffer, 0, readed);
                                    }
                                    catch (IOException)
                                    {
                                        return CryptResult.IOError;
                                    }
                                    catch
                                    {
                                        return CryptResult.CryptoStreamError;
                                    }

                                    if (Input.Position == Input.Length)
                                    {
                                        var temp = Hasher.TransformFinalBlock(Buffer, 0, readed);
                                    }
                                    else
                                    {
                                        Hasher.TransformBlock(Buffer, 0, readed, Buffer, 0);
                                    }
                                }
                            } while (readed > 0);
                            Header.FileHash = CreateHMAC(Key, (byte[])Hasher.Hash.Clone());
                        }
                        try
                        {
                            CS.FlushFinalBlock();
                        }
                        catch (IOException)
                        {
                            return CryptResult.IOError;
                        }
                        catch
                        {
                            return CryptResult.CryptoStreamError;
                        }
                        //Store File hash and seek back to the end
                        try
                        {
                            Output.Flush();
                            long CurrentPos = Output.Position;
                            Output.Seek(HashPos, SeekOrigin.Begin);
                            Output.Write(Header.FileHash, 0, Header.FileHash.Length);
                            Output.Flush();
                            Output.Seek(Output.Position, SeekOrigin.Begin);
                        }
                        catch
                        {
                            return CryptResult.IOError;
                        }
                    }
                }
            }
            return CryptResult.Success;
        }

        /// <summary>
        /// Decrypts a stream
        /// </summary>
        /// <param name="Input">Input stream</param>
        /// <param name="Output">Output stream</param>
        /// <returns>true, if successfull</returns>
        public CryptResult Decrypt(Stream Input, Stream Output, string Password)
        {
            if (!Input.CanRead)
            {
                return CryptResult.StreamCantRead;
            }
            if (!Output.CanWrite)
            {
                return CryptResult.StreamCantWrite;
            }
            var Header = GetHeader(Input);
            if (!Header.Valid)
            {
                return CryptResult.InvalidFileState;
            }
            using (Rijndael R = Rijndael.Create())
            {
                NotClosingCryptoStream CS;

                byte[] Key = DeriveBytes(Password, MaxKeySize, Header.Salt, Header.Cycles);

                if (!CheckPasswordBytes(Key, Header.KeyHash))
                {
                    return CryptResult.PasswordInvalid;
                }

                try
                {
                    CS = new NotClosingCryptoStream(Input, R.CreateDecryptor(Key, Header.IV), CryptoStreamMode.Read);
                }
                catch
                {
                    return CryptResult.CryptoStreamError;
                }
                using (CS)
                {
                    using (var Hasher = (SHA256)HashAlgorithm.Create(HASHALG))
                    {
                        byte[] Data = new byte[R.BlockSize * 100];
                        int readed = 0;
                        do
                        {
                            try
                            {
                                readed = CS.Read(Data, 0, Data.Length);
                            }
                            catch (IOException)
                            {
                                return CryptResult.IOError;
                            }
                            catch
                            {
                                return CryptResult.CryptoStreamError;
                            }
                            if (readed > 0)
                            {
                                try
                                {
                                    Output.Write(Data, 0, readed);
                                }
                                catch
                                {
                                    return CryptResult.IOError;
                                }
                                //Always read a multiple of the supported blocksize to avoid problems with readahead
                                if (Input.Position == Input.Length)
                                {
                                    Hasher.TransformFinalBlock(Data, 0, readed);
                                }
                                else
                                {
                                    Hasher.TransformBlock(Data, 0, readed, Data, 0);
                                }
                            }
                        } while (readed > 0);
                        if (!VerifyHMAC(Key, Header.FileHash, Hasher.Hash))
                        {
                            return CryptResult.FileHashInvalid;
                        }
                    }
                }
            }
            return CryptResult.Success;
        }

        /// <summary>
        /// Verifies a HMAC
        /// </summary>
        /// <param name="Salt">Salt to generate HMAC</param>
        /// <param name="OriginalHash">Hash on record</param>
        /// <param name="NewHash">New Hash to generate HMAC and check</param>
        /// <returns>True, if identical</returns>
        private static bool VerifyHMAC(byte[] Salt, byte[] OriginalHash, byte[] NewHash)
        {
            return CompareBytes(CreateHMAC(Salt, NewHash), OriginalHash);
        }

        /// <summary>
        /// Creates a HMAC (SHA256)
        /// </summary>
        /// <param name="Salt">Salt</param>
        /// <param name="Content">Content to create HMAC from</param>
        /// <returns>HMAC</returns>
        private static byte[] CreateHMAC(byte[] Salt, byte[] Content)
        {
            using (HMACSHA256 H = new HMACSHA256(Salt))
            {
                return H.ComputeHash(Content);
            }
        }

        /// <summary>
        /// Creates the <see cref="HASHALG"/> Hash of a password
        /// </summary>
        /// <param name="Password">Password (or other binary content)</param>
        /// <returns>Hash</returns>
        private static byte[] GetPasswordByteHash(byte[] Password)
        {
            using (var A = HashAlgorithm.Create(HASHALG))
            {
                return A.ComputeHash(Password);
            }
        }

        /// <summary>
        /// Checks an existing password hash against a password or other binary content
        /// </summary>
        /// <param name="Password">Password</param>
        /// <param name="Hash">Hash</param>
        /// <returns>true, if identical</returns>
        private static bool CheckPasswordBytes(byte[] Password, byte[] Hash)
        {
            return CompareBytes(GetPasswordByteHash(Password), Hash);
        }

        /// <summary>
        /// Compares two byte arrays
        /// </summary>
        /// <param name="B1">Array 1</param>
        /// <param name="B2">Array 2</param>
        /// <returns>true, if identical</returns>
        private static bool CompareBytes(byte[] B1, byte[] B2)
        {
            if (B1 == null && B2 == null)
            {
                return true;
            }
#if FASTHASH
            return B1 != null && B2 != null && B1.Length == B2.Length && memcmp(B1, B2, B1.Length) == 0;
#else
            if (B1 == null || B2 == null || B1.Length != B2.Length)
            {
                return false;
            }

            for (var i = 0; i < B1.Length; i++)
            {
                if (B1[i] != B2[i])
                {
                    return false;
                }
            }
            return true;
#endif
        }

        /// <summary>
        /// Tries to read the crypt header from a file
        /// </summary>
        /// <param name="Filename">File name</param>
        /// <returns>Crypt header. Check the valid property before using any of its values</returns>
        public static CryptHeader GetHeader(string Filename)
        {
            using (var FS = File.OpenRead(Filename))
            {
                return GetHeader(FS);
            }
        }

        /// <summary>
        /// Tries to read the crypt header from a stream
        /// </summary>
        /// <param name="Input">Input stream</param>
        /// <returns>Crypt header.</returns>
        /// <remarks>This will leave the stream as-is</remarks>
        public static CryptHeader GetHeader(Stream Input)
        {
            var H = new CryptHeader();
            try
            {
                H.ReadFrom(Input);
            }
            catch
            {
                return new CryptHeader();
            }
            return H;
        }

        /// <summary>
        /// Checks if a file has a crypt header
        /// </summary>
        /// <param name="Filename">File name</param>
        /// <returns>true, if it has valid header</returns>
        /// <remarks>This will not attempt to verify the header or content itself</remarks>
        public static bool IsEncrypted(string Filename)
        {
            return GetHeader(Filename).Valid;
        }

        /// <summary>
        /// Checks if a stream has a crypt header
        /// </summary>
        /// <param name="Input">Stream (positioned at expected header start)</param>
        /// <returns>true, if it has valid header</returns>
        /// <remarks>
        /// This will not attempt to verify the header or content itself.
        /// This will not rewind the stream.
        /// The stream position is undefined after this function
        /// </remarks>
        public static bool IsEncrypted(Stream Input)
        {
            return GetHeader(Input).Valid;
        }

        /// <summary>
        /// Generates cryptographically safe random bytes
        /// </summary>
        /// <param name="Count">Number of bytes to generate</param>
        /// <returns>Byte array</returns>
        private static byte[] RandomBytes(int Count)
        {
            byte[] Data = new byte[Count];
            using (RNGCryptoServiceProvider RNG = (RNGCryptoServiceProvider)RandomNumberGenerator.Create())
            {
                RNG.GetBytes(Data);
            }
            return Data;
        }

        /// <summary>
        /// Derives the encryption/decryption bytes from a string
        /// </summary>
        /// <param name="Password">User supplied password</param>
        /// <param name="NumberOfBytes">Number of bytes needed</param>
        /// <param name="Salt">Salt. This should be unique to each file</param>
        /// <param name="Cycles">Cycles for the function. Bigger takes longer.</param>
        /// <returns>Pseudorandom bytes</returns>
        /// <remarks>crypt does not stores the cycles in the header. You need to remember for yourself.</remarks>
        private static byte[] DeriveBytes(string Password, int NumberOfBytes, byte[] Salt, int Cycles = 50000)
        {
            using (var Deriver = new Rfc2898DeriveBytes(Password, Salt, Cycles))
            {
                return Deriver.GetBytes(NumberOfBytes);
            }
        }
    }
}


text:
<?php

require_once(dirname(__FILE__).'/../../bootstrap/unit.php');

$t = new lime_test(2, new lime_output_color());

$f = new sfWidgetFormSchemaFormatterTable();

// ->formatRow()
$t->diag('->formatRow()');
$output = <<<EOF

  label
  <input />
help

EOF;
$t->is($f->formatRow('label', '<input />', array(), 'help', ''), $output, '->formatRow() formats a field in a row');

// ->formatErrorRow()
$t->diag('->formatErrorRow()');
$output = <<<EOF

Global error

id: required

1 > sub_id: required

EOF;
$t->is($f->formatErrorRow(array('Global error', 'id' => 'required', array('sub_id' => 'required'))), $output, '->formatErrorRow() formats an array of errors in a row');


text:
from django.conf.urls.defaults import *
from django.conf import settings

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('zookeeper_dashboard',
    (r'^cluster/', include('zookeeper_dashboard.zkadmin.urls')),
    (r'^tree/', include('zookeeper_dashboard.zktree.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # (r'^admin/(.*)', admin.site.root),

    (r'^$', include('zookeeper_dashboard.zkadmin.urls')),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^css/(?P<path>.*)$', 'django.views.static.serve', {'document_root': './css'}),
    )


text:
<?php

namespace Zend\Ldap\Node\RootDse;

use Zend\Ldap\Node;

/**
 * Zend\Ldap\Node\RootDse\OpenLdap provides a simple data-container for the
 * RootDse node of an OpenLDAP server.
 *
 * @category   Zend
 * @package    Zend_Ldap
 * @subpackage RootDse
 */
class OpenLdap extends Node\RootDse
{
    /**
     * Gets the configContext.
     *
     * @return string|null
     */
    public function getConfigContext()
    {
        return $this->getAttribute('configContext', 0);
    }

    /**
     * Gets the monitorContext.
     *
     * @return string|null
     */
    public function getMonitorContext()
    {
        return $this->getAttribute('monitorContext', 0);
    }

    /**
     * Determines if the control is supported
     *
     * @param  string|array $oids control oid(s) to check
     * @return boolean
     */
    public function supportsControl($oids)
    {
        return $this->attributeHasValue('supportedControl', $oids);
    }

    /**
     * Determines if the extension is supported
     *
     * @param  string|array $oids oid(s) to check
     * @return boolean
     */
    public function supportsExtension($oids)
    {
        return $this->attributeHasValue('supportedExtension', $oids);
    }

    /**
     * Determines if the feature is supported
     *
     * @param  string|array $oids feature oid(s) to check
     * @return boolean
     */
    public function supportsFeature($oids)
    {
        return $this->attributeHasValue('supportedFeatures', $oids);
    }

    /**
     * Gets the server type
     *
     * @return int
     */
    public function getServerType()
    {
        return self::SERVER_TYPE_OPENLDAP;
    }
}


text:
/*  =========================================================================

    samwise - reliable message publishing

    This Source Code Form is subject to the terms of the MIT
    License. If a copy of the MIT License was not distributed with
    this file, You can obtain one at http://opensource.org/licenses/MIT

    =========================================================================
*/
/**

   @brief Samwise API interface

   Offers all public functions necessary to store and forward
   messages.

*/

#ifndef __SAM_H__
#define __SAM_H__

#ifdef __cplusplus
extern "C" {
#endif

#define SAM_VERSION_MAJOR 0
#define SAM_VERSION_MINOR 0
#define SAM_VERSION_PATCH 1

#define SAM_MAKE_VERSION(major, minor, patch) \
    ((major) *10000 + (minor) * 100 + (patch))

#define SAM_VERSION \
    SAM_MAKE_VERSION(SAM_VERSION_MAJOR, \
                     SAM_VERSION_MINOR, \
                     SAM_VERSION_PATCH)

//
//   DEPENDENCIES
//

#ifdef __SAM_TEST
#include <check.h>
#endif

#include <db.h>
#include <amqp.h>
#include <amqp_tcp_socket.h>

#include <czmq.h>
#if CZMQ_VERSION < 30000
#  error "sam needs at least CZMQ 3.0.0"
#endif

//
//   MACROS
//
#define UU __attribute__((unused))

// global configuration
#define SAM_PROTOCOL_VERSION 120
#define SAM_RET_RESTART 0x10

// enable stats
#define SAM_STAT

// don't define these to show all log levels
// TODO offer an option for ./configure
// #define LOG_THRESHOLD_TRACE   // show info + error
// #define LOG_THRESHOLD_INFO    // only show error
// #define LOG_THRESHOLD_ERROR   // disable logging

// forward references
typedef struct sam_t sam_t;
typedef struct sam_cfg_t sam_cfg_t;
typedef struct sam_msg_t sam_msg_t;

/// backend types
typedef enum {
    SAM_BE_RMQ     ///< RabbitMQ message backend
} sam_be_t;

/// signals sent by messaging backends
typedef enum {
    SAM_BE_SIG_CONNECTION_LOSS = 0x10, ///< if a backend was split
    SAM_BE_SIG_RECONNECTED,            ///< if the backend re-connected
    SAM_BE_SIG_KILL                    ///< backend no longer re-connects
} sam_be_sig_t;

/// return type for client responses
typedef struct sam_ret_t {
    int rc;          ///< return code
    char *msg;       ///< additional info, either static or allocated
    bool allocated;  ///< indicates if ret.msg must be free'd
} sam_ret_t;

//  --------------------------------------------------------------------------
/// @brief Creates a new sam instance
/// @param be_type Backend type
/// @return Handle for inter thread communication
sam_t *
sam_new (sam_be_t be_type);

//  --------------------------------------------------------------------------
/// @brief Destroy an instance, tears down the thread and free's all memory
void
sam_destroy (
    sam_t **self);

//  --------------------------------------------------------------------------
/// @brief (Re)load configuration file
/// @param conf Location of the configuration file
/// @return 0 in case of success, -1 in case of error
int
sam_init (
    sam_t *self,
    sam_cfg_t **cfg);

//  --------------------------------------------------------------------------
/// @brief Instruct sam to analyze and act according to a message
/// @param self A sam instance
/// @param msg Message containing some <action>
/// @return Some sam_ret_t
sam_ret_t *
sam_eval (
    sam_t *self,
    sam_msg_t *msg);

//  --------------------------------------------------------------------------
/// @brief Self test this class.
void *
sam_test ();

#ifdef __cplusplus
}
#endif

#endif


text:
<?php
//
// Description
// ===========
// This method will return the list of jobs which are missing from
// subscriptions and have not yet been setup in the system.
//
// Arguments
// ---------
// api_key:
// auth_token:
// business_id:		The ID of the business to get the task list for.
//
// Returns
// -------
//	<jobs>
//		<job id="23" name="2007" status="60" status_text="Completed" pstart_date="Jan 1, 2007" pend_date="Dec 31, 2007" service_date="Dec 31, 2007" date_schedule="" date_due="Apr 31, 2008"
//			date_started="Apr 5, 2010" date_completed="Apr 10, 2010" />
//		<job id="0" name="2008" status="0" status_text="Missing" pstart_date="Jan 1, 2008" pend_date="Dec 31, 2008" service_date="Dec 31, 2008" date_schedule="" date_due="Apr 31, 2009"
//			date_started="" date_completed="" />
//		<job id="783" name="2009" status="61" status_text="Skipped" pstart_date="Jan 1, 2009" pend_date="Dec 31, 2009" service_date="Dec 31, 2009" date_schedule="" date_due="Apr 31, 2010"
//			date_started="" date_completed="" />
//		<job id="783" name="2010" status="60" status_text="Completed" pstart_date="Jan 1, 2010" pend_date="Dec 31, 2010" service_date="Dec 31, 2010" date_schedule="" date_due="Apr 31, 2011"
//			date_started="Mar 1, 2011" date_completed="Mar 23, 2011" />
//		<job id="783" name="2011" status="60" status_text="Completed" pstart_date="Jan 1, 2011" pend_date="Dec 31, 2011" service_date="Dec 31, 2011" date_schedule="" date_due="Apr 31, 2012"
//			date_started="Feb 25, 2012" date_completed="Mar 23, 2012" />
//		<job id="783" name="2012" status="0" status_text="Upcoming" pstart_date="Jan 1, 2012" pend_date="Dec 31, 2012" service_date="Dec 31, 2012" date_schedule="" date_due="Apr 31, 2013"
//			date_started="" date_completed="Mar 23, 2013" />
//	</jobs>
//
function ciniki_services_jobsMissing($ciniki) {
    //
    // Find all the required and optional arguments
    //
	ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'prepareArgs');
    $rc = ciniki_core_prepareArgs($ciniki, 'no', array(
        'business_id'=>array('required'=>'yes', 'blank'=>'no', 'name'=>'Business'),
        ));
    if( $rc['stat'] != 'ok' ) {
        return $rc;
    }
    $args = $rc['args'];

    //
    // Make sure this module is activated, and
    // check permission to run this function for this business
    //
	ciniki_core_loadMethod($ciniki, 'ciniki', 'services', 'private', 'checkAccess');
    $rc = ciniki_services_checkAccess($ciniki, $args['business_id'], 'ciniki.services.jobsMissing', 0, 0);
    if( $rc['stat'] != 'ok' ) {
        return $rc;
    }
	$modules = $rc['modules'];

	//
	// Setup the timezone offset, to get back proper UTC dates from database
	//
	ciniki_core_loadMethod($ciniki, 'ciniki', 'users', 'private', 'timezoneOffset');
	$utc_offset = ciniki_users_timezoneOffset($ciniki);

	ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbQuote');
	ciniki_core_loadMethod($ciniki, 'ciniki', 'users', 'private', 'dateFormat');
	$date_format = ciniki_users_dateFormat($ciniki);

	//
	// Load the list of status messages for this business
	//
	ciniki_core_loadMethod($ciniki, 'ciniki', 'services', 'private', 'statusList');
	$rc = ciniki_services_statusList($ciniki, $args['business_id']);
	$status_texts = $rc['list'];

	if( !isset($args['year']) ) {
		$args['year'] = date('Y');
	}
	if( !isset($args['month']) ) {
		$args['month'] = date('m');
	}

    //
	// Get the types of customers available for this business
	//
	ciniki_core_loadMethod($ciniki, 'ciniki', 'customers', 'private', 'getCustomerTypes');
	$rc = ciniki_customers_getCustomerTypes($ciniki, $args['business_id']);
	if( $rc['stat'] != 'ok' ) {
		return $rc;
	}
	$types = $rc['types'];

	//
	// Build the SQL string to get the list of subscriptions with missing jobs,
	// and include the existing jobs so the holes can be filled in
	//
	$strsql = "SELECT ciniki_service_subscriptions.id, "
		. "IFNULL(DATE_FORMAT(ciniki_service_subscriptions.date_started, '" . ciniki_core_dbQuote($ciniki, $date_format) . "'), '') AS date_started, "
		. "IFNULL(DATE_FORMAT(ciniki_service_subscriptions.date_ended, '" . ciniki_core_dbQuote($ciniki, $date_format) . "'), '') AS date_ended, "
		. "ciniki_service_subscriptions.date_started AS raw_date_started, "
		. "ciniki_service_subscriptions.date_ended AS raw_date_ended, "
		. "ciniki_service_subscriptions.customer_id, "
		. "ciniki_customers.type AS customer_type, "
		. "";
	if( count($types) > 0 ) {
		// If there are customer types defined, choose the right name for the customer
		// This is required here to be able to sort properly
		$strsql .= "CASE ciniki_customers.type ";
		foreach($types as $tid => $type) {
			$strsql .= "WHEN " . ciniki_core_dbQuote($ciniki, $tid) . " THEN ";
			if( $type['detail_value'] == 'business' ) {
				$strsql .= " ciniki_customers.company ";
			} else {
				$strsql .= "CONCAT_WS(' ', first, last) ";
			}
		}
		$strsql .= "ELSE CONCAT_WS(' ', first, last) END AS customer_name, ";
	} else {
		// Default to a person
		$strsql .= "CONCAT_WS(' ', first, last) AS customer_name, ";
	}
	$strsql .= "ciniki_service_subscriptions.service_id, "
		. "ciniki_services.name AS service_name, "
		. "ciniki_services.repeat_type, "
		. "ciniki_services.repeat_interval, "
		. "ciniki_services.due_after_days, ciniki_services.due_after_months, "
		. "ciniki_service_jobs.id AS job_id, "
		. "IFNULL(DATE_FORMAT(ciniki_service_jobs.pstart_date, '" . ciniki_core_dbQuote($ciniki, $date_format) . "'), '') AS pstart_date, "
		. "IFNULL(DATE_FORMAT(ciniki_service_jobs.pend_date, '" . ciniki_core_dbQuote($ciniki, $date_format) . "'), '') AS pend_date, "
		. "IFNULL(DATE_FORMAT(ciniki_service_jobs.date_due, '" . ciniki_core_dbQuote($ciniki, $date_format) . "'), '') AS job_date_due, "
		. "ciniki_service_jobs.pend_date AS raw_pend_date "
		. "FROM ciniki_service_subscriptions "
		. "LEFT JOIN ciniki_services ON (ciniki_service_subscriptions.service_id = ciniki_services.id "
			. "AND ciniki_services.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "') "
		. "LEFT JOIN ciniki_customers ON (ciniki_service_subscriptions.customer_id = ciniki_customers.id "
			. "AND ciniki_customers.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "') "
		. "LEFT JOIN ciniki_service_jobs ON (ciniki_service_subscriptions.id = ciniki_service_jobs.subscription_id "
			. "AND ciniki_service_subscriptions.customer_id = ciniki_service_jobs.customer_id ) "
		. "WHERE EXISTS ( "
			// Find service subscriptions which are missing jobs
			. "SELECT ciniki_service_subscriptions.id, "
			. "((PERIOD_DIFF("
				. "IF(ciniki_service_subscriptions.date_ended>ciniki_service_subscriptions.date_started, "
					. "DATE_FORMAT(ciniki_service_subscriptions.date_ended+INTERVAL due_after_months MONTH, '%Y%m'), "
					. "'" . ciniki_core_dbQuote($ciniki, sprintf("%04d%02d", $args['year'], $args['month'])) . "'), "
				. "DATE_FORMAT(ciniki_service_subscriptions.date_started-INTERVAL 1 DAY, '%Y%m'))-due_after_months) "
				. "DIV CASE repeat_type WHEN 40 THEN 12 WHEN 30 THEN repeat_interval END) AS required_jobs, "
			. "COUNT(ciniki_service_jobs.id) AS existing_jobs "
			. "FROM ciniki_service_subscriptions "
			. "LEFT JOIN ciniki_services ON (ciniki_service_subscriptions.service_id = ciniki_services.id "
				. "AND ciniki_services.business_id = '" . ciniki_core_dbQuote($ciniki, $args['business_id']) . "') "
			. "LEFT JOIN ciniki_service_jobs ON (ciniki_service_subscriptions.id = ciniki_service_jobs.subscription_id "
				. "AND ciniki_service_subscriptions.customer_id = ciniki_service_jobs.customer_id ) "
			. "WHERE ciniki_service_subscriptions.service_id = ciniki_services.id "
			. "GROUP BY ciniki_service_subscriptions.id "
			. "HAVING required_jobs > existing_jobs "
		. ") "
		. "ORDER BY customer_name, ciniki_services.name, ciniki_service_subscriptions.date_started "
		. "";
	ciniki_core_loadMethod($ciniki, 'ciniki', 'core', 'private', 'dbHashQueryTree');
	$rc = ciniki_core_dbHashQueryTree($ciniki, $strsql, 'ciniki.services', array(
		array('container'=>'subscriptions', 'fname'=>'id', 'name'=>'subscription',
			'fields'=>array('id', 'customer_id', 'customer_type', 'customer_name',
				'service_id', 'service_name', 'date_started', 'date_ended',
				'repeat_type', 'repeat_interval', 'raw_date_started', 'raw_date_ended', 'due_after_days', 'due_after_months')),
		array('container'=>'jobs', 'fname'=>'job_id', 'name'=>'job',
			'fields'=>array('id'=>'job_id',
				'pstart_date', 'pend_date', 'raw_pend_date', 'date_due'=>'job_date_due'),
			'maps'=>array('status_text'=>$status_texts)),
		));
	if( $rc['stat'] != 'ok' ) {
		return $rc;
	}
	if( !isset($rc['subscriptions']) ) {
		return array('stat'=>'ok', 'subscriptions'=>array());
	}
	$subscriptions = $rc['subscriptions'];

	//
	// Go through all the subscriptions returned and build a list of missing jobs
	//
	$jobs = array();
	foreach($subscriptions as $sid => $service) {
		$service = $service['subscription'];
		$date_started = date_create($service['raw_date_started']);
		$date_ended = date_create($service['raw_date_ended']);
		$end_date = 0;
		if( $date_started->getTimestamp() > 0 && $date_ended->getTimestamp() > $date_started->getTimestamp() ) {
			$end_date = date_create($service['raw_date_ended']);
			// Add the due_after_months, this is used when subscription has an end date
			if( $service['due_after_months'] > 0 ) {
				$end_date->modify('+' . $service['due_after_months'] . ' month');
				// if it starts at 1st of month, it should end on last day of month, check for rollover
				if( $date_started->format('j') == 1 && $end_date->format('j') < 5 ) {
					$end_date->modify('last day of previous month');
				}
				// Check if end is last day of month
				elseif( $date_ended->format('t') == $date_ended->format('j') && $end_date->format('t') != $end_date->format('j') ) {
					$end_date->modify('last day of this month');
				}
			}
//		} elseif( isset($args['projections']) && $args['projections'] != '' ) {
//			$end_date = date_create("now");
//			$end_date = date_add($end_date, new DateInterval($args['projections']));
		} else {
			$end_date = date_create("now");
		}
		$interval = 0;
		if( $service['repeat_type'] == 30 ) {
			$interval = new DateInterval("P" . $service['repeat_interval'] . "M");
		} elseif( $service['repeat_type'] == 40 ) {
			$interval = new DateInterval("P" . $service['repeat_interval'] . "Y");
		} else {
			continue;
		}
		$dueinterval = 0;
		if( $service['due_after_days'] > 0 && $service['due_after_months'] > 0 ) {
			$dueinterval = new DateInterval("P" . $service['due_after_months'] . "M" . $service['due_after_days'] . "D");
		} elseif( $service['due_after_days'] > 0 ) {
			$dueinterval = new DateInterval("P" . $service['due_after_days'] . "D");
		} elseif( $service['due_after_months'] > 0 ) {
			$dueinterval = new DateInterval("P" . $service['due_after_months'] . "M");
		}
		$lessaday = new DateInterval("P1D");

		//
		// Setup status_text in existing jobs, and setup utc_pend_date
		//
		if( isset($service['jobs']) ) {
			foreach($service['jobs'] as $jid => $job) {
				// Setup utc_pend_date
				$subscriptions[$sid]['subscription']['jobs'][$jid]['job']['utc_pend_date'] = date_format(date_create($job['job']['raw_pend_date']), 'U');
			}
		}

		//
		// Setup the start and end dates of the current subscription period
		//
		$cur_pstart_date = clone $date_started;
		$cur_pstart_year = $date_started->format('Y');
		$cur_pend_date = clone $cur_pstart_date;
		$cur_pend_date->add($interval);
		$cur_pend_date->sub($lessaday);
		// Setup due date
		$due_date = clone $cur_pend_date;
		$due_date->add($dueinterval);
		// Check for month rollover
		if( $cur_pend_date->format('j') >= 28 && $due_date->format('j') < 5 ) {
			$due_date->modify('last day of previous month');
		}
		// Check if end is last day of month
		elseif( $cur_pend_date->format('t') == $cur_pend_date->format('j') && $due_date->format('t') != $due_date->format('j') ) {
			$due_date->modify('last day of this month');
		}
		$count = 0;
		while( $due_date->getTimestamp() <= $end_date->getTimestamp() ) {
			//
			// Check to see if the job exists
			//
			$utc_pend_date = $cur_pend_date->getTimestamp();
			$exists = 0;
			if( isset($service['jobs']) ) {
				foreach($service['jobs'] as $jid => $job) {
					if( $subscriptions[$sid]['subscription']['jobs'][$jid]['job']['utc_pend_date'] == $utc_pend_date ) {
						$exists = 1;
						break;
					}
				}
			}
			//
			// Keep track of the current quarter, if a quarterly job
			//
			if( $service['repeat_type'] == 30 && $service['repeat_interval'] == 3 ) {
				$quarter = (($count%4)+1);
			}
			//
			// Setup the name for the job
			//
			if( $service['repeat_type'] == 30 ) {
				if( $service['repeat_interval'] == 3 ) {
					$name = $cur_pstart_year . " Q" . $quarter;
				} else {
					$name = date_format($cur_pstart_date, 'Y-M');
				}
			} elseif( $service['repeat_type'] == 40 ) {
				$name = date_format($cur_pstart_date, 'Y');
			} else {
				$name = '';
			}

			if( $exists == 0 ) {
				if( $cur_pend_date->getTimestamp() < time() ) {
					$status = '1';
					$status_text = $status_texts[$status];
				} else {
					$status = '2';
					$status_text = $status_texts[$status];
				}
				//
				// Add the job
				//
				array_push($jobs, array('job'=>array('id'=>'0', 'subscription_id'=>$service['id'],
					'service_id'=>$service['service_id'],
					'service_name'=>$service['service_name'], 'name'=>$name,
					'customer_id'=>$service['customer_id'], 'customer_type'=>$service['customer_type'],
					'customer_name'=>$service['customer_name'],
					'status'=>$status, 'status_text'=>$status_text,
					'utc_pend_date'=>$cur_pend_date->getTimestamp(),
					'pstart_date'=>date_format($cur_pstart_date, "M j, Y"), 'pend_date'=>date_format($cur_pend_date, "M j, Y"),
					'date_scheduled'=>'', 'date_started'=>'', 'date_due'=>date_format($due_date, 'M j, Y'), 'date_completed'=>'')));
			}
			//
			// Advance the year
			//
			if( $service['repeat_type'] == 30 ) {
				if( ($count+1)%(12/$service['repeat_interval']) == 0 ) {
					$cur_pstart_year++;
				}
			}

			//
			// Setup the next period
			//
			$cur_pstart_date->add($interval);
			$cur_pend_date = clone $cur_pstart_date;
			$cur_pend_date->add($interval);
			$cur_pend_date->sub($lessaday);
			// Setup due date
			$due_date = clone $cur_pend_date;
			$due_date->add($dueinterval);
			// Check for month rollover
			if( $cur_pend_date->format('j') >= 28 && $due_date->format('j') < 5 ) {
				$due_date->modify('last day of previous month');
			}
			// Check if end is last day of month
			elseif( $cur_pend_date->format('t') == $cur_pend_date->format('j') && $due_date->format('t') != $due_date->format('j') ) {
				$due_date->modify('last day of this month');
			}
			$count++;
		}
	}

	return array('stat'=>'ok', 'jobs'=>$jobs);
}
?>