text:
package main

import (
	"fmt"
	"os"
	"testing"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/steveeJ/gexpect"
	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/syndtr/gocapability/capability"
)

var capsTests = []struct {
	testName            string
	capIsolator         string
	capa                capability.Cap
	capInStage1Expected bool
	capInStage2Expected bool
	nonrootCapExpected  bool
}{
	{
		testName:            "Check we don't have CAP_NET_ADMIN without isolator",
		capIsolator:         "",
		capa:                capability.CAP_NET_ADMIN,
		capInStage1Expected: false,
		capInStage2Expected: false,
		nonrootCapExpected:  false,
	},
	{
		testName:            "Check we have CAP_MKNOD without isolator",
		capIsolator:         "",
		capa:                capability.CAP_MKNOD,
		capInStage1Expected: true,
		capInStage2Expected: true,
		nonrootCapExpected:  true,
	},
	{
		testName:            "Check we have CAP_NET_ADMIN with an isolator",
		capIsolator:         "CAP_NET_ADMIN,CAP_NET_BIND_SERVICE",
		capa:                capability.CAP_NET_ADMIN,
		capInStage1Expected: true,
		capInStage2Expected: true,
		nonrootCapExpected:  true,
	},
	{
		testName:            "Check we have CAP_NET_BIND_SERVICE with an isolator",
		capIsolator:         "CAP_NET_ADMIN,CAP_NET_BIND_SERVICE",
		capa:                capability.CAP_NET_BIND_SERVICE,
		capInStage1Expected: true,
		capInStage2Expected: true,
		nonrootCapExpected:  true,
	},
	{
		testName:            "Check we don't have CAP_NET_ADMIN with an isolator setting CAP_NET_BIND_SERVICE",
		capIsolator:         "CAP_NET_BIND_SERVICE",
		capa:                capability.CAP_NET_ADMIN,
		capInStage1Expected: false,
		capInStage2Expected: false,
		nonrootCapExpected:  false,
	},
}

func TestCaps(t *testing.T) {
	ctx := newRktRunCtx()
	defer ctx.cleanup()

	for i, tt := range capsTests {
		stage1Args := []string{"--exec=/inspect --print-caps-pid=1 --print-user"}
		stage2Args := []string{"--exec=/inspect --print-caps-pid=0 --print-user"}
		if tt.capIsolator != "" {
			stage1Args = append(stage1Args, "--capability="+tt.capIsolator)
			stage2Args = append(stage2Args, "--capability="+tt.capIsolator)
		}
		stage1FileName := patchTestACI("rkt-inspect-print-caps-stage1.aci", stage1Args...)
		stage2FileName := patchTestACI("rkt-inspect-print-caps-stage2.aci", stage2Args...)
		defer os.Remove(stage1FileName)
		defer os.Remove(stage2FileName)
		stageFileNames := []string{stage1FileName, stage2FileName}

		for _, stage := range []int{1, 2} {
			t.Logf("Running test #%v: %v [stage %v]", i, tt.testName, stage)

			cmd := fmt.Sprintf("%s --debug --insecure-skip-verify run --mds-register=false --set-env=CAPABILITY=%d %s", ctx.cmd(), int(tt.capa), stageFileNames[stage-1])
			t.Logf("Command: %v", cmd)
			child, err := gexpect.Spawn(cmd)
			if err != nil {
				t.Fatalf("Cannot exec rkt #%v: %v", i, err)
			}

			expectedLine := tt.capa.String()
			if (stage == 1 && tt.capInStage1Expected) || (stage == 2 && tt.capInStage2Expected) {
				expectedLine += "=enabled"
			} else {
				expectedLine += "=disabled"
			}
			err = expectWithOutput(child, expectedLine)
			if err != nil {
				t.Fatalf("Expected %q but not found: %v", expectedLine, err)
			}

			err = expectWithOutput(child, "User: uid=0 euid=0 gid=0 egid=0")
			if err != nil {
				t.Fatalf("Expected user 0 but not found: %v", err)
			}

			err = child.Wait()
			if err != nil {
				t.Fatalf("rkt didn't terminate correctly: %v", err)
			}
		}
		ctx.reset()
	}
}

func TestNonRootCaps(t *testing.T) {
	ctx := newRktRunCtx()
	defer ctx.cleanup()

	for i, tt := range capsTests {
		args := []string{"--exec=/inspect --print-caps-pid=0 --print-user", "--user=9000", "--group=9000"}
		if tt.capIsolator != "" {
			args = append(args, "--capability="+tt.capIsolator)
		}
		fileName := patchTestACI("rkt-inspect-print-caps-nonroot.aci", args...)
		defer os.Remove(fileName)

		t.Logf("Running test #%v: %v [non-root]", i, tt.testName)

		cmd := fmt.Sprintf("%s --debug --insecure-skip-verify run --mds-register=false --set-env=CAPABILITY=%d %s", ctx.cmd(), int(tt.capa), fileName)
		t.Logf("Command: %v", cmd)
		child, err := gexpect.Spawn(cmd)
		if err != nil {
			t.Fatalf("Cannot exec rkt #%v: %v", i, err)
		}

		expectedLine := tt.capa.String()
		if tt.nonrootCapExpected {
			expectedLine += "=enabled"
		} else {
			expectedLine += "=disabled"
		}
		err = expectWithOutput(child, expectedLine)
		if err != nil {
			t.Fatalf("Expected %q but not found: %v", expectedLine, err)
		}

		err = expectWithOutput(child, "User: uid=9000 euid=9000 gid=9000 egid=9000")
		if err != nil {
			t.Fatalf("Expected user 9000 but not found: %v", err)
		}

		err = child.Wait()
		if err != nil {
			t.Fatalf("rkt didn't terminate correctly: %v", err)
		}
		ctx.reset()
	}
}


text:
package org.interledger.cryptoconditions;

import net.i2p.crypto.eddsa.EdDSAPublicKey;
import org.interledger.cryptoconditions.der.DerOutputStream;
import org.interledger.cryptoconditions.der.DerTag;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Objects;

/**
 * Implementation of a crypto-condition using the ED-25519 and SHA-256 functions.
 */
public final class Ed25519Sha256Condition extends Sha256Condition implements SimpleCondition {

  /**
   * The public key and signature are a fixed size therefore the cost for an ED25519
   * crypto-condition is fixed at 131072.
   */
  private static final long COST = 131072L;

  /**
   * Constructs an instance of the condition.
   *
   * @param key A {@link EdDSAPublicKey} used to create the fingerprint.
   */
  public Ed25519Sha256Condition(final EdDSAPublicKey key) {
    super(
        CryptoConditionType.ED25519_SHA256,
        COST,
        hashFingerprintContents(constructFingerprintContents(key))
    );
  }

  /**
   *
Constructs an instance of the condition with the given fingerprint and cost.

   *
   *
This constructor _should_ be primarily used by CODECs, whereas developers should, in
   * general, use the {@link #Ed25519Sha256Condition(EdDSAPublicKey)} constructor, or else create an
   * actual fulfillment via {@link Ed25519Sha256Fulfillment#Ed25519Sha256Fulfillment(EdDSAPublicKey,
   * byte[])} and then generate a condition from that object.

   *
   * @param fingerprint The binary representation of the fingerprint for this condition.
   */
  public Ed25519Sha256Condition(final byte[] fingerprint) {
    super(CryptoConditionType.ED25519_SHA256, COST, fingerprint);
  }

  /**
   * Constructs the fingerprint for this condition.
   *

   * Note: This method is package-private as (opposed to private) for testing purposes.
   */
  static final byte[] constructFingerprintContents(final EdDSAPublicKey publicKey) {
    Objects.requireNonNull(publicKey);

    try {
      // Write public publicKey
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DerOutputStream out = new DerOutputStream(baos);
      out.writeTaggedObject(0, publicKey.getA().toByteArray());
      out.close();
      byte[] buffer = baos.toByteArray();

      // Wrap SEQUENCE
      baos = new ByteArrayOutputStream();
      out = new DerOutputStream(baos);
      out.writeEncoded(DerTag.CONSTRUCTED.getTag() + DerTag.SEQUENCE.getTag(), buffer);
      out.close();

      return baos.toByteArray();

    } catch (IOException ioe) {
      throw new UncheckedIOException("DER Encoding Error", ioe);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.hl7.v3;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="POCD_MT000040.LanguageCommunication", propOrder={"realmCode", "typeId", "templateId", "languageCode", "modeCode", "proficiencyLevelCode", "preferenceInd"})
public class POCDMT000040LanguageCommunication
{
  protected List<CS> realmCode;
  protected POCDMT000040InfrastructureRootTypeId typeId;
  protected List<II> templateId;
  protected CS languageCode;
  protected CE modeCode;
  protected CE proficiencyLevelCode;
  protected BL preferenceInd;

  @XmlAttribute(name="nullFlavor")
  protected List<String> nullFlavor;

  public List<CS> getRealmCode()
  {
    if (this.realmCode == null) {
      this.realmCode = new ArrayList();
    }
    return this.realmCode;
  }

  public POCDMT000040InfrastructureRootTypeId getTypeId()
  {
    return this.typeId;
  }

  public void setTypeId(POCDMT000040InfrastructureRootTypeId value)
  {
    this.typeId = value;
  }

  public List<II> getTemplateId()
  {
    if (this.templateId == null) {
      this.templateId = new ArrayList();
    }
    return this.templateId;
  }

  public CS getLanguageCode()
  {
    return this.languageCode;
  }

  public void setLanguageCode(CS value)
  {
    this.languageCode = value;
  }

  public CE getModeCode()
  {
    return this.modeCode;
  }

  public void setModeCode(CE value)
  {
    this.modeCode = value;
  }

  public CE getProficiencyLevelCode()
  {
    return this.proficiencyLevelCode;
  }

  public void setProficiencyLevelCode(CE value)
  {
    this.proficiencyLevelCode = value;
  }

  public BL getPreferenceInd()
  {
    return this.preferenceInd;
  }

  public void setPreferenceInd(BL value)
  {
    this.preferenceInd = value;
  }

  public List<String> getNullFlavor()
  {
    if (this.nullFlavor == null) {
      this.nullFlavor = new ArrayList();
    }
    return this.nullFlavor;
  }
}


text:
"""Interface for AlphaGo self-play"""
from AlphaGo.go import GameState

class play_match(object):
    """Interface to handle play between two players."""

    def __init__(self, player1, player2, save_dir=None, size=19):
        # super(ClassName, self).__init__()
        self.player1 = player1
        self.player2 = player2
        self.state = GameState(size=size)
        # I Propose that GameState should take a top-level save directory,
        # then automatically generate the specific file name

    def _play(self, player):
        move = player.get_move(self.state)
        # TODO: Fix is_eye?
        self.state.do_move(move)  # Return max prob sensible legal move
        # self.state.write_to_disk()
        if len(self.state.history) > 1:
            if self.state.history[-1] is None and self.state.history[-2] is None \
                    and self.state.current_player == -1:
                end_of_game = True
            else:
                end_of_game = False
        else:
            end_of_game = False
        return end_of_game

    def play(self):
        """Play one turn, update game state, save to disk"""
        end_of_game = self._play(self.player1)
        # This is incorrect.
        return end_of_game


text:
<?php

/**
 * VideoRecordingFormatType
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    mediaSCORE
 * @subpackage model
 * @author     Nouman Tayyab
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class VideoRecordingFormatType extends BaseVideoRecordingFormatType {

    public static $constants = array('' => 'Select', 0 => 'NTSC', 1 => 'PAL', 2 => 'SECAM', 3 => 'Unknown');

}


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

import * as Common from '../../../core/common/common.js';

import inspectorSyntaxHighlightStyles from '../inspectorSyntaxHighlight.css.legacy.js';

let themeSupportInstance: ThemeSupport;

const themeValuesCache = new Map<CSSStyleDeclaration, Map<string, string>>();

export class ThemeSupport extends EventTarget {
  private themeNameInternal = 'default';
  private customSheets: Set<string> = new Set();
  private computedRoot = Common.Lazy.lazy(() => window.getComputedStyle(document.documentElement));

  private constructor(private setting: Common.Settings.Setting<string>) {
    super();
  }

  static hasInstance(): boolean {
    return typeof themeSupportInstance !== 'undefined';
  }

  static instance(opts: {
    forceNew: boolean|null,
    setting: Common.Settings.Setting<string>|null,
  } = {forceNew: null, setting: null}): ThemeSupport {
    const {forceNew, setting} = opts;
    if (!themeSupportInstance || forceNew) {
      if (!setting) {
        throw new Error(`Unable to create theme support: setting must be provided: ${new Error().stack}`);
      }

      themeSupportInstance = new ThemeSupport(setting);
    }

    return themeSupportInstance;
  }

  getComputedValue(variableName: string, target: Element|null = null): string {
    const computedRoot = target ? window.getComputedStyle(target) : this.computedRoot();
    if (typeof computedRoot === 'symbol') {
      throw new Error(`Computed value for property (${variableName}) could not be found on :root.`);
    }

    // Since we might query the same variable name from various targets we need to support
    // per-target caching of computed values. Here we attempt to locate the particular computed
    // value cache for the target. If no target was specified we use the default computed root,
    // which belongs to the document element.
    let computedRootCache = themeValuesCache.get(computedRoot);
    if (!computedRootCache) {
      computedRootCache = new Map<string, string>();
      themeValuesCache.set(computedRoot, computedRootCache);
    }

    // Since theme changes trigger a reload, we can avoid repeatedly looking up color values
    // dynamically. Instead we can look up the first time and cache them for future use,
    // knowing that the cache will be invalidated by virtue of a reload when the theme changes.
    let cachedValue = computedRootCache.get(variableName);
    if (!cachedValue) {
      cachedValue = computedRoot.getPropertyValue(variableName).trim();

      // If we receive back an empty value (nothing has been set) we don't store it for the future.
      // This means that subsequent requests will continue to query the styles in case the value
      // has been set.
      if (cachedValue) {
        computedRootCache.set(variableName, cachedValue);
      }
    }

    return cachedValue;
  }

  hasTheme(): boolean {
    return this.themeNameInternal !== 'default';
  }

  themeName(): string {
    return this.themeNameInternal;
  }

  injectHighlightStyleSheets(element: Element|ShadowRoot): void {
    this.appendStyle(element, inspectorSyntaxHighlightStyles);
  }

  appendStyle(node: Node, {cssContent}: {cssContent: string}): void {
    const styleElement = document.createElement('style');
    styleElement.textContent = cssContent;
    node.appendChild(styleElement);
  }

  injectCustomStyleSheets(element: Element|ShadowRoot): void {
    for (const sheet of this.customSheets) {
      const styleElement = document.createElement('style');
      styleElement.textContent = sheet;
      element.appendChild(styleElement);
    }
  }

  addCustomStylesheet(sheetText: string): void {
    this.customSheets.add(sheetText);
  }

  applyTheme(document: Document): void {
    const isForcedColorsMode = window.matchMedia('(forced-colors: active)').matches;
    const systemPreferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default';

    const useSystemPreferred = this.setting.get() === 'systemPreferred' || isForcedColorsMode;
    this.themeNameInternal = useSystemPreferred ? systemPreferredTheme : this.setting.get();

    const wasDarkThemed = document.documentElement.classList.contains('-theme-with-dark-background');
    document.documentElement.classList.toggle('-theme-with-dark-background', this.themeNameInternal === 'dark');

    const isDarkThemed = document.documentElement.classList.contains('-theme-with-dark-background');

    // In the event the theme changes we need to clear caches and notify subscribers.
    if (wasDarkThemed !== isDarkThemed) {
      themeValuesCache.clear();
      this.customSheets.clear();
      this.dispatchEvent(new ThemeChangeEvent());
    }
  }
}

export class ThemeChangeEvent extends Event {
  static readonly eventName = 'themechange';

  constructor() {
    super(ThemeChangeEvent.eventName, {bubbles: true, composed: true});
  }
}


text:
/*
 * $Id: maildirdriver.c,v 1.17 2008/02/17 13:13:26 hoa Exp $
 */

/*
  flags directory MUST be kept so that we can have other flags
  than standards
*/

#ifdef HAVE_CONFIG_H
#	include <config.h>
#endif

#include "maildirdriver.h"

#include <stdio.h>
#include <sys/types.h>
#ifdef WIN32
#	include "win_etpan.h"
#else
#	include <dirent.h>
#	include <unistd.h>
#	include <sys/mman.h>
#endif
#include <sys/stat.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

#include "maildir.h"
#include "maildriver_tools.h"
#include "maildirdriver_message.h"
#include "maildirdriver_tools.h"
#include "mailmessage.h"
#include "generic_cache.h"

static int initialize(mailsession * session);

static void uninitialize(mailsession * session);

static int connect_path(mailsession * session, const char * path);

static int logout(mailsession * session);

static int expunge_folder(mailsession * session);

static int status_folder(mailsession * session, const char * mb,
    uint32_t * result_messages, uint32_t * result_recent,
    uint32_t * result_unseen);

static int recent_number(mailsession * session, const char * mb,
    uint32_t * result);

static int unseen_number(mailsession * session, const char * mb,
    uint32_t * result);

static int messages_number(mailsession * session, const char * mb,
    uint32_t * result);

static int append_message(mailsession * session,
    const char * message, size_t size);

static int append_message_flags(mailsession * session,
    const char * message, size_t size, struct mail_flags * flags);

static int get_messages_list(mailsession * session,
    struct mailmessage_list ** result);

static int get_envelopes_list(mailsession * session,
    struct mailmessage_list * env_list);

static int check_folder(mailsession * session);

static int get_message_by_uid(mailsession * session,
    const char * uid, mailmessage ** result);

static mailsession_driver local_maildir_session_driver = {
   /* sess_name */ "maildir",

  /* sess_initialize */ initialize,
  /* sess_uninitialize */ uninitialize,

  /* sess_parameters */ NULL,

  /* sess_connect_stream */ NULL,
  /* sess_connect_path */ connect_path,
  /* sess_starttls */ NULL,
  /* sess_login */ NULL,
  /* sess_logout */ logout,
  /* sess_noop */ NULL,

  /* sess_build_folder_name */ NULL,
  /* sess_create_folder */ NULL,
  /* sess_delete_folder */ NULL,
  /* sess_rename_folder */ NULL,
  /* sess_check_folder */ check_folder,
  /* sess_examine_folder */ NULL,
  /* sess_select_folder */ NULL,
  /* sess_expunge_folder */ expunge_folder,
  /* sess_status_folder */ status_folder,
  /* sess_messages_number */ messages_number,
  /* sess_recent_number */ recent_number,
  /* sess_unseen_number */ unseen_number,
  /* sess_list_folders */ NULL,
  /* sess_lsub_folders */ NULL,
  /* sess_subscribe_folder */ NULL,
  /* sess_unsubscribe_folder */ NULL,

  /* sess_append_message */ append_message,
  /* sess_append_message_flags */ append_message_flags,
  /* sess_copy_message */ NULL,
  /* sess_move_message */ NULL,

  /* sess_get_message */ NULL,
  /* sess_get_message_by_uid */ get_message_by_uid,

  /* sess_get_messages_list */ get_messages_list,
  /* sess_get_envelopes_list */ get_envelopes_list,
  /* sess_remove_message */ NULL,
#if 0
  /* sess_search_messages */ maildriver_generic_search_messages,
#endif
  /* sess_login_sasl */ NULL
};

mailsession_driver * maildir_session_driver = &local_maildir_session_driver;

static int flags_store_process(struct maildir * md,
    struct mail_flags_store * flags_store);

static inline struct maildir_session_state_data * get_data(mailsession * session)
{
  return session->sess_data;
}

static struct maildir * get_maildir_session(mailsession * session)
{
  return get_data(session)->md_session;
}

static int initialize(mailsession * session)
{
  struct maildir_session_state_data * data;

  data = malloc(sizeof(* data));
  if (data == NULL)
    goto err;

  data->md_session = NULL;

  data->md_flags_store = mail_flags_store_new();
  if (data->md_flags_store == NULL)
    goto free;

  session->sess_data = data;

  return MAIL_NO_ERROR;

 free:
  free(data);
 err:
  return MAIL_ERROR_MEMORY;
}

static void uninitialize(mailsession * session)
{
  struct maildir_session_state_data * data;

  data = get_data(session);

  if (data->md_session != NULL)
    flags_store_process(data->md_session, data->md_flags_store);

  mail_flags_store_free(data->md_flags_store);
  if (data->md_session != NULL)
    maildir_free(data->md_session);

  free(data);

  session->sess_data = NULL;
}

static int connect_path(mailsession * session, const char * path)
{
  struct maildir * md;
  int res;
  int r;

  if (get_maildir_session(session) != NULL) {
    res = MAIL_ERROR_BAD_STATE;
    goto err;
  }

  md = maildir_new(path);
  if (md == NULL) {
    res = MAIL_ERROR_MEMORY;
    goto err;
  }

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR) {
    res = maildirdriver_maildir_error_to_mail_error(r);
    goto free;
  }

  get_data(session)->md_session = md;

  return MAIL_NO_ERROR;

 free:
  maildir_free(md);
 err:
  return res;
}

static int logout(mailsession * session)
{
  struct maildir * md;

  check_folder(session);

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  maildir_free(md);
  get_data(session)->md_session = NULL;

  return MAIL_NO_ERROR;
}

/* folders operations */

static int status_folder(mailsession * session, const char * mb,
    uint32_t * result_messages, uint32_t * result_recent,
    uint32_t * result_unseen)
{
  int r;
  struct maildir * md;
  unsigned int i;
  uint32_t messages;
  uint32_t recent;
  uint32_t unseen;

  check_folder(session);

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR)
    return maildirdriver_maildir_error_to_mail_error(r);

  messages = 0;
  recent = 0;
  unseen = 0;
  for(i = 0 ; i < carray_count(md->mdir_msg_list) ; i ++) {
    struct maildir_msg * msg;

    msg = carray_get(md->mdir_msg_list, i);
    if ((msg->msg_flags & MAILDIR_FLAG_NEW) != 0)
      recent ++;
    if ((msg->msg_flags & MAILDIR_FLAG_SEEN) == 0)
      unseen ++;
    messages ++;
  }

  * result_messages = messages;
  * result_recent = recent;
  * result_unseen = unseen;

  return MAIL_NO_ERROR;
}

static int messages_number(mailsession * session, const char * mb,
    uint32_t * result)
{
  struct maildir * md;
  int r;

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR)
    return maildirdriver_maildir_error_to_mail_error(r);

  * result = carray_count(md->mdir_msg_list);

  return MAIL_NO_ERROR;
}

static int unseen_number(mailsession * session, const char * mb,
    uint32_t * result)
{
  uint32_t messages;
  uint32_t recent;
  uint32_t unseen;
  int r;

  r = status_folder(session, mb, &messages, &recent, &unseen);
  if (r != MAIL_NO_ERROR)
    return r;

  * result = unseen;

  return MAIL_NO_ERROR;
}

static int recent_number(mailsession * session, const char * mb,
    uint32_t * result)
{
  uint32_t messages;
  uint32_t recent;
  uint32_t unseen;
  int r;

  r = status_folder(session, mb, &messages, &recent, &unseen);
  if (r != MAIL_NO_ERROR)
    return r;

  * result = recent;

  return MAIL_NO_ERROR;
}

/* messages operations */

static int append_message(mailsession * session,
    const char * message, size_t size)
{
#if 0
  struct maildir * md;
  int r;

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_message_add(md, message, size);
  if (r != MAILDIR_NO_ERROR)
    return maildirdriver_maildir_error_to_mail_error(r);

  return MAIL_NO_ERROR;
#endif

  return append_message_flags(session, message, size, NULL);
}

static int append_message_flags(mailsession * session,
    const char * message, size_t size, struct mail_flags * flags)
{
  struct maildir * md;
  int r;
  char uid[PATH_MAX];
  struct maildir_msg * md_msg;
  chashdatum key;
  chashdatum value;
  uint32_t md_flags;

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_message_add_uid(md, message, size,
      uid, sizeof(uid));
  if (r != MAILDIR_NO_ERROR)
    return maildirdriver_maildir_error_to_mail_error(r);

  if (flags == NULL)
    goto exit;

  key.data = uid;
  key.len = strlen(uid);
  r = chash_get(md->mdir_msg_hash, &key, &value);
  if (r < 0)
    goto exit;

  md_msg = value.data;

  md_flags = maildirdriver_flags_to_maildir_flags(flags->fl_flags);

  r = maildir_message_change_flags(md, uid, md_flags);
  if (r != MAILDIR_NO_ERROR)
    goto exit;

  return MAIL_NO_ERROR;

 exit:
  return MAIL_NO_ERROR;
}

static int get_messages_list(mailsession * session,
    struct mailmessage_list ** result)
{
  struct maildir * md;
  int r;
  struct mailmessage_list * env_list;
  int res;

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR) {
    res = maildirdriver_maildir_error_to_mail_error(r);
    goto err;
  }

  r = maildir_get_messages_list(session, md,
      maildir_message_driver, &env_list);
  if (r != MAILDIR_NO_ERROR) {
    res = r;
    goto free_list;
  }

  * result = env_list;

  return MAIL_NO_ERROR;

 free_list:
  mailmessage_list_free(env_list);
 err:
  return res;
}

static int get_envelopes_list(mailsession * session,
    struct mailmessage_list * env_list)
{
  int r;
  struct maildir * md;
  unsigned int i;
  int res;

  check_folder(session);

  md = get_maildir_session(session);
  if (md == NULL) {
    res = MAIL_ERROR_BAD_STATE;
    goto err;
  }

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR) {
    res = maildirdriver_maildir_error_to_mail_error(r);
    goto err;
  }

  r = maildriver_generic_get_envelopes_list(session, env_list);
  if (r != MAIL_NO_ERROR) {
    res = r;
    goto err;
  }

  for(i = 0 ; i < carray_count(env_list->msg_tab) ; i++) {
    struct maildir_msg * md_msg;
    mailmessage * msg;
    uint32_t driver_flags;
    clist * ext;
    chashdatum key;
    chashdatum value;

    msg = carray_get(env_list->msg_tab, i);

    key.data = msg->msg_uid;
    key.len = strlen(msg->msg_uid);
    r = chash_get(md->mdir_msg_hash, &key, &value);
    if (r < 0)
      continue;

    md_msg = value.data;

    driver_flags = maildirdriver_maildir_flags_to_flags(md_msg->msg_flags);

    if (msg->msg_flags == NULL) {
      ext = clist_new();
      if (ext == NULL) {
        res = MAIL_ERROR_MEMORY;
        continue;
      }

      msg->msg_flags = mail_flags_new(driver_flags, ext);
      if (msg->msg_flags == NULL) {
        clist_free(ext);
        res = MAIL_ERROR_MEMORY;
        continue;
      }

      if ((md_msg->msg_flags & MAILDIR_FLAG_NEW) != 0) {
        mail_flags_store_set(get_data(session)->md_flags_store, msg);
      }
    }
    else {
      msg->msg_flags->fl_flags &= MAIL_FLAG_FORWARDED;
      msg->msg_flags->fl_flags |= driver_flags;
    }
  }

  return MAIL_NO_ERROR;

 err:
  return res;
}

static int expunge_folder(mailsession * session)
{
  unsigned int i;
  int r;
  int res;
  struct maildir * md;

  check_folder(session);

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR) {
    res = maildirdriver_maildir_error_to_mail_error(r);
    goto err;
  }

  for(i = 0 ; i < carray_count(md->mdir_msg_list) ; i++) {
    struct maildir_msg * md_msg;

    md_msg = carray_get(md->mdir_msg_list, i);

    if ((md_msg->msg_flags & MAILDIR_FLAG_TRASHED) != 0)
      maildir_message_remove(md, md_msg->msg_uid);
  }

  return MAIL_NO_ERROR;

 err:
  return res;
}

static int flags_store_process(struct maildir * md,
    struct mail_flags_store * flags_store)
{
  unsigned int i;

  if (carray_count(flags_store->fls_tab) == 0)
    return MAIL_NO_ERROR;

  for(i = 0 ; i < carray_count(flags_store->fls_tab) ; i ++) {
    mailmessage * msg;
    uint32_t md_flags;

    msg = carray_get(flags_store->fls_tab, i);
    md_flags = maildirdriver_flags_to_maildir_flags(msg->msg_flags->fl_flags);
    md_flags &= ~MAILDIR_FLAG_NEW;

    maildir_message_change_flags(md, msg->msg_uid, md_flags);
  }

  mail_flags_store_clear(flags_store);

  return MAIL_NO_ERROR;
}

static int check_folder(mailsession * session)
{
  struct mail_flags_store * flags_store;
  struct maildir_session_state_data * data;
  struct maildir * md;

  md = get_maildir_session(session);
  if (md == NULL)
    return MAIL_ERROR_BAD_STATE;

  data = get_data(session);
  flags_store = data->md_flags_store;

  return flags_store_process(md, flags_store);
}

static int get_message_by_uid(mailsession * session,
    const char * uid, mailmessage ** result)
{
  int r;
  struct maildir * md;
  int res;
  mailmessage * msg;
  char * msg_filename;
  struct stat stat_info;

  md = get_maildir_session(session);

  /* update maildir data */

  r = maildir_update(md);
  if (r != MAILDIR_NO_ERROR) {
    res = maildirdriver_maildir_error_to_mail_error(r);
    goto err;
  }

  msg_filename = maildir_message_get(md, uid);
  if (msg_filename == NULL) {
    res = MAIL_ERROR_INVAL;
    goto err;
  }

  r = stat(msg_filename, &stat_info);
  free(msg_filename);
  if (r < 0) {
    res = MAIL_ERROR_INVAL;
    goto err;
  }

  /* create message */

  msg = mailmessage_new();
  if (msg == NULL) {
    res = MAIL_ERROR_MEMORY;
    goto err;
  }

  r = mailmessage_init(msg, session, maildir_message_driver,
      0, stat_info.st_size);
  if (r != MAIL_NO_ERROR) {
    mailmessage_free(msg);
    res = r;
    goto err;
  }

  msg->msg_uid = strdup(uid);
  if (msg->msg_uid == NULL) {
    mailmessage_free(msg);
    res = r;
    goto err;
  }

  * result = msg;

  return MAIL_NO_ERROR;

 err:
  return res;
}


text:
  L'Étoile est
       un village
       géographiquement positionné dans le département de Jura en Franche-Comté. Elle totalisait 563 habitants en 2008.

La commune propose quelques  aménagements, elle propose entre autres un terrain de sport.

Le parc d'habitations, à L'Étoile, se décomposait en 2011 en 15 appartements et 246 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de emmenager à L'Étoile, vous pourrez facilement trouver une maison à vendre.

À L'Étoile, la valorisation moyenne à la vente d'un appartement se situe à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2 458 € du m². À la location le prix moyen se situe à 5,2 € du m² mensuel.

À coté de L'Étoile sont localisées les villes de
Montmorot à 4 km, 3 124 habitants,
Montain située à 3 km, 493 habitants,
Quintigny située à 2 km, 220 habitants,
Lavigny située à 4 km, 364 habitants,
Plainoiseau située à 2 km, 529 habitants,
Le Louverot à 3 km, 273 habitants,
 entre autres. De plus, L'Étoile est située à seulement quatre km de Lons-le-Saunier.


text:
layout: section
title: "Portability Framework"
permalink: /contribute/portability/
section_menu: section-menu/contribute.html
---
<!--
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Portability Framework

* TOC
{:toc}

## Overview

Interoperability between SDKs and runners is a key aspect of Apache
Beam. So far, however, the reality is that most runners support the
Java SDK only, because each SDK-runner combination requires non-trivial
work on both sides. All runners are also currently written in Java,
which makes support of non-Java SDKs far more expensive. The
_portability framework_ aims to rectify this situation and provide
full interoperability across the Beam ecosystem.

The portability framework introduces well-defined, language-neutral
data structures and protocols between the SDK and runner. This interop
layer -- called the _portability API_ -- ensures that SDKs and runners
can work with each other uniformly, reducing the interoperability
burden for both SDKs and runners to a constant effort.  It notably
ensures that _new_ SDKs automatically work with existing runners and
vice versa.  The framework introduces a new runner, the _Universal
Local Runner (ULR)_, as a practical reference implementation that
complements the direct runners. Finally, it enables cross-language
pipelines (sharing I/O or transformations across SDKs) and
user-customized execution environments ("custom containers").

The portability API consists of a set of smaller contracts that
isolate SDKs and runners for job submission, management and
execution. These contracts use protobufs and gRPC for broad language
support.

 * **Job submission and management**: The _Runner API_ defines a
   language-neutral pipeline representation with transformations
   specifying the execution environment as a docker container
   image. The latter both allows the execution side to set up the
   right environment as well as opens the door for custom containers
   and cross-environment pipelines. The _Job API_ allows pipeline
   execution and configuration to be managed uniformly.

 * **Job execution**: The _SDK harness_ is a SDK-provided
   program responsible for executing user code and is run separately
   from the runner.  The _Fn API_ defines an execution-time binary
   contract between the SDK harness and the runner that describes how
   execution tasks are managed and how data is transferred. In
   addition, the runner needs to handle progress and monitoring in an
   efficient and language-neutral way. SDK harness initialization
   relies on the _Provision_ and _Artifact APIs_ for obtaining staged
   files, pipeline options and environment information. Docker
   provides isolation between the runner and SDK/user environments to
   the benefit of both as defined by the _container contract_. The
   containerization of the SDK gives it (and the user, unless the SDK
   is closed) full control over its own environment without risk of
   dependency conflicts. The runner has significant freedom regarding
   how it manages the SDK harness containers.

The goal is that all (non-direct) runners and SDKs eventually support
the portability API, perhaps exclusively.

## Design

The [model protos](https://github.com/apache/beam/tree/master/model)
contain all aspects of the portability API and is the truth on the
ground. The proto definitions supercede any design documents. The main
design documents are the following:

 * [Runner API](https://s.apache.org/beam-runner-api). Pipeline
   representation and discussion on primitive/composite transforms and
   optimizations.

 * [Job API](https://s.apache.org/beam-job-api). Job submission and
   management protocol.

 * [Fn API](https://s.apache.org/beam-fn-api). Execution-side control
   and data protocols and overview.

 * [Container
   contract](https://s.apache.org/beam-fn-api-container-contract).
   Execution-side docker container invocation and provisioning
   protocols. See
   [CONTAINERS.md](https://github.com/apache/beam/blob/master/sdks/CONTAINERS.md)
   for how to build container images.

In discussion:

 * [Cross
   language](https://s.apache.org/beam-mixed-language-pipelines). Options
   and tradeoffs for how to handle various kinds of
   multi-language/multi-SDK pipelines.

## Development

The portability framework is a substantial effort that touches every
Beam component. In addition to the sheer magnitude, a major challenge
is engineering an interop layer that does not significantly compromise
performance due to the additional serialization overhead of a
language-neutral protocol.

### Roadmap

The proposed project phases are roughly as follows and are not
strictly sequential, as various components will likely move at
different speeds. Additionally, there have been (and continues to be)
supporting refactorings that are not always tracked as part of the
portability effort. Work already done is not tracked here either.

 * **P1 [MVP]**: Implement the fundamental plumbing for portable SDKs
   and runners for batch and streaming, including containers and the
   ULR
   [[BEAM-2899](https://issues.apache.org/jira/browse/BEAM-2899)]. Each
   SDK and runner should use the portability framework at least to the
   extent that wordcount
   [[BEAM-2896](https://issues.apache.org/jira/browse/BEAM-2896)] and
   windowed wordcount
   [[BEAM-2941](https://issues.apache.org/jira/browse/BEAM-2941)] run
   portably.

 * **P2 [Feature complete]**: Design and implement portability support
   for remaining execution-side features, so that any pipeline from
   any SDK can run portably on any runner. These features include side
   inputs
   [[BEAM-2863](https://issues.apache.org/jira/browse/BEAM-2863)], User state [[BEAM-2862](https://issues.apache.org/jira/browse/BEAM-2862)], User
   timers
   [[BEAM-2925](https://issues.apache.org/jira/browse/BEAM-2925)],
   Splittable DoFn
   [[BEAM-2896](https://issues.apache.org/jira/browse/BEAM-2896)] and
   more.  Each SDK and runner should use the portability framework at
   least to the extent that the mobile gaming examples
   [[BEAM-2940](https://issues.apache.org/jira/browse/BEAM-2940)] run
   portably.

 * **P3 [Performance]**: Measure and tune performance of portable
   pipelines using benchmarks such as Nexmark. Features such as
   progress reporting
   [[BEAM-2940](https://issues.apache.org/jira/browse/BEAM-2940)],
   combiner lifting
   [[BEAM-2937](https://issues.apache.org/jira/browse/BEAM-2937)] and
   fusion are expected to be needed.

 * **P4 [Cross language]**: Design and implement cross-language
   pipeline support, including how the ecosystem of shared transforms
   should work.

### Issues

The portability effort touches every component, so the "portability"
label is used to identify all portability-related issues. Pure
design or proto definitions should use the "beam-model" component. A
common pattern for new portability features is that the overall
feature is in "beam-model" with subtasks for each SDK and runner in
their respective components.

**JIRA:** [query](https://issues.apache.org/jira/issues/?filter=12341256)

### Status

MVP in progress (near completion for Flink runner). See the
[Portability support table](https://s.apache.org/apache-beam-portability-support-table)
for details.

#### Running Python wordcount on Flink

The Flink runner is currently the only runner to support portable pipeline execution.
To run a basic Python wordcount (in batch mode) with embedded Flink:

1. Run once to build the SDK harness container: `./gradlew :beam-sdks-python-container:docker`
2. Start the Flink portable JobService endpoint: `./gradlew :beam-runners-flink_2.11-job-server:runShadow`
3. Submit the wordcount pipeline to above endpoint: `./gradlew :beam-sdks-python:portableWordCount -PjobEndpoint=localhost:8099`

To run the pipeline in streaming mode: `./gradlew :beam-sdks-python:portableWordCount -PjobEndpoint=localhost:8099 -Pstreaming`

To run on a separate [Flink cluster](https://ci.apache.org/projects/flink/flink-docs-release-1.5/quickstart/setup_quickstart.html):

1. Start local Flink cluster
2. Create shaded JobService jar: `./gradlew :beam-runners-flink_2.11-job-server:installShadowDist`
3. Optional optimization step: Place the generated JobServer Jar `beam/runners/flink/job-server/build/libs/beam-runners-flink_2.11-job-server-2.7.0-SNAPSHOT.jar` in `flink/lib` and change class loading order for Flink by adding `classloader.resolve-order: parent-first` to `conf/flink-conf.yaml`.
4. Start JobService with Flink web service endpoint: `./gradlew :beam-runners-flink_2.11-job-server:runShadow -PflinkMasterUrl=localhost:8081`
5. Submit the pipeline.


text:
namespace ntp_snippets {

// Represents the status of a category of content suggestions.
// On Android builds, a Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome.browser.ntp.snippets
enum class CategoryStatus {
  // The provider is still initializing and it is not yet determined whether
  // content suggestions will be available or not.
  INITIALIZING,

  // Content suggestions are available (though the list of available suggestions
  // may be empty simply because there are no reasonable suggestions to be made
  // at the moment).
  AVAILABLE,
  // Content suggestions are provided but not yet loaded.
  AVAILABLE_LOADING,

  // There is no provider that provides suggestions for this category.
  NOT_PROVIDED,
  // The entire content suggestions feature has explicitly been disabled as part
  // of the service configuration.
  ALL_SUGGESTIONS_EXPLICITLY_DISABLED,
  // Content suggestions from a specific category have been disabled as part of
  // the service configuration. Any suggestions from this category should be
  // removed from the UI immediately.
  CATEGORY_EXPLICITLY_DISABLED,

  // Content suggestions are not available because an error occurred when
  // loading or updating them. Any suggestions from this category should be
  // removed from the UI immediately.
  LOADING_ERROR
};

// Determines whether the given status is one of the AVAILABLE statuses.
bool IsCategoryStatusAvailable(CategoryStatus status);

// Determines whether the given status is INITIALIZING or one of the AVAILABLE
// statuses. All of these statuses have in common that there is or will soon be
// content.
bool IsCategoryStatusInitOrAvailable(CategoryStatus status);

}  // namespace ntp_snippets

#endif  // COMPONENTS_NTP_SNIPPETS_CATEGORY_STATUS_H_


text:
+++
cast = ["a", "b", "c"]
date = "2016-06-13T21:41:34-04:00"
description = ""
genre = ["a", "b", "c"]
poster_url = ""
rating = ""
stars = 1
title = ""
year = ""
+++

{
  "Title": "TRON",
  "Year": "1982",
  "Rated": "PG",
  "Released": "09 Jul 1982",
  "Runtime": "96 min",
  "Genre": "Action, Adventure, Sci-Fi",
  "Director": "Steven Lisberger",
  "Writer": "Steven Lisberger (screenplay), Steven Lisberger (story), Bonnie MacBird (story)",
  "Actors": "Jeff Bridges, Bruce Boxleitner, David Warner, Cindy Morgan",
  "Plot": "A computer hacker is abducted into the digital world and forced to participate in gladiatorial games where his only chance of escape is with the help of a heroic security program.",
  "Language": "English",
  "Country": "USA",
  "Awards": "Nominated for 2 Oscars. Another 2 wins & 6 nominations.",
  "Poster": "http://ia.media-imdb.com/images/M/MV5BMTY0OTM4ODM2MF5BMl5BanBnXkFtZTgwMTI0NDIxMDE@._V1_SX300.jpg",
  "Metascore": "N/A",
  "imdbRating": "6.8",
  "imdbVotes": "93,099",
  "imdbID": "tt0084827",
  "Type": "movie",
  "tomatoMeter": "70",
  "tomatoImage": "fresh",
  "tomatoRating": "6.4",
  "tomatoReviews": "54",
  "tomatoFresh": "38",
  "tomatoRotten": "16",
  "tomatoConsensus": "Though perhaps not as strong dramatically as it is technologically, TRON is an original and visually stunning piece of science fiction that represents a landmark work in the history of computer animation.",
  "tomatoUserMeter": "69",
  "tomatoUserRating": "3.4",
  "tomatoUserReviews": "72086",
  "tomatoURL": "http://www.rottentomatoes.com/m/tron/",
  "DVD": "15 Jan 2002",
  "BoxOffice": "N/A",
  "Production": "Buena Vista Pictures",
  "Website": "N/A",
  "Response": "True"
}


text:
Date: 2012/02/01
Authors: [Duodezimalsystem](http://duodezimal.me)

---
---

<iframe src="http://player.vimeo.com/video/36272038?title=0&byline=0&portrait=0&badge=0&color=c9ff23" width="640" height="400" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

The world becomes smaller, moves closer and various cultures bump into one another. Is it possible that different cultural groups live peacefully next to each other?


text:
#include "act-activity-accum.h"

#include "act-activity.h"
#include "act-config.h"
#include "act-format.h"
#include "act-output-table.h"
#include "act-util.h"

#include <cmath>
#include <cfloat>

namespace act {

activity_accum::value_accum::value_accum(accum_field f)
: field(f),
  samples(0),
  sum(0),
  sum_sq(0),
  min(DBL_MAX),
  max(DBL_MIN)
{
}

void
activity_accum::value_accum::add(double x)
{
  samples++;
  sum += x;
  sum_sq += x*x;
  min = std::min(min, x);
  max = std::max(max, x);
}

double
activity_accum::value_accum::get_total() const
{
  return sum;
}

double
activity_accum::value_accum::get_mean() const
{
  return samples > 0 ? sum / samples : 0;
}

double
activity_accum::value_accum::get_sdev() const
{
  if (samples == 0)
    return 0;

  double recip = 1/samples;
  return sqrt(std::max(sum_sq * recip - (sum * recip) * (sum * recip), 0.));
}

double
activity_accum::value_accum::get_min() const
{
  return min;
}

double
activity_accum::value_accum::get_max() const
{
  return max;
}

bool
activity_accum::field_by_name(const char *name, accum_field &ret)
{
  field_id f_id = lookup_field_id(name);

  switch (f_id)
    {
    case field_id::distance:
      ret = accum_field::distance;
      return true;
    case field_id::duration:
      ret = accum_field::duration;
      return true;
    case field_id::speed:
    case field_id::pace:
      ret = accum_field::speed;
      return true;
    case field_id::max_speed:
    case field_id::max_pace:
      ret = accum_field::max_speed;
      return true;
    case field_id::avg_hr:
      ret = accum_field::avg_hr;
      return true;
    case field_id::max_hr:
      ret = accum_field::max_hr;
      return true;
    case field_id::resting_hr:
      ret = accum_field::resting_hr;
      return true;
    case field_id::avg_cadence:
      ret = accum_field::avg_cadence;
      return true;
    case field_id::max_cadence:
      ret = accum_field::max_cadence;
      return true;
    case field_id::avg_stance_time:
      ret = accum_field::avg_stance_time;
      return true;
    case field_id::avg_stance_ratio:
      ret = accum_field::avg_stance_ratio;
      return true;
    case field_id::avg_stride_length:
      ret = accum_field::avg_stride_length;
      return true;
    case field_id::avg_vertical_oscillation:
      ret = accum_field::avg_vertical_oscillation;
      return true;
    case field_id::calories:
      ret = accum_field::calories;
      return true;
    case field_id::training_effect:
      ret = accum_field::training_effect;
      return true;
    case field_id::weight:
      ret = accum_field::weight;
      return true;
    case field_id::effort:
      ret = accum_field::effort;
      return true;
    case field_id::quality:
      ret = accum_field::quality;
      return true;
    case field_id::points:
      ret = accum_field::points;
      return true;
    case field_id::temperature:
      ret = accum_field::temperature;
      return true;
    case field_id::dew_point:
      ret = accum_field::dew_point;
      return true;
    default:
      return false;
    }
}

std::vector<activity_accum::accum_field>
activity_accum::format_fields(const char *format)
{
  std::vector<accum_field> fields;

  if (format != nullptr)
    {
      while (*format != 0)
	{
	  if (const char *ptr = strchr(format, '%'))
	    {
	      ptr++;

	      if (ptr[0] == '@')
		ptr++;
	      if (ptr[0] == '-')
		ptr++;
	      while (isdigit(*ptr))
		ptr++;

	      switch (*ptr++)
		{
		case 'x':
		  if (ptr[0] != 0 && ptr[1] != 0)
		    ptr += 2;
		  break;

		case '{': {
		  const char *end = strchr(ptr, '}');
		  char token[128];
		  if (end && end - ptr < sizeof(token)-1)
		    {
		      memcpy(token, ptr, end - ptr);
		      token[end - ptr] = 0;

		      char *arg = strchr(token, ':');
		      if (arg)
			*arg++ = 0;

		      accum_field field;
		      if (field_by_name(token, field)
			  && std::find(fields.begin(), fields.end(),
				       field) == fields.end())
			{
			  fields.push_back(field);
			}
		    }
		  ptr = end ? end + 1 : ptr + strlen(ptr);
		  break; }
		}
	      format = ptr;
	    }
	}
    }

  return fields;
}

activity_accum::activity_accum(const std::vector<accum_field> &fields)
: _count(0)
{
  for (accum_field field : fields)
    _accum.push_back(value_accum(field));
}

void
activity_accum::add(const activity &a)
{
  _count++;

  for (auto &accum : _accum)
    {
      switch(accum.field)
	{
	case accum_field::distance:
	  if (double x = a.distance())
	    accum.add(x);
	  break;

	case accum_field::duration:
	  if (double x = a.duration())
	    accum.add(x);
	  break;

	case accum_field::speed:
	  if (double x = a.speed())
	    accum.add(x);
	  break;

	case accum_field::max_speed:
	  if (double x = a.max_speed())
	    accum.add(x);
	  break;

	case accum_field::avg_hr:
	  if (double x = a.avg_hr())
	    accum.add(x);
	  break;

	case accum_field::max_hr:
	  if (double x = a.max_hr())
	    accum.add(x);
	  break;

	case accum_field::resting_hr:
	  if (double x = a.resting_hr())
	    accum.add(x);
	  break;

	case accum_field::avg_cadence:
	  if (double x = a.avg_cadence())
	    accum.add(x);
	  break;

	case accum_field::max_cadence:
	  if (double x = a.max_cadence())
	    accum.add(x);
	  break;

	case accum_field::avg_stance_time:
	  if (double x = a.avg_stance_time())
	    accum.add(x);
	  break;

	case accum_field::avg_stance_ratio:
	  if (double x = a.avg_stance_ratio())
	    accum.add(x);
	  break;

	case accum_field::avg_vertical_oscillation:
	  if (double x = a.avg_vertical_oscillation())
	    accum.add(x);
	  break;

	case accum_field::avg_stride_length:
	  if (double x = a.avg_stride_length())
	    accum.add(x);
	  break;

	case accum_field::calories:
	  if (double x = a.calories())
	    accum.add(x);
	  break;

	case accum_field::training_effect:
	  if (double x = a.training_effect())
	    accum.add(x);
	  break;

	case accum_field::weight:
	  if (double x = a.weight())
	    accum.add(x);
	  break;

	case accum_field::effort:
	  if (double x = a.effort())
	    accum.add(x);
	  break;

	case accum_field::quality:
	  if (double x = a.quality())
	    accum.add(x);
	  break;

	case accum_field::points:
	  if (double x = a.points())
	    accum.add(x);
	  break;

	case accum_field::temperature:
	  if (double x = a.temperature())
	    accum.add(x);
	  break;

	case accum_field::dew_point:
	  if (double x = a.dew_point())
	    accum.add(x);
	  break;
	}
    }
}

void
activity_accum::printf(const char *format, const char *key) const
{
  while (*format != 0)
    {
      if (const char *ptr = strchr(format, '%'))
	{
	  if (ptr > format)
	    fwrite(format, 1, ptr - format, stdout);

	  ptr++;

	  bool left_relative = false;
	  if (ptr[0] == '-' && isdigit(ptr[1]))
	    left_relative = true, ptr++;

	  int field_width = 0;
	  while (isdigit(*ptr))
	    field_width = field_width * 10 + (*ptr++ - '0');

	  switch (*ptr++)
	    {
	    case 'n':
	      fputc('\n', stdout);
	      break;

	    case 't':
	      fputc('\t', stdout);
	      break;

	    case '%':
	      fputc('\n', stdout);
	      break;

	    case 'x':
	      if (ptr[0] != 0 && ptr[1] != 0)
		{
		  int c0 = convert_hexdigit(ptr[0]);
		  int c1 = convert_hexdigit(ptr[1]);
		  fputc((c0 << 4) | c1, stdout);
		}
	      break;

	    case '{': {
	      const char *end = strchr(ptr, '}');
	      char token[128];
	      if (end && end - ptr < sizeof(token)-1)
		{
		  memcpy(token, ptr, end - ptr);
		  token[end - ptr] = 0;

		  char *arg = strchr(token, ':');
		  if (arg)
		    *arg++ = 0;

		  print_expansion(token, arg, key, !left_relative
				  ? field_width : -field_width);
		}
	      ptr = end ? end + 1 : ptr + strlen(ptr);
	      break; }
	    }
	  format = ptr;
	}
      else
	{
	  fputs(format, stdout);
	  break;
	}
    }
}

bool
activity_accum::get_field_value(const char *name, const char *arg,
				field_data_type &type, double &value) const
{
  accum_field field;
  if (!field_by_name(name, field))
    return false;

  if (arg == nullptr)
    {
      switch (field)
	{
	case accum_field::calories:
	case accum_field::distance:
	case accum_field::duration:
	case accum_field::points:
	  arg = "total";
	  break;
	case accum_field::avg_cadence:
	case accum_field::avg_hr:
	case accum_field::avg_stance_ratio:
	case accum_field::avg_stance_time:
	case accum_field::avg_stride_length:
	case accum_field::avg_vertical_oscillation:
	case accum_field::dew_point:
	case accum_field::effort:
	case accum_field::quality:
	case accum_field::speed:
	case accum_field::temperature:
	case accum_field::training_effect:
	case accum_field::weight:
	  arg = "average";
	  break;
	case accum_field::max_cadence:
	case accum_field::max_hr:
	case accum_field::max_speed:
	  arg = "max";
	  break;
	case accum_field::resting_hr:
	  arg = "min";
	  break;
	}
    }

  const value_accum *accum = nullptr;
  for (const auto &a : _accum)
    {
      if (a.field == field)
	{
	  accum = &a;
	  break;
	}
    }

  if (accum == nullptr || arg == nullptr)
    return false;

  value = 0;
  if (strcasecmp(arg, "total") == 0 || strcasecmp(arg, "sum") == 0)
    value = accum->get_total();
  else if (strcasecmp(arg, "average") == 0 || strcasecmp(arg, "mean") == 0)
    value = accum->get_mean();
  else if (strcasecmp(arg, "sd") == 0 || strcasecmp(arg, "sdev") == 0)
    value = accum->get_sdev();
  else if (strcasecmp(arg, "min") == 0 || strcasecmp(arg, "minimum") == 0)
    value = accum->get_min();
  else if (strcasecmp(arg, "max") == 0 || strcasecmp(arg, "maximum") == 0)
    value = accum->get_max();
  else
    return false;

  type = lookup_field_data_type(lookup_field_id(name));

  return true;
}

void
activity_accum::print_expansion(const char *name, const char *arg,
				const char *key, int field_width) const
{
  if (strcasecmp(name, "count") == 0)
    {
      fprintf(stdout, "%*d", field_width, _count);
    }
  else if (strcasecmp(name, "key") == 0)
    {
      fprintf(stdout, "%*s", field_width, key);
    }
  else
    {
      field_data_type type;
      double value;

      if (!get_field_value(name, arg, type, value))
	return;

      std::string str;

      switch (type)
	{
	case field_data_type::string:
	case field_data_type::date:
	case field_data_type::keywords:
	  return;

	  /* FIXME: add a way to specify custom unit conversions,
	     precision specifiers, etc. */

	case field_data_type::duration:
	case field_data_type::number:
	case field_data_type::distance:
	case field_data_type::pace:
	case field_data_type::speed:
	case field_data_type::temperature:
	case field_data_type::fraction:
	case field_data_type::weight:
	case field_data_type::heart_rate:
	case field_data_type::cadence:
	case field_data_type::efficiency:
	  format_value(str, type, value, unit_type::unknown);
	  break;
	}

      if (str.size() != 0)
	{
	  if (field_width == 0)
	    fwrite(str.c_str(), 1, str.size(), stdout);
	  else
	    fprintf(stdout, "%*s", field_width, str.c_str());
	}
    }
}

void
activity_accum::print_row(output_table &out, const char *format,
			  const char *key) const
{
  while (*format != 0)
    {
      if (const char *ptr = strchr(format, '%'))
	{
	  ptr++;

	  bool left_relative = false;
	  bool bar_value = false;

	  if (ptr[0] == '@')
	    bar_value = true, left_relative = true, ptr++;

	  if (ptr[0] == '-')
	    left_relative = !left_relative, ptr++;

	  int field_width = 0;
	  while (isdigit(*ptr))
	    field_width = field_width * 10 + (*ptr++ - '0');

	  if (left_relative)
	    {
	      field_width = std::max(field_width, 1);
	      field_width = -field_width;
	    }

	  switch (*ptr++)
	    {
	    case '{': {
	      const char *end = strchr(ptr, '}');
	      char token[128];
	      if (end && end - ptr < sizeof(token)-1)
		{
		  memcpy(token, ptr, end - ptr);
		  token[end - ptr] = 0;

		  char *arg = strchr(token, ':');
		  if (arg)
		    *arg++ = 0;

		  if (strcasecmp(token, "count") == 0)
		    {
		      if (!bar_value)
			{
			  out.output_value(field_width, field_data_type::number,
					   _count, unit_type::unknown);
			}
		      else
			{
			  out.output_bar_value(field_width, _count);
			}
		    }
		  else if (strcasecmp(token, "key") == 0)
		    {
		      out.output_string(field_width, key);
		    }
		  else
		    {
		      field_data_type type;
		      double value;

		      if (!get_field_value(token, arg, type, value))
			return;

		      if (!bar_value)
			{
			  out.output_value(field_width, type,
					   value, unit_type::unknown);
			}
		      else
			{
			  out.output_bar_value(field_width, value);
			}
		    }
		}
	      ptr = end ? end + 1 : ptr + strlen(ptr);
	      break; }
	    }
	  format = ptr;
	}
      else
	{
	  fputs(format, stdout);
	  break;
	}
    }
}

} // namespace act


text:
FROM ubuntu:14.04
MAINTAINER anonim@no.ne

RUN apt-get update -y && apt-get upgrade -y
RUN apt-get install -y apt-transport-https
# Add the repository to your APT sources
RUN echo deb https://get.docker.com/ubuntu docker main > /etc/apt/sources.list.d/docker.list
# Then import the repository key
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9

# Let's start with some basic stuff.
RUN apt-get update -qq && apt-get install -qqy \
    ca-certificates \
    curl \
    vim \
    telnet \
    lxc-docker \
    iptables \
    supervisor \
    default-jre \
    jq

RUN echo 'DOCKER_OPTS="-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock"' > /etc/default/docker
EXPOSE 4243

#VOLUME /var/log/supervisor

# Install Jenkins Swarm agent
ENV HOME /home/jenkins-agent
RUN useradd -c "Jenkins agent" -d $HOME -m jenkins-agent
RUN usermod -aG docker jenkins-agent
RUN curl --create-dirs -sSLo \
    /usr/share/jenkins/swarm-client-jar-with-dependencies.jar \
    http://maven.jenkins-ci.org/content/repositories/releases/org/jenkins-ci/plugins/swarm-client/2.0/swarm-client-2.0-jar-with-dependencies.jar \
    && chmod 755 /usr/share/jenkins

# Install gcloud
ENV CLOUDSDK_PYTHON_SITEPACKAGES 1
RUN apt-get install -y -qq --no-install-recommends wget unzip python openjdk-7-jre-headless openssh-client python-openssl \
  && cd /home/jenkins-agent \
  && wget https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.zip && unzip google-cloud-sdk.zip && rm google-cloud-sdk.zip \
  && google-cloud-sdk/install.sh --usage-reporting=true --path-update=true --bash-completion=true --rc-path=/.bashrc --disable-installation-options \
  && google-cloud-sdk/bin/gcloud --quiet components update pkg-go pkg-python pkg-java preview app \
  && google-cloud-sdk/bin/gcloud --quiet config set component_manager/disable_update_check true \
  && chown -R jenkins-agent /home/jenkins-agent/.config \
  && chown -R jenkins-agent google-cloud-sdk
ENV PATH /home/jenkins-agent/google-cloud-sdk/bin:$PATH

# Install docker-compose form source (until 1.5 is released)
RUN apt-get install -y -qq --no-install-recommends python-dev libxml2-dev libxslt-dev
RUN curl https://bootstrap.pypa.io/ez_setup.py -o - | python
RUN cd /tmp && git clone https://github.com/therealjessesanford/compose.git && cd compose && python setup.py install && cd .. && rm -rf compose

# cleanup
RUN apt-get clean
RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Run Docker and Swarm processe with supervisord
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY jenkins-docker-supervisor.sh /usr/local/bin/jenkins-docker-supervisor.sh
ENTRYPOINT ["/usr/local/bin/jenkins-docker-supervisor.sh"]


text:
#ifndef _MATH_PERM_COMB_CPP_
#define _MATH_PERM_COMB_CPP_

#include <iostream>          /* std::cout                    */
#include <iomanip>           /* std::setw                    */
#include <cmath>             /* pow                          */
#include <cassert>           /* assert                       */
#include <algorithm>         /* std::max                     */

/* To generate permutations (lexicographic/heap) refer to    *
 * https://github.com/prashrock/C/blob/master/math/math_permute.h */

/* Calculate #ways to chose k elements from n posibilities   *
 * #ways = nCk   = n!/(r!(n-r)!)                             *
 * @param n      - Number of elements                        *
 * @param k      - Number of choices                         *
 * @param result - nCk value (or zero upon error/overflow)   *
 * Time Complexity = O(k-1)                                  */
template<typename Tret=unsigned, typename T=unsigned>
bool nCk(T n, T k, Tret &result)
{
	if(k > n)  return false;      /* Spl case - Invalid args */
	k = std::min(k, n-k);         /* nCk = nC(n-k)           */
	/* Handle all special cases where we can avoid the loop  */
	if(k == 0)        result = 1; /* nC0 = 1                 */
	else if(k == 1)   result = n; /* nC1 = n                 */
	else              result = n; /* Start with the last #   */

	/* The below for-loop will not be executed for special   *
	 * cases above (k == 0 or 1). For all else, it does      *
	 * result = n!/k!(n-k)! = n*(n-1)*(n-2)*..*(n-k+1)/k!    */
	for(T i = 2; i <= k; ++i)
	{
		Tret overflow_chk = result; /* Handle overflow cases */
		result *= (n - i + 1);   /* Iterative numerator calc */
		result /= i;           /* Iterative denominator calc */
		/* Combination should always grow unless overflow    */
		if(overflow_chk >= result) {
			result = 0;
			return false;
		}
	}
	return true;
}

/* Wrapper to call and use value of nCk directly             */
template<typename Tret=unsigned, typename T=unsigned>
Tret nCk(T n, T k)
{
	Tret result = 0;
	if(nCk(n, k, result)) return result;
	else                  return 0;
}

#endif //_MATH_PERM_COMB_CPP_


text:
Sponsored By

The most accurate speech-to-text API. Built for Python developers.


text:
"""
FILE: podcast.vim
AUTHOR: koturn <jeak.koutan.apple@gmail.com>
DESCRIPTION: {{{
Podcast player for Vim.
This file is a extension for denite.nvim and provides denite-source.
denite.nvim: https://github.com/Shougo/denite.nvim
}}}
"""

from .base import Base

class Source(Base):
    def __init__(self, vim):
        super().__init__(vim)
        self.name = 'podcast'
        self.kind = 'podcast'

    def gather_candidates(self, context):
        names = self.vim.call('podcast#get_channel_names') if len(context['args']) == 0 else context['args']
        candidates = []
        for name in names:
            items = self.vim.call('podcast#get_items', name)
            for item in items:
                item['word'] = item['title'] + ' [' + name + ']'
            candidates += items
        return candidates


text:
var moment = require("../moment-tokens.js")

exports.phpformat = {
    "test escape": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("\\Y"), "Y");
        test.done();
    },
    "test format n":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("n"), "M");
        test.done();
    },
    "test format Y and o": function(test) {
        test.expect(2);
        test.equal(moment().__translatePhpFormat("Y"), "YYYY");
        test.equal(moment().__translatePhpFormat("o"), "YYYY");
        test.done();
    },
    "test format y": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("y"), "YY");
        test.done();
    },
    "test format m":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("m"), "MM");
        test.done();
    },
    "test format M":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("M"), "MMM");
        test.done();
    },
    "test format d":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("d"), "DD");
        test.done();
    },
    "test format z":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("z"), "DDD");
        test.done();
    },
    "test format F":  function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("F"), "MMMM");
        test.done();
    },
    "test format W": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("W"), "ww");
        test.done();
    },
    "test format G": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("G"), "H");
        test.done();
    },
    "test format j": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("j"), "D");
        test.done();
    },
    "test format e": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("e"), "zz");
        test.done();
    },
    "test format a": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("a"), "a");
        test.done();
    },
    "test format A": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("A"), "A");
        test.done();
    },
    "test format w": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("w"), "d");
        test.done();
    },
    "test format l": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("l"), "dddd");
        test.done();
    },
    "test format D": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("D"), "ddd");
        test.done();
    },
    "test format H": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("H"), "HH");
        test.done();
    },
    "test format g": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("g"), "h");
        test.done();
    },
    "test format h": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("h"), "hh");
        test.done();
    },
    "test format i": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("i"), "mm");
        test.done();
    },
    "test format s": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("s"), "ss");
        test.done();
    },
    "test format O": function(test) {
        test.expect(1);
        test.equal(moment().__translatePhpFormat("O"), "ZZ");
        test.done();
    }
}


text:
using OpenQA.Selenium;

namespace Tranquire.Selenium.Questions.UIModels
{
    /// <summary>
    /// Indicates the method for <see cref="By"/>
    /// </summary>
    public enum ByMethod
    {
        /// <summary>
        /// The <see cref="By.CssSelector(string)"/> method
        /// </summary>
        CssSelector,
        /// <summary>
        /// The <see cref="By.Id(string)"/> method
        /// </summary>
        Id,
        /// <summary>
        /// The <see cref="By.Name(string)"/> method
        /// </summary>
        Name,
        /// <summary>
        /// The <see cref="By.ClassName(string)"/> method
        /// </summary>
        ClassName,
        /// <summary>
        /// The <see cref="By.TagName(string)"/> method
        /// </summary>
        TagName,
        /// <summary>
        /// The <see cref="By.XPath(string)"/> method
        /// </summary>
        XPath,
        /// <summary>
        /// Use the container element
        /// </summary>
        Self
    }
}


text:
#include "stdafx.h"
// AI_Character.cpp

#include "Scene.h"
#include "Obj_Character.h"
#include "GameTable.h"
#include "PathFinder.h"
#include "AI_Character.h"

using namespace Combat_Module::Skill_Module;

#define RANDOM_TIME (2000)
#define RANDOM_DIST (15)

AI_Character::AI_Character( VOID )
{
    m_pCharacter = NULL;
    m_nIntervalTime = RANDOM_TIME;
    _state = g_StateList.InstanceState(ESTATE_IDLE);
}

AI_Character::~AI_Character( VOID )
{
}

BOOL AI_Character::Init( Obj_Character *pCharacter )
{
    m_pCharacter    = pCharacter;
    return TRUE;
}

VOID AI_Character::Term( VOID )
{
    m_pCharacter    = NULL;
}

// all interface of actions
ORESULT AI_Character::Obj_Move(const WORLD_POS* pTar)
{
    Obj_Character* pCharacter = GetCharacter();
    if (!pCharacter)
    {
        Assert(NULL && "AI_Character::MoveTo...pCharacter = NULL...");
        return OR_ERROR;
    }
    if (TRUE == pCharacter->IsLimitMove() )
    {
        return OR_LIMIT_MOVE;
    }
    if (pCharacter->IsDie())
    {
        return OR_DIE;
    }

    int numNode = 0;
    const WORLD_POS* pCur = pCharacter->getWorldPos();
    WORLD_POS posNode[MAX_CHAR_PATH_NODE_NUMBER];
    WORLD_POS posCur = *pCur;
    pCharacter->getScene()->GetMap()->VerifyPos( const_cast<WORLD_POS*>(pTar) );
    pCharacter->getScene()->GetMap()->GetPathFinder()->FindPath(&posCur,
                                const_cast<WORLD_POS*>(pTar), posNode, numNode, pCharacter->GetDriverLevel());

    if( numNode == 0 )
        return OR_ERROR;

    return _state->Obj_Move(this, -1, numNode, posNode );
}

ORESULT AI_Character::Obj_UseSkill(ObjID_t idSkill, BYTE nLevel, ObjID_t idTarget, FLOAT fTargetX, FLOAT fTargetZ, FLOAT fDir/* = -1.f*/, GUID_t guidTarget/*=INVALID_ID*/)
{
    __ENTER_FUNCTION
    return _state->Obj_UseSkill(this, idSkill, nLevel, idTarget, fTargetX, fTargetZ, fDir, guidTarget);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT AI_Character::Obj_UseItem(ID_t nBagIndex, ObjID_t nTargetObj, WORLD_POS const& posTarget, PET_GUID_t const& guidTargetPet, ID_t nTargetItem)
{
    __ENTER_FUNCTION
    return _state->Obj_UseItem(this, nBagIndex, nTargetObj, posTarget, guidTargetPet, nTargetItem);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT AI_Character::Jump(VOID)
{
    __ENTER_FUNCTION
    return _state->Jump(this);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT    AI_Character::Stop(VOID)
{
    __ENTER_FUNCTION
    return _state->Stop(this);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT    AI_Character::Stall(VOID)
{
    __ENTER_FUNCTION
    return _state->Stall(this);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT    AI_Character::UseAbility(VOID)
{
    __ENTER_FUNCTION
    return _state->UseAbility(this);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT    AI_Character::Move(const WORLD_POS* pTar)
{
    __ENTER_FUNCTION
    Obj_Character* pCharacter = GetCharacter();
    if (!pCharacter)
    {
        Assert(NULL && "AI_Character::MoveTo...pCharacter = NULL...");
        return OR_ERROR;
    }
    if (TRUE == pCharacter->IsLimitMove() )
    {
        return OR_LIMIT_MOVE;
    }

    int numNode = 0;
    const WORLD_POS* pCur = pCharacter->getWorldPos();
    WORLD_POS posNode[MAX_CHAR_PATH_NODE_NUMBER];
    WORLD_POS posCur = *pCur;
    pCharacter->getScene()->GetMap()->VerifyPos( const_cast<WORLD_POS*>(pTar) );
    if (FALSE == pCharacter->getScene()->GetMap()->IsCanGo(*pTar,pCharacter->GetDriverLevel()))
    {// 为不可走区域
        return OR_IMPASSABLE_ZONE;
    }
    pCharacter->getScene()->GetMap()->GetPathFinder()->FindPath(&posCur,
                                const_cast<WORLD_POS*>(pTar), posNode, numNode, pCharacter->GetDriverLevel());

    if( numNode == 0 )
        return OR_ERROR;

    WORD wNumNode = numNode;
    return Move( -1, wNumNode, posNode );
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT AI_Character::Move(INT nHandleID, WORD& wNumTargetPos, WORLD_POS *paTargetPos, BOOL bLine)
{
    __ENTER_FUNCTION
    Obj_Character* pCharacter = GetCharacter();
    if( !pCharacter )
    {
        Assert(NULL && "AI_Character::MoveTo...pCharacter = NULL...");
        return OR_ERROR;
    }
    if( pCharacter->IsLimitMove() )
    {
        return OR_LIMIT_MOVE;
    }
    WORD nNumPos = wNumTargetPos;
    const WORLD_POS* pCur = pCharacter->getWorldPos();
    WORLD_POS posCur = *pCur;
    if( pCharacter->getScene()->GetMap()->IsCanGo(posCur,pCharacter->GetDriverLevel()) )
    {
        INT numNode;
        WORLD_POS posNode[MAX_CHAR_PATH_NODE_NUMBER];
        WORD w = 0;
        for(w = 0; w < wNumTargetPos; w++ )
        {
            BOOL bFind = pCharacter->getScene()->GetMap()->GetPathFinder()->FindPath(&posCur,paTargetPos+w, posNode, numNode, pCharacter->GetDriverLevel(), bLine);

            if( bFind == FALSE ||numNode <= 0 )
                break;

            if( !(posNode[numNode-1] == *(paTargetPos+w)) )
            {
                posNode[numNode-1] = *(paTargetPos+w);
                break;
            }

            posCur = *(paTargetPos+w);
        }

        if( w == 0 ) //第一步就不能走
            return OR_ERROR;

        if( w < wNumTargetPos )//截短
            nNumPos = w;
    }
    ORESULT oResult = _state->Move(this, nHandleID, nNumPos, paTargetPos);
    if(OR_SUCCEEDED(oResult) && nNumPos != wNumTargetPos)
    {
        wNumTargetPos = nNumPos;
        return OR_CUT_PATHROUTE;
    }
    return oResult;

    //Obj_Character* pCharacter = GetCharacter();
    //if (!pCharacter)
    //{
    //    Assert(NULL && "AI_Character::MoveTo...pCharacter = NULL...");
    //    return OR_ERROR;
    //}
    //if (TRUE == pCharacter->IsLimitMove() )
    //{
    //    return OR_LIMIT_MOVE;
    //}

    //int numNode = 0;
    //const WORLD_POS* pCur = pCharacter->getWorldPos();
    //WORLD_POS posNode[MAX_CHAR_PATH_NODE_NUMBER];
    //WORLD_POS posCur = *pCur;
    //pCharacter->getScene()->GetMap()->VerifyPos(paTargetPos);
    //if( posCur == *paTargetPos )
    //{//起点终点一样
    //    return OR_ERROR;
    //}
    //if( pCharacter->getScene()->GetMap()->IsCanGo(posCur,pCharacter->GetDriverLevel()) )
    //{
    //    //if (FALSE == pCharacter->getScene()->GetMap()->IsCanGo(*paTargetPos))
    //    //{// 为不可走区域
    //    //    return OR_IMPASSABLE_ZONE;
    //    //}
    //    pCharacter->getScene()->GetMap()->GetPathFinder()->FindPath(&posCur,
    //        paTargetPos, posNode, numNode, pCharacter->GetDriverLevel(), bLine);

    //    if( numNode <= 0 )
    //        return OR_ERROR;

    //    if( numNode < wNumTargetPos )
    //    {//截短
    //        if( posNode[numNode-1] == posCur )
    //            return OR_ERROR;

    //        *paTargetPos = posNode[numNode-1];
    //        wNumTargetPos = numNode;
    //    }
    //}

    //return _state->Move(this, nHandleID, wNumTargetPos, paTargetPos);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT AI_Character::UseSkill(ObjID_t idSkill, BYTE nLevel, ObjID_t idTarget, FLOAT fTargetX, FLOAT fTargetZ, FLOAT fDir/* = -1.f*/, GUID_t guidTarget)
{
    __ENTER_FUNCTION
    return _state->UseSkill(this, idSkill, nLevel, idTarget, fTargetX, fTargetZ, fDir, guidTarget);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

ORESULT AI_Character::UseItem(ID_t nBagIndex, ObjID_t nTargetObj, WORLD_POS const& posTarget, PET_GUID_t const& guidTargetPet, ID_t nTargetItem)
{
    __ENTER_FUNCTION
    return _state->UseItem(this, nBagIndex, nTargetObj, posTarget, guidTargetPet, nTargetItem);
    __LEAVE_FUNCTION
    return OR_ERROR;
}

// common logic
VOID    AI_Character::AI_Logic_Terror(UINT uTime)
{
    __ENTER_FUNCTION
    Obj_Character* pCharacter = GetCharacter();
    if (!pCharacter) {
        return ;
    }

    //if (!_state->IsTerrorState(this) ) {
    //    Stop();
    //    ChangeState(ESTATE_IDLE);
    //}

    if (RANDOM_TIME == m_nIntervalTime || m_nIntervalTime <= 0) {
        FLOAT fLen = (FLOAT)(rand() % RANDOM_DIST);
        WORLD_POS pos = GetRandPosOfCircle(pCharacter->getWorldPos(), fLen);

        Obj_Move(&pos);
        m_nIntervalTime = rand() % RANDOM_TIME;

        return ;
    }

    m_nIntervalTime -= pCharacter->GetLogicTime();
    //if (pCharacter->IsMoving() ) {
    //    return ;
    //}

    __LEAVE_FUNCTION
}

// event interface.
VOID AI_Character::OnDie(Obj *pKiller/* = NULL*/)
{
    __ENTER_FUNCTION
    _state->OnDie(this, pKiller);
    __LEAVE_FUNCTION
}

VOID AI_Character::OnRelive(Obj *pKiller/* = NULL*/)
{
}

VOID AI_Character::OnDamage(INT nDamage, Obj_Character* pAttacker)
{
    __ENTER_FUNCTION
    _state->OnDamage(this, nDamage, pAttacker);
    __LEAVE_FUNCTION
}

VOID AI_Character::OnBeSkill(Obj_Character* pCharacter, INT nGoodEffect)
{
    __ENTER_FUNCTION
    _state->OnBeSkill(this, pCharacter, nGoodEffect);
    __LEAVE_FUNCTION
}

WORLD_POS AI_Character::GetRandPosOfCircle( const WORLD_POS* pPos,FLOAT fRadio )
{/** 生成以pPos为圆心,fRadio为半径的圆周上的随机一点 */
    WORLD_POS Tar;
__ENTER_FUNCTION
    /** 假设半径为10的圆 */
    FLOAT Vx = (FLOAT)(rand() % 11) ;
    INT nDir = rand() % 2 ;
    if ( !nDir )
        Vx = -Vx ;

    FLOAT    Vz = (FLOAT)sqrt( 100 - Vx*Vx );
    nDir = rand() % 2 ;
    if ( !nDir )
        Vz = - Vz ;

    Tar.m_fX = pPos->m_fX + (Vx/10)*fRadio;
    Tar.m_fZ = pPos->m_fZ + (Vz/10)*fRadio;
__LEAVE_FUNCTION
    return Tar;
}


text:
package org.apache.lucene.search;

import java.util.List;

import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.English;
import org.apache.lucene.util.LuceneTestCase;

public class TestSpanQueryFilter extends LuceneTestCase {

  public void testFilterWorks() throws Exception {
    Directory dir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random, dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
    for (int i = 0; i < 500; i++) {
      Document document = new Document();
      document.add(newField("field", English.intToEnglish(i) + " equals " + English.intToEnglish(i),
              Field.Store.NO, Field.Index.ANALYZED));
      writer.addDocument(document);
    }
    IndexReader reader = writer.getReader();
    writer.close();

    SpanTermQuery query = new SpanTermQuery(new Term("field", English.intToEnglish(10).trim()));
    SpanQueryFilter filter = new SpanQueryFilter(query);
    SpanFilterResult result = filter.bitSpans(reader);
    DocIdSet docIdSet = result.getDocIdSet();
    assertTrue("docIdSet is null and it shouldn't be", docIdSet != null);
    assertContainsDocId("docIdSet doesn't contain docId 10", docIdSet, 10);
    List<SpanFilterResult.PositionInfo> spans = result.getPositions();
    assertTrue("spans is null and it shouldn't be", spans != null);
    int size = getDocIdSetSize(docIdSet);
    assertTrue("spans Size: " + spans.size() + " is not: " + size, spans.size() == size);
    for (final SpanFilterResult.PositionInfo info: spans) {
      assertTrue("info is null and it shouldn't be", info != null);
      //The doc should indicate the bit is on
      assertContainsDocId("docIdSet doesn't contain docId " + info.getDoc(), docIdSet, info.getDoc());
      //There should be two positions in each
      assertTrue("info.getPositions() Size: " + info.getPositions().size() + " is not: " + 2, info.getPositions().size() == 2);
    }
    reader.close();
    dir.close();
  }

  int getDocIdSetSize(DocIdSet docIdSet) throws Exception {
    int size = 0;
    DocIdSetIterator it = docIdSet.iterator();
    while (it.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
      size++;
    }
    return size;
  }

  public void assertContainsDocId(String msg, DocIdSet docIdSet, int docId) throws Exception {
    DocIdSetIterator it = docIdSet.iterator();
    assertTrue(msg, it.advance(docId) != DocIdSetIterator.NO_MORE_DOCS);
    assertTrue(msg, it.docID() == docId);
  }
}


text:
module Azure::SQL::Mgmt::V2017_10_01_preview
  module Models
    #
    # A vulnerability assessment scan record.
    #
    class VulnerabilityAssessmentScanRecord < ProxyResource

      include MsRestAzure

      # @return [String] The scan ID.
      attr_accessor :scan_id

      # @return [VulnerabilityAssessmentScanTriggerType] The scan trigger type.
      # Possible values include: 'OnDemand', 'Recurring'
      attr_accessor :trigger_type

      # @return [VulnerabilityAssessmentScanState] The scan status. Possible
      # values include: 'Passed', 'Failed', 'FailedToRun', 'InProgress'
      attr_accessor :state

      # @return [DateTime] The scan start time (UTC).
      attr_accessor :start_time

      # @return [DateTime] The scan end time (UTC).
      attr_accessor :end_time

      # @return [Array<VulnerabilityAssessmentScanError>] The scan errors.
      attr_accessor :errors

      # @return [String] The scan results storage container path.
      attr_accessor :storage_container_path

      # @return [Integer] The number of failed security checks.
      attr_accessor :number_of_failed_security_checks

      #
      # Mapper for VulnerabilityAssessmentScanRecord class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'VulnerabilityAssessmentScanRecord',
          type: {
            name: 'Composite',
            class_name: 'VulnerabilityAssessmentScanRecord',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              scan_id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.scanId',
                type: {
                  name: 'String'
                }
              },
              trigger_type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.triggerType',
                type: {
                  name: 'String'
                }
              },
              state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.state',
                type: {
                  name: 'String'
                }
              },
              start_time: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.startTime',
                type: {
                  name: 'DateTime'
                }
              },
              end_time: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.endTime',
                type: {
                  name: 'DateTime'
                }
              },
              errors: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.errors',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'VulnerabilityAssessmentScanErrorElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'VulnerabilityAssessmentScanError'
                      }
                  }
                }
              },
              storage_container_path: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.storageContainerPath',
                type: {
                  name: 'String'
                }
              },
              number_of_failed_security_checks: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.numberOfFailedSecurityChecks',
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
Synoptico is a small desktop application that can aggregate multiple websites.
The goal of the project is mainly to get familiar with Elm, Electron and Bacon.js, how they can be
used together and to learn more about functional programming techniques in general. Feedback is very
welcome.

# Usage

1. Create a `json` file describing the URLs to aggregate. The [releases](https://github.com/friegger/synoptico/releases) reference a `sample.json` file with
   the required format.

2. Open the file via the `Open File...` menu entry or just drag it onto the app window.

# Development

## How to run locally

It has been tested with Node.js 6+.

```
$ npm install
$ npm run elm #-> compiles the Elm code
$ npm start
```

## How to run the tests

```
$ npm install #-> only required once
$ npm test #-> executes the JS and the Elm tests
```

## Building

```
$ cd app
$ npm install
$ cd ..
$ npm run package-linux
$ npm run package-darwin
$ npm run package-windows
```


text:
/*
 * ProjectEuler/src/c/Problem265.c
 *
 * Binary Circles
 * ==============
 * Published on Saturday, 21st November 2009, 09:00 am
 *
 * 2N binary digits can be placed in a circle so that all the N-digit clockwise
 * subsequences are distinct. For N=3, two such circular arrangements are
 * possible, ignoring rotations:  For the first arrangement, the 3-digit
 * subsequences, in clockwise order, are: 000, 001, 010, 101, 011, 111, 110 and
 * 100. Each circular arrangement can be encoded as a number by concatenating
 * the binary digits starting with the subsequence of all zeros as the most
 * significant bits and proceeding clockwise. The two arrangements for N=3 are
 * thus represented as 23 and 29:  00010111 2 = 23 00011101 2 = 29 Calling S(N)
 * the sum of the unique numeric representations, we can see that S(3) = 23 + 29
 * = 52. Find S(5).
 */

#include <stdio.h>
#include "ProjectEuler/ProjectEuler.h"
#include "ProjectEuler/Problem265.h"

int main(int argc, char** argv) {

    return 0;
}


text:
int checkArguments(int argc, char **argv, char **move, int *boardSize, int *transformations, char *functionName) {
	// No of arg check
	if (argc != 4) {
		fprintf(stderr, "%s: there should be three arguments\n", *functionName);
		return EXIT_FAILURE;
	}
	// Board size check
	char *boardSizeString = *(argv+2);
	*boardSize = atoi(boardSizeString);
	if (*boardSize < 2 || *boardSize > 25 || *boardSize%2 == 0) {
		fprintf(stderr, "%s: invalid board size argument: %s\n", *functionName, boardSizeString);
		return EXIT_FAILURE;
	}
	// Move check
	*move = *(argv+1);
	//printf("1 %s\n", *(argv+1)); OK
	if (strlen(*move) != 2 || coordinateNotInRange(*move, *boardSize) || coordinateNotInRange(*move+1, *boardSize) ) {
		fprintf(stderr, "%s: invalid move argument: %c\n", *functionName, *move);
		return EXIT_FAILURE;
	}
	// Transformations check
	char *transformationsString = *(argv+3);
	*transformations = atoi(transformationsString);
	if (*transformations < 0) {
		fprintf(stderr, "%s: invalid transformations argument: %s\n", *functionName, transformationsString);
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

int coordinateNotInRange(char *c, int boardSize) {
	return *c < 97 || *c > 97 + boardSize-1;
}


text:
package org.vaadin.sebastian.indeterminatecheckbox.testcomponents;

import org.vaadin.sebastian.indeterminatecheckbox.IndeterminateCheckBox;

import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.server.ExternalResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Notification;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class BasicTestsLayout extends VerticalLayout {

    private static final String ICON_URL = "https://dev.vaadin.com/svn/integration/eclipse/plugins/com.vaadin.integration.eclipse/icons/vaadin-icon-16.png";

    public BasicTestsLayout() {
        createComponents();
    }

    private void createComponents() {
        CheckBox basicBox = new CheckBox("Normal checkbox");
        basicBox.setIcon(new ExternalResource(ICON_URL));
        addComponent(basicBox);

        IndeterminateCheckBox box = new IndeterminateCheckBox(
                "Disabled Indeterminate Box set to True", true);
        box.setEnabled(false);
        addComponent(box);

        box = new IndeterminateCheckBox("Indeterminate Box set to False",
                false);
        addComponent(box);

        final IndeterminateCheckBox indeterminatBox = new IndeterminateCheckBox(
                "Indeterminate Box set to Indeterminate", null);
        addComponent(indeterminatBox);

        final IndeterminateCheckBox nextStateBox = new IndeterminateCheckBox(
                "Toggle Next State Box", null);
        addComponent(nextStateBox);

        final Button setNextValue = new Button();
        setNextValue.setCaption("Set next state");
        setNextValue.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                Boolean value = false;
                if (nextStateBox.getValue() == null) {
                    value = true;
                } else if (!nextStateBox.getValue()) {
                    value = null;
                }

                nextStateBox.setValue(value);
            }
        });
        addComponent(setNextValue);

        box = new IndeterminateCheckBox("Icon box");
        box.setUserCanToggleIndeterminate(true);
        box.setIcon(new ExternalResource(ICON_URL));
        addComponent(box);

        box = new IndeterminateCheckBox("Error box");
        box.setUserCanToggleIndeterminate(true);
        addComponent(box);

        final IndeterminateCheckBox togglebox = new IndeterminateCheckBox(
                "Toggle box");
        togglebox.setUserCanToggleIndeterminate(true);
        togglebox.addValueChangeListener(new ValueChangeListener() {

            @Override
            public void valueChange(ValueChangeEvent event) {
                Notification.show("Value of box : " + togglebox.getValue());
            }
        });
        addComponent(togglebox);

        final Button toggle = new Button();
        toggle.setCaption(
                "User toggle : " + togglebox.isUserCanToggleIndetermine());
        toggle.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                togglebox.setUserCanToggleIndeterminate(
                        !togglebox.isUserCanToggleIndetermine());
                toggle.setCaption("User toggle : "
                        + togglebox.isUserCanToggleIndetermine());
            }
        });
        addComponent(toggle);

    }

}