text:
#include "AConfig.h"
#if(HAS_MS5803_XXBA)

#include "Device.h"
#include "MS5803_XXBA.h"
#include "Settings.h"
#include "Timer.h"
#include <Wire.h>
#include "MS5803_XXBALib.h"

/*
Library for MS5803 14 and 30 bar sensors on OpenROV.

Author: brian@openrov.com
Based on works by Walt Holm and Luke Miller
*/

const int DevAddress = MS5803_XXBA_I2C_ADDRESS;  // 7-bit I2C address of the MS5803

// Here are the commands that can be sent to the 5803
// Page 6 of the data sheet
const byte Reset = 0x1E;
const byte D1_256 = 0x40;
const byte D1_512 = 0x42;
const byte D1_1024 = 0x44;
const byte D1_2048 = 0x46;
const byte D1_4096 = 0x48;
const byte D2_256 = 0x50;
const byte D2_512 = 0x52;
const byte D2_1024 = 0x54;
const byte D2_2048 = 0x56;
const byte D2_4096 = 0x58;
const byte AdcRead = 0x00;
const byte PromBaseAddress = 0xA0;
const bool FreshWater = 0;
const bool SaltWater = 1;
//io_timeout is the max wait time in ms for I2C requests to complete
const int io_timeout = 20;

unsigned int CalConstant[8];  // Matrix for holding calibration constants

long AdcTemperature, AdcPressure;  // Holds raw ADC data for temperature and pressure
float Temperature, Pressure, TempDifference, Offset, Sensitivity;
float T2, Off2, Sens2;  // Offsets for second-order temperature computation
float AtmosPressure = 1015;
float Depth;
float DepthOffset = 0;
float WaterDensity = 1.019716;
Timer DepthSensorSamples;
byte ByteHigh, ByteMiddle, ByteLow;  // Variables for I2C reads
bool WaterType = FreshWater;
static bool MS5803_inialized = false;

// Program initialization starts here

void sendCommand(byte command){
  Wire.beginTransmission(DevAddress);
  Wire.write(command);
  Wire.endTransmission();
}

void MS5803_XXBA::device_setup(){
  DepthSensorSamples.reset();
  Wire.beginTransmission(MS5803_XXBA_I2C_ADDRESS);
  if (Wire.endTransmission() != 0)
    return; //Cannot find I2c device, abort setup

  Settings::capability_bitarray |= (1 << DEPTH_CAPABLE);

  Serial.println("log:Depth Sensor setup;");
  Wire.begin();
  Serial.println("MS5803.status: initialized I2C;");
  delay(10);
  unsigned int cal;
  // Reset the device and check for device presence

  sendCommand(Reset);
  delay(10);
  Serial.println("MS5803.status: reset;");

  // Get the calibration constants and store in array

  for (byte i = 0; i < 8; i++)
  {
    sendCommand(PromBaseAddress + (2*i));
    Wire.requestFrom(DevAddress, 2);
    while(Wire.available()){
      ByteHigh = Wire.read();
      ByteLow = Wire.read();
    }
    CalConstant[i] = (((unsigned int)ByteHigh << 8) + ByteLow);
  }

  Serial.println("Depth: Calibration constants are:");

  for (byte i=0; i < 8; i++)
  {
    cal = CalConstant[i];
    Serial.print("Depth.C");Serial.print(i);Serial.print(":");Serial.print(cal);Serial.println(";");
    //log(CalConstant[i]);
  }

  MS5803_inialized = true;

}

void MS5803_XXBA::device_loop(Command command){
  if (!MS5803_inialized){
    if (DepthSensorSamples.elapsed(30000)){
      device_setup();
    }
    return;
  }

  if (command.cmp("dzer")){
    DepthOffset=Depth;
  }
  else if (command.cmp("dtwa")){
    if (Settings::water_type == FreshWater) {
      Settings::water_type = SaltWater;
      Serial.println(F("dtwa:1;"));
    } else {
      Settings::water_type =  FreshWater;
      Serial.println(F("dtwa:0;"));
    }
  }

  if (DepthSensorSamples.elapsed(1000)){
  // Read the Device for the ADC Temperature and Pressure values

  sendCommand(D1_512);
  delay(10);
  sendCommand(AdcRead);
  Wire.requestFrom(DevAddress, 3);

  unsigned int millis_start = millis();
  while (Wire.available() < 3) {
    if (io_timeout > 0 && ((unsigned int)millis() - millis_start) > io_timeout) {
      Serial.println("log:Failed to read Depth from I2C");
      return;
    }
  }
  ByteHigh = Wire.read();
  ByteMiddle = Wire.read();
  ByteLow = Wire.read();

  AdcPressure = ((long)ByteHigh << 16) + ((long)ByteMiddle << 8) + (long)ByteLow;

//  log("D1 is: ");
//  log(AdcPressure);

  sendCommand(D2_512);
  delay(10);
  sendCommand(AdcRead);
  Wire.requestFrom(DevAddress, 3);

  millis_start = millis();
  while (Wire.available() < 3) {
    if (io_timeout > 0 && ((unsigned int)millis() - millis_start) > io_timeout) {
      Serial.println("log:Failed to read Depth from I2C");
      return;
    }
  }
  ByteHigh = Wire.read();
  ByteMiddle = Wire.read();
  ByteLow = Wire.read();

  AdcTemperature = ((long)ByteHigh << 16) + ((long)ByteMiddle << 8) + (long)ByteLow;
 // log("D2 is: ");
//  log(AdcTemperature);

  envdata::TEMP = CorrectedTemperature(AdcTemperature, CalConstant);

  Pressure = TemperatureCorrectedPressure(AdcPressure, AdcTemperature, CalConstant);

  envdata::PRES = Pressure;

  // Convert to psig and display
  //
  //Pressure = Pressure - 1.015;  // Convert to gauge pressure (subtract atmospheric pressure)
  //Pressure = Pressure * 14.50377;  // Convert bars to psi
  //log("Pressure in psi is: ");
  //log(Pressure);

  if (Settings::water_type == FreshWater){
    //FreshWater
    Depth = (Pressure - AtmosPressure) * WaterDensity / 100;
  } else {
    // Salt Water
    // See Seabird App Note #69 for details
    // 9.72659 / 9.780318 = 0.9945

    Depth = (Pressure - AtmosPressure) * 0.9945 / 100;

  }
  navdata::DEEP = Depth-DepthOffset;

  }
}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="100" />
    <translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="200"/>
</set>

redpajama_set_name: RedPajamaGithub


text:
"""Unit test for RemoteValueScaling objects."""
from xknx import XKNX
from xknx.remote_value import RemoteValueScaling

class TestRemoteValueScaling:
    """Test class for RemoteValueScaling objects."""

    def test_calc_0_10(self):
        """Test if from/to calculations work with small range."""
        assert RemoteValueScaling._calc_to_knx(0, 10, 0) == 0
        assert RemoteValueScaling._calc_to_knx(0, 10, 1) == 26
        assert RemoteValueScaling._calc_to_knx(0, 10, 9) == 230
        assert RemoteValueScaling._calc_to_knx(0, 10, 10) == 255

        assert RemoteValueScaling._calc_from_knx(0, 10, 0) == 0
        assert RemoteValueScaling._calc_from_knx(0, 10, 1) == 0
        assert RemoteValueScaling._calc_from_knx(0, 10, 12) == 0
        assert RemoteValueScaling._calc_from_knx(0, 10, 13) == 1
        assert RemoteValueScaling._calc_from_knx(0, 10, 254) == 10
        assert RemoteValueScaling._calc_from_knx(0, 10, 255) == 10

    def test_calc_0_100(self):
        """Test if from/to calculations work range 0-100 with many test cases."""
        assert RemoteValueScaling._calc_to_knx(0, 100, 0) == 0
        assert RemoteValueScaling._calc_to_knx(0, 100, 1) == 3
        assert RemoteValueScaling._calc_to_knx(0, 100, 2) == 5
        assert RemoteValueScaling._calc_to_knx(0, 100, 3) == 8
        assert RemoteValueScaling._calc_to_knx(0, 100, 30) == 76
        assert RemoteValueScaling._calc_to_knx(0, 100, 50) == 128
        assert RemoteValueScaling._calc_to_knx(0, 100, 70) == 178
        assert RemoteValueScaling._calc_to_knx(0, 100, 97) == 247
        assert RemoteValueScaling._calc_to_knx(0, 100, 98) == 250
        assert RemoteValueScaling._calc_to_knx(0, 100, 99) == 252
        assert RemoteValueScaling._calc_to_knx(0, 100, 100) == 255

        assert RemoteValueScaling._calc_from_knx(0, 100, 0) == 0
        assert RemoteValueScaling._calc_from_knx(0, 100, 1) == 0
        assert RemoteValueScaling._calc_from_knx(0, 100, 2) == 1
        assert RemoteValueScaling._calc_from_knx(0, 100, 3) == 1
        assert RemoteValueScaling._calc_from_knx(0, 100, 4) == 2
        assert RemoteValueScaling._calc_from_knx(0, 100, 5) == 2
        assert RemoteValueScaling._calc_from_knx(0, 100, 76) == 30
        assert RemoteValueScaling._calc_from_knx(0, 100, 128) == 50
        assert RemoteValueScaling._calc_from_knx(0, 100, 178) == 70
        assert RemoteValueScaling._calc_from_knx(0, 100, 251) == 98
        assert RemoteValueScaling._calc_from_knx(0, 100, 252) == 99
        assert RemoteValueScaling._calc_from_knx(0, 100, 253) == 99
        assert RemoteValueScaling._calc_from_knx(0, 100, 254) == 100
        assert RemoteValueScaling._calc_from_knx(0, 100, 255) == 100

    def test_calc_0_1000(self):
        """Test if from/to calculations work with large range."""
        assert RemoteValueScaling._calc_to_knx(0, 1000, 0) == 0
        assert RemoteValueScaling._calc_to_knx(0, 1000, 1) == 0
        assert RemoteValueScaling._calc_to_knx(0, 1000, 2) == 1
        assert RemoteValueScaling._calc_to_knx(0, 1000, 3) == 1
        assert RemoteValueScaling._calc_to_knx(0, 1000, 500) == 128
        assert RemoteValueScaling._calc_to_knx(0, 1000, 997) == 254
        assert RemoteValueScaling._calc_to_knx(0, 1000, 998) == 254
        assert RemoteValueScaling._calc_to_knx(0, 1000, 999) == 255
        assert RemoteValueScaling._calc_to_knx(0, 1000, 1000) == 255

        assert RemoteValueScaling._calc_from_knx(0, 1000, 0) == 0
        assert RemoteValueScaling._calc_from_knx(0, 1000, 1) == 4
        assert RemoteValueScaling._calc_from_knx(0, 1000, 2) == 8
        assert RemoteValueScaling._calc_from_knx(0, 1000, 128) == 502
        assert RemoteValueScaling._calc_from_knx(0, 1000, 251) == 984
        assert RemoteValueScaling._calc_from_knx(0, 1000, 252) == 988
        assert RemoteValueScaling._calc_from_knx(0, 1000, 253) == 992
        assert RemoteValueScaling._calc_from_knx(0, 1000, 254) == 996
        assert RemoteValueScaling._calc_from_knx(0, 1000, 255) == 1000

    def test_calc_100_0(self):
        """Test if from/to calculations work with negative range."""
        assert RemoteValueScaling._calc_to_knx(100, 0, 0) == 255
        assert RemoteValueScaling._calc_to_knx(100, 0, 1) == 252
        assert RemoteValueScaling._calc_to_knx(100, 0, 2) == 250
        assert RemoteValueScaling._calc_to_knx(100, 0, 3) == 247
        assert RemoteValueScaling._calc_to_knx(100, 0, 30) == 178
        assert RemoteValueScaling._calc_to_knx(100, 0, 50) == 128
        assert RemoteValueScaling._calc_to_knx(100, 0, 70) == 76
        assert RemoteValueScaling._calc_to_knx(100, 0, 97) == 8
        assert RemoteValueScaling._calc_to_knx(100, 0, 98) == 5
        assert RemoteValueScaling._calc_to_knx(100, 0, 99) == 3
        assert RemoteValueScaling._calc_to_knx(100, 0, 100) == 0

        assert RemoteValueScaling._calc_from_knx(100, 0, 0) == 100
        assert RemoteValueScaling._calc_from_knx(100, 0, 1) == 100
        assert RemoteValueScaling._calc_from_knx(100, 0, 2) == 99
        assert RemoteValueScaling._calc_from_knx(100, 0, 3) == 99
        assert RemoteValueScaling._calc_from_knx(100, 0, 4) == 98
        assert RemoteValueScaling._calc_from_knx(100, 0, 5) == 98
        assert RemoteValueScaling._calc_from_knx(100, 0, 76) == 70
        assert RemoteValueScaling._calc_from_knx(100, 0, 128) == 50
        assert RemoteValueScaling._calc_from_knx(100, 0, 178) == 30
        assert RemoteValueScaling._calc_from_knx(100, 0, 251) == 2
        assert RemoteValueScaling._calc_from_knx(100, 0, 252) == 1
        assert RemoteValueScaling._calc_from_knx(100, 0, 253) == 1
        assert RemoteValueScaling._calc_from_knx(100, 0, 254) == 0
        assert RemoteValueScaling._calc_from_knx(100, 0, 255) == 0

    def test_calc_100_200(self):
        """Test if from/to calculations work with rnage not starting at zero."""
        assert RemoteValueScaling._calc_to_knx(100, 200, 100) == 0
        assert RemoteValueScaling._calc_to_knx(100, 200, 130) == 76
        assert RemoteValueScaling._calc_to_knx(100, 200, 150) == 128
        assert RemoteValueScaling._calc_to_knx(100, 200, 170) == 178
        assert RemoteValueScaling._calc_to_knx(100, 200, 200) == 255

        assert RemoteValueScaling._calc_from_knx(100, 200, 0) == 100
        assert RemoteValueScaling._calc_from_knx(100, 200, 76) == 130
        assert RemoteValueScaling._calc_from_knx(100, 200, 128) == 150
        assert RemoteValueScaling._calc_from_knx(100, 200, 178) == 170
        assert RemoteValueScaling._calc_from_knx(100, 200, 255) == 200

    def test_value_unit(self):
        """Test for the unit_of_measurement."""
        xknx = XKNX()
        remote_value = RemoteValueScaling(xknx)
        assert remote_value.unit_of_measurement == "%"


text:
package com.nec.strudel.entity;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface GroupId {

}


text:
class Array
  def self.insist(thing)
    thing.is_a?(Array) ? thing : [thing]
  end
end


text:
import gulp from 'gulp';
import {sass} from './sass';

export const prepare = 'prepare';

gulp.task(prepare, gulp.series(
    sass
));


text:
package io.shuqi.graduation.service;

import io.shuqi.graduation.domain.ClassDetail;
import io.shuqi.graduation.domain.Course;
import io.shuqi.graduation.domain.CourseClass;
import io.shuqi.graduation.domain.bo.Pager;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.ModelAndView;

public abstract class CourseService {

	/**
	 * 添加课程
	 * @author shuqi
	 * @date   2015年5月10日
	 * @version since 1.0
	 * @return
	 */
	public abstract ModelAndView addCourseIndex(HttpServletRequest request);
	/**
	 * 添加课程
	 * @author shuqi
	 * @date   2015年5月10日
	 * @version since 1.0
	 * @return
	 */
	public abstract Map<String, Object> addCourseAction(HttpServletRequest request);

	/**
	 * 科目管理
	 * @author shuqi
	 * @date   2015年5月10日
	 * @version since 1.0
	 * @param request
	 * @param pager
	 * @return
	 */
	public abstract ModelAndView courseManager(HttpServletRequest request, Pager<Course> pager);
	/**
	 * 编辑科目 -- index
	 * @author shuqi
	 * @date   2015年5月10日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract ModelAndView editCourseIndex(HttpServletRequest request, Long id);
	/**
	 * 编辑科目 --action
	 * @author shuqi
	 * @date   2015年5月10日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract Map<String, Object> editCourseAction(HttpServletRequest request, Long id);
	/**
	 * 科目课程管理
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @param pager
	 * @return
	 */
	public abstract ModelAndView courseClassManager(HttpServletRequest request, Pager<CourseClass> pager);
	/**
	 * 科目课程发布 --action
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @return
	 */

	public abstract Map<String, Object> addCourseClassAction(HttpServletRequest request);
	/**
	 * 课程发布 --index
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @return
	 */
	public abstract ModelAndView addCourseClassIndex(HttpServletRequest request);
	/**
	 * 编辑index
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract ModelAndView editCourseClassIndex(HttpServletRequest request, Long id);
	/**
	 * 编辑 action
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract Map<String, Object> editCourseClassAction(HttpServletRequest request, Long id);
	/**
	 * 添加课程内容 --index
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @return
	 */
	public abstract ModelAndView addCourseClassDetailIndex(HttpServletRequest request);
	/**
	 * 添加课程类容 --action
	 * @author shuqi
	 * @date   2015年5月11日
	 * @version since 1.0
	 * @param request
	 * @return
	 */
	public abstract Map<String, Object> addCourseClassDetailAction(HttpServletRequest request);
	/**
	 * 课程内容管理 ---老师
	 * @author shuqi
	 * @date   2015年5月12日
	 * @version since 1.0
	 * @param request
	 * @param pager
	 * @return
	 */
	public abstract ModelAndView classDetailManager(HttpServletRequest request, Pager<ClassDetail> pager);
	/**
	 * 编辑课程内容  --index
	 * @author shuqi
	 * @date   2015年5月12日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract ModelAndView editClasssDetailIndex(HttpServletRequest request, Long id);
	/**
	 * 编辑课程内容  --action
	 * @author shuqi
	 * @date   2015年5月12日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @return
	 */
	public abstract Map<String, Object> editClasssDetailAction(HttpServletRequest request, Long id);
	/**
	 * 课程中心
	 * @author shuqi
	 * @date   2015年5月13日
	 * @version since 1.0
	 * @param request
	 * @return
	 */
	public abstract ModelAndView courseIndex(HttpServletRequest request);
	/**
	 * 得到课程中心的分页
	 * @author shuqi
	 * @date   2015年5月13日
	 * @version since 1.0
	 * @param request
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	public abstract ModelAndView getCoursePger(HttpServletRequest request, Long currentPage, int pageSize,String type);

	/**
	 * 课程相关的查看
	 * @author shuqi
	 * @date   2015年5月14日
	 * @version since 1.0
	 * @param request
	 * @param id
	 * @param type
	 * @return
	 */
	public abstract ModelAndView view(HttpServletRequest request, Long id, String type);

	/**
	 * 课程评论
	 * @author shuqi
	 * @date   2015年5月14日
	 * @version since 1.0
	 * @param request
	 * @return
	 */
	public abstract Map<String, Object> addClassDetailComments(HttpServletRequest request);
}


text:
title: 'Diesel & Dust – The Outback'
author: David Hogge
layout: post
permalink: /australia/diesel-dust-the-outback.html
thumbnail: http://farm1.static.flickr.com/185/416122437_a41acda971
thumbnail_alt: Mad Maxs Car - Sweet!
geo_latitude:
  - -35.610767
geo_longitude:
  - 138.173302
geo_address:
  - Silverton, South Australia, Australia
geo_enabled:
  - 1
geo_public:
  - 1
categories:
  - Australia
tags:
  - Breaker Morant
  - Broken Hill
  - car camping adventure
  - Geography of Australia
  - Ghost town
  - New South Wales
  - Priscilla Queen
  - Silverton
---
As our car camping adventure in Aus continues we headed back to Sydney via the Outback. To say there's a lot of nothing out there is a bit of an understatement. Aside from mining towns, road houses, road trains and red dust there's not too much. We went through about three or four real towns in the better part of a week. There were three types: surprisingly big-ish towns centered around the mining industry, ghost towns and very poor run-down aboriginal towns with …no industry.

With all this nothing you would figure there wouldn't be too much to say about these towns. You'd be wrong, movie makers love this place, and they keep coming. It seems like every town we stopped at had been the set of some movie or another. Breaker Morant was filmed in Burra, Broken Hill played host to Priscilla Queen of the Desert, and the near ghost town of Silverton was the set of Mad Max. Cobar was home to …okay, there's nothing in Cobar (except free internet!).

And flat, let's talk about flat. On a ridge north of Silverton you can literally see the curvature of the Earth. It's a crazy strange and strangely beautiful place.


text:
<!DOCTYPE html>

<title>OfChat</title>
<meta charset="utf-8">

OfChat Changelog

0.0.0.9

New: Added support for Jingle Audio/Video using WebRTC JSEP

Changed: Fixed various faults

0.0.0.8

New: Added support for Jingle Audio/Video using WebRTC Roap

Changed: Removed support for Redfire

0.0.0.7

Fixed: Quotes replaced with escape characters in chat message

Fixed: Reconnection failure creating "Authenticating.." message

Fixed: Accept incoming messages from federated users not on roster

Fixed: Notifications for group chat

Fixed: Accept broadcasts messages (no chat type) from components or server

New: Added support for editing/viewing vCards and Avatars (XEP-0054 and XEP-0153)

0.0.0.6

New. Added partial support for Redfire Plugin. Audio video in chat and groupchat. Compatible with Redfire Spark plugin

Changed: Added Boxy jQuery plugin for UI windowing, dialogs and alerts

0.0.0.5

New. Added partial support for XEP-0100 Gateways. Requires Kraken plugin

0.0.0.4

New. Added partial support for XEP-0136 Archiving. Requires OpenArchive plugin

New. Added partial support for XEP-0045 MUC. Requires Openfire client management plugin

0.0.0.3

Fixed. Added missing enable/disable icons

0.0.0.2

Changed. Minimal Chrome version down-graded to 14 for OSX

Fixed. Filter for smilies removing HTML tags

0.0.0.1

New. Project cloned from Gtalklet by Sean Zheng

New. Added Strophe Openfire.Connection class for Openfire WebSocket plugin

Changed. Handled contact's first <presence> arriving before get roster response

Changed. Handled both 2way subscription expected by Openfire

Changed. Added avatars

Changed. Added emtional icons (smilies)


text:
<?php

namespace Appcia\Bind;

use Appcia\Utils\Arrays;

/**
 * Data bind
 */
abstract class Data extends Bind implements \IteratorAggregate, \Countable, \ArrayAccess
{
    /**
     * {@inheritdoc}
     */
    protected function getDefault()
    {
        return array();
    }

    /**
     * Set value by key
     *
     * @param int|string $key
     * @param mixed      $value
     *
     * @throws \InvalidArgumentException
     * @return $this
     */
    public function set($key, $value = null)
    {
        $this->check();

        if (!Arrays::isArray($key)) {
            $key = array($key => $value);
        }
        foreach ($key as $k => $v) {
            Arrays::setPath($this->data, $k, $v);
        }

        $this->encode();

        return $this;
    }

    /**
     * Push mixed value as data
     *
     * @param mixed $data
     *
     * @return $this
     */
    public function push($data)
    {
        if (is_array($data)) {
            $data = Arrays::extend($this->getData(), $data);
        } elseif (is_string($data)) {
            $data = Arrays::parse($data);
        }

        $this->setData($data);

        return $this;
    }

    /**
     * Remove value by key
     *
     * @param int|string $key
     *
     * @return $this
     */
    public function remove($key)
    {
        $this->check();

        Arrays::clear($this->data, $key);
        $this->encode();

        return $this;
    }

    /**
     * Check whether value exists by key
     *
     * @param int|string $key
     *
     * @return boolean
     */
    public function has($key)
    {
        $this->check();

        return array_key_exists($key, $this->data);
    }

    /**
     * Get value by key
     *
     * @param int|string $key
     * @param mixed      $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        $this->check();
        $value = Arrays::getPath($this->data, $key, $default);

        return $value;
    }

    /**
     * Check whether bind data is array (key / value storage)
     *
     * @param bool $verbose
     *
     * @throws \UnexpectedValueException
     * @return $this
     */
    protected function check($verbose = true)
    {
        $valid = is_array($this->data);
        if (!$valid && $verbose) {
            throw new \UnexpectedValueException(sprintf("Bind data is not an array: '%s'", gettype($this->data)));
        }

        return $valid;
    }

    /**
     * Allows iterating if data is in array
     *
     * {@inheritdoc}
     */
    public function getIterator()
    {
        $this->check();

        return new \ArrayIterator($this->data);
    }

    /**
     * Allows use count() on binding if data is an array
     *
     * {@inheritdoc}
     */
    public function count()
    {
        $this->check();

        return count($this->data);
    }

    /**
     * Set value as string representation from an array
     *
     * @param mixed $key
     * @param array $value
     *
     * @return $this
     */
    public function compose($key, $value)
    {
        return $this->set($key, Arrays::compose($value));
    }

    /**
     * Get value as an array from string representation
     *
     * @param mixed $key
     *
     * @return array
     */
    public function parse($key)
    {
        return Arrays::parse($this->get($key));
    }

    /**
     * {@inheritdoc}
     */
    public function offsetSet($offset, $value)
    {
        $this->set($offset, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetExists($offset)
    {
        return $this->has($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetUnset($offset)
    {
        $this->remove($offset);
    }

    /**
     * {@inheritdoc}
     */
    public function offsetGet($offset)
    {
        return $this->has($offset)
            ? $this->get($offset)
            : null;
    }

    /**
     * @see get()
     */
    public function __get($property)
    {
        return $this->get($property);
    }

    /**
     * @see set()
     */
    public function __set($property, $value)
    {
        $this->set($property, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        if ($this->check(false)) {
            return Arrays::compose($this->data);
        } else {
            return parent::__toString();
        }
    }
}


text:
from django.utils import six
from django.utils.html import escape
from django.utils.safestring import mark_safe

def split_classes(classes, separator=' '):
    return classes.split(separator) if not classes in ('', None) else []

def join_classes(iterable, *args):
    iterable += args
    return ' '.join(iterable)

class AttributeDict(dict):
    """
    A wrapper around `dict` that knows how to render itself as HTML
    style tag attributes.

    The returned string is marked safe, so it can be used safely in a template.
    See `.as_html` for a usage example.
    """

    def __str__(self):
        return self.as_html()

    def as_html(self):
        """
        Render to HTML tag attributes.

        Example:

        .. code-block:: python

            >>> from cmsplugin_bootstrap.utils import AttributeDict
            >>> attrs = AttributeDict({'class': 'mytable', 'id': 'someid'})
            >>> attrs.as_html()
            'class="mytable" id="someid"'

        :rtype: `~django.utils.safestring.SafeUnicode` object

        """
        return mark_safe(' '.join(['%s="%s"' % (k, escape(v if not callable(v) else v()))
                                   for k, v in six.iteritems(self)]))


text:
<?php

namespace backend\controllers;

use Yii;
use common\models\ShopConfig;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ShopconfigController implements the CRUD actions for ShopConfig model.
 */
class ShopconfigController extends CommonController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all ShopConfig models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (!$this->is_access('shopconfig/index')) {
            Yii::$app->session->setFlash('error', $this->errorInfo);
            return $this->redirect($this->redirectUrl);
        }

        $model = new ShopConfig();

        if (Yii::$app->request->isPost) {
            if (!$this->is_access('shopconfig/index')) {
                Yii::$app->session->setFlash('error', $this->errorInfo);
                return $this->redirect($this->redirectUrl);
            }

            $model->editData($_POST['ShopConfig']);

            $this->redirect(['index']);
        }
        $model->setData();

        Yii::$app->view->params['meta_title'] = '系统设置';

        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing ShopConfig model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (!$this->is_access('shopconfig/update')) {
            Yii::$app->session->setFlash('error', $this->errorInfo);
            return $this->redirect($this->redirectUrl);
        }

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            Yii::$app->session->setFlash('success', '编辑成功');

            return $this->redirect(['index']);
        } else {

            Yii::$app->view->params['meta_title'] = '编辑配置';

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Finds the ShopConfig model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ShopConfig the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ShopConfig::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
using NetMud.Data.Architectural.PropertyBinding;
using NetMud.Data.Gaia;
using NetMud.DataAccess.Cache;
using NetMud.DataStructure.Architectural.EntityBase;
using NetMud.DataStructure.Gaia;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace NetMud.Models.Admin
{
    public class ManageCelestialsViewModel : PagedDataModel<ICelestial>
    {
        public ManageCelestialsViewModel(IEnumerable<ICelestial> items)
            : base(items)
        {
            CurrentPageNumber = 1;
            ItemsPerPage = 20;
        }

        internal override Func<ICelestial, bool> SearchFilter
        {
            get
            {
                return item => item.Name.ToLower().Contains(SearchTerms.ToLower());
            }
        }

        internal override Func<ICelestial, object> OrderPrimary
        {
            get
            {
                return item => item.Name;
            }
        }

        internal override Func<ICelestial, object> OrderSecondary
        {
            get
            {
                return null;
            }
        }
    }

    public class AddEditCelestialViewModel : AddEditTemplateModel<ICelestial>
    {
        [Display(Name = "Apply Existing Template", Description = "Apply an existing object's data to this new data.")]
        [UIHint("CelestialList")]
        [CelestialDataBinder]
        public override ICelestial Template { get; set; }

        public AddEditCelestialViewModel() : base(-1)
        {
            ValidMaterials = TemplateCache.GetAll<IMaterial>(true);
            ValidModels = TemplateCache.GetAll<IDimensionalModelData>(true);
    }

        public AddEditCelestialViewModel(long templateId) : base(templateId)
        {
            ValidMaterials = TemplateCache.GetAll<IMaterial>(true);
            ValidModels = TemplateCache.GetAll<IDimensionalModelData>(true);
            DataObject = new Celestial();

            //apply template
            if (DataTemplate != null)
            {
                DataObject.Apogee = DataTemplate.Apogee;
                DataObject.Perigree = DataTemplate.Apogee;
                DataObject.Velocity = DataTemplate.Velocity;
                DataObject.Luminosity = DataTemplate.Luminosity;
                DataObject.Model = DataTemplate.Model;
                DataObject.OrientationType = DataTemplate.OrientationType;
            }
        }

        public AddEditCelestialViewModel(string archivePath, ICelestial item) : base(archivePath, item)
        {
            ValidMaterials = TemplateCache.GetAll<IMaterial>(true);
            ValidModels = TemplateCache.GetAll<IDimensionalModelData>(true);
            DataObject = item;
        }

        public IEnumerable<IDimensionalModelData> ValidModels { get; set; }
        public IEnumerable<IMaterial> ValidMaterials { get; set; }

        public ICelestial DataObject { get; set; }
    }
}


text:
<?php

namespace Tests\Behat\Gherkin\Keywords;

use Symfony\Component\Finder\Finder,
    Symfony\Component\Translation\Translator,
    Symfony\Component\Translation\MessageSelector,
    Symfony\Component\Translation\Loader\XliffFileLoader;

use Behat\Gherkin\Lexer,
    Behat\Gherkin\Parser,
    Behat\Gherkin\Node,
    Behat\Gherkin\Keywords\SymfonyTranslationKeywords;

class SymfonyTranslationKeywordsTest extends \PHPUnit_Framework_TestCase
{
    private $translator;
    private $parser;

    public function translationTestDataProvider()
    {
        $data = array();

        $translator = $this->getTranslator();
        $parser     = $this->getParser();

        $finder     = new Finder();
        $i18ns      = $finder->files()->name('*.xliff')->in(__DIR__ . '/../Fixtures/i18n');

        foreach ($i18ns as $i18n) {
            $language = basename($i18n, '.xliff');
            $translator->addResource('xliff', $i18n, $language, 'gherkin');

            $etalon   = array();
            $features = array();
            foreach ($this->getTranslatedKeywords('Feature', $language) as $featureNum => $featureKeyword) {
                $gherkin = "# language: $language";
                $lineNum = 1;

                $feature = new Node\FeatureNode(null, null, null, ++$lineNum);
                $feature->setLanguage($language);
                $feature->setKeyword($featureKeyword);
                $feature->setTitle($title = "title of the feature N$featureNum");
                $feature->setDescription($description = "some\nfeature\ndescription");

                $gherkin .= "\n$featureKeyword: $title";
                $gherkin .= "\n$description";
                $lineNum += 3;

                $stepKeywords       = $this->getTranslatedKeywords('Given|When|Then|And|But', $language);
                $backgroundKeywords = $this->getTranslatedKeywords('Background', $language);
                $examplesKeywords   = $this->getTranslatedKeywords('Examples', $language);

                // Background
                $backgroundKeyword = $backgroundKeywords[0];
                $background = new Node\BackgroundNode(null, ++$lineNum);
                $background->setKeyword($backgroundKeyword);
                $feature->setBackground($background);

                $gherkin .= "\n$backgroundKeyword:";

                foreach ($stepKeywords as $stepNum => $stepKeyword) {
                    $step = new Node\StepNode($stepKeyword, $text = "text of the step N$stepNum", ++$lineNum);
                    $background->addStep($step);

                    $gherkin .= "\n$stepKeyword $text";
                }

                // Scenarios
                foreach ($this->getTranslatedKeywords('Scenario', $language) as $scenarioNum => $scenarioKeyword) {
                    $scenario = new Node\ScenarioNode($title = "title of the scenario N$scenarioNum", ++$lineNum);
                    $scenario->setKeyword($scenarioKeyword);
                    $feature->addScenario($scenario);

                    $gherkin .= "\n$scenarioKeyword: $title";

                    foreach ($stepKeywords as $stepNum => $stepKeyword) {
                        $step = new Node\StepNode($stepKeyword, $text = "text of the step N$stepNum", ++$lineNum);
                        $scenario->addStep($step);

                        $gherkin .= "\n$stepKeyword $text";
                    }
                }

                // Scenario Outlines
                foreach ($this->getTranslatedKeywords('Scenario Outline', $language) as $outlineNum => $outlineKeyword) {
                    $outline = new Node\OutlineNode($title = "title of the outline N$outlineNum", ++$lineNum);
                    $outline->setKeyword($outlineKeyword);
                    $feature->addScenario($outline);

                    $gherkin .= "\n$outlineKeyword: $title";

                    $stepKeyword = $stepKeywords[0];
                    $step = new Node\StepNode($stepKeyword, $text = "text of the step <num>", ++$lineNum);
                    $outline->addStep($step);

                    $gherkin .= "\n$stepKeyword $text";

                    $examplesKeyword = $examplesKeywords[0];
                    $examples = new Node\TableNode();
                    $examples->setKeyword($examplesKeyword);
                    $lineNum += 1;

                    $examples->addRow(array('num'), ++$lineNum);
                    $examples->addRow(array(2), ++$lineNum);
                    $outline->setExamples($examples);

                    $gherkin .= "\n$examplesKeyword:";
                    $gherkin .= "\n  | num |";
                    $gherkin .= "\n  | 2   |";
                }

                $etalon[]   = $feature;
                $features[] = $this->getParser()->parse($gherkin);
            }

            $data[] = array($language, $etalon, $features);
        }

        return $data;
    }

    /**
     * @dataProvider translationTestDataProvider
     *
     * @param   string  $language   language name
     * @param   array   $etalon     etalon features (to test against)
     * @param   array   $features   array of parsed feature(s)
     */
    public function testTranslation($language, array $etalon, array $features)
    {
        $this->assertEquals($etalon, $features);
    }

    protected function getParser()
    {
        if (null === $this->parser) {
            $keywords       = new SymfonyTranslationKeywords($this->getTranslator());
            $lexer          = new Lexer($keywords);
            $this->parser   = new Parser($lexer);
        }

        return $this->parser;
    }

    protected function getTranslator()
    {
        if (null === $this->translator) {
            $this->translator = new Translator(null, new MessageSelector());
            $this->translator->addLoader('xliff', new XliffFileLoader());
        }

        return $this->translator;
    }

    protected function getTranslatedKeywords($keyword, $language)
    {
        return explode('|', $this->translate($keyword, $language));
    }

    protected function translate($keyword, $language)
    {
        return $this->getTranslator()->trans($keyword, array(), 'gherkin', $language);
    }
}


text:
class AddFieldsToCourseLessonPlanItem < ActiveRecord::Migration
  def change
    add_column :course_lesson_plan_items,
               :course_id, :integer,
               null: false,
               foreign_key: { references: :courses }
    add_column :course_lesson_plan_items, :title, :string, null: false
    add_column :course_lesson_plan_items, :description, :text
    add_column :course_lesson_plan_items, :published, :boolean, default: false, null: false
    change_column :course_lesson_plan_items, :start_time, :datetime, null: false
  end
end


text:
package ds

import "fmt"

var (
	ErrHeapFull  = fmt.Errorf("Heap is full")
	ErrHeapEmpty = fmt.Errorf("Heap is empty")
)

type BinaryHeap struct {
	heap           []interface{}
	comparer       Comparer
	size           int
	insertionPoint int
}

func NewBinaryHeap(comparer Comparer, size int) *BinaryHeap {
	return &BinaryHeap{
		heap:           make([]interface{}, size),
		comparer:       comparer,
		size:           size,
		insertionPoint: 0,
	}
}

func (bh *BinaryHeap) Size() int {
	return bh.insertionPoint
}

func (bh *BinaryHeap) Peek() interface{} {
	return bh.heap[0]
}

func (bh *BinaryHeap) Insert(data ...interface{}) error {
	if bh.insertionPoint+len(data) > bh.size {
		return ErrHeapFull
	}

	for _, d := range data {
		bh.heap[bh.insertionPoint] = d
		bh.percolateUp()
		bh.insertionPoint += 1
	}

	return nil
}

func (bh *BinaryHeap) percolateUp() {
	currPtr := bh.insertionPoint
	for {
		parent := (currPtr - 1) / 2
		if bh.comparer(bh.heap[parent], bh.heap[currPtr]) >= 0 {
			break
		}
		bh.swapItems(parent, currPtr)
		currPtr = parent
	}
}

func (bh *BinaryHeap) Remove() (interface{}, error) {
	if bh.insertionPoint == 0 {
		return nil, ErrHeapEmpty
	}

	item := bh.heap[0]
	bh.insertionPoint = bh.insertionPoint - 1
	bh.heap[0] = bh.heap[bh.insertionPoint]
	if bh.insertionPoint > 1 {
		bh.percolateDown()
	}
	return item, nil
}

func (bh *BinaryHeap) percolateDown() {
	currPtr := 0
	for {
		child := (currPtr * 2) + 1
		if child >= bh.insertionPoint || bh.comparer(bh.heap[currPtr], bh.heap[child]) >= 0 {
			break
		}
		bh.swapItems(currPtr, child)
		currPtr = child
	}
}

func (bh *BinaryHeap) swapItems(a int, b int) {
	tmp := bh.heap[a]
	bh.heap[a] = bh.heap[b]
	bh.heap[b] = tmp
}

func (bh *BinaryHeap) String() string {
	return fmt.Sprintf("{ip: %d, heap: %#v}", bh.insertionPoint, bh.heap)
}


text:
<ExtendHITResult>
  <Request>
    <IsValid>True</IsValid>
  </Request>
</ExtendHITResult>


text:
import fs from 'fs';
import csv from 'csv-parser';
import toJson from './to-json';
import { autobind } from 'core-decorators';
import path from 'path';

export class CsvToJsonInPlace {
  constructor(argv) {
    this.file = argv.file;
    this.tmpFile = `${this.file}.json`;
    const structured = path.parse(this.file);
    delete structured.base;
    structured.ext = '.json';
    this.outFile= path.format(structured);
  }

  run() {
    fs.createReadStream(this.file)
      .pipe(csv())
      .pipe(toJson())
      .pipe(fs.createWriteStream(this.tmpFile))
      .on('close', this.onClose)
  }

  @autobind
  onClose(err) {
    if (err) {
      return;
    }
    fs.rename(this.tmpFile, this.outFile, this.onRename);
  }

  @autobind
  onRename(err) {
    console.log('done', this.outFile);
  }
}


text:
/* 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.
 */
package org.camunda.bpm.container.impl.jmx.deployment;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.camunda.bpm.application.AbstractProcessApplication;
import org.camunda.bpm.application.impl.metadata.spi.ProcessesXml;
import org.camunda.bpm.container.impl.jmx.JmxRuntimeContainerDelegate.ServiceTypes;
import org.camunda.bpm.container.impl.jmx.kernel.MBeanDeploymentOperation;
import org.camunda.bpm.container.impl.jmx.kernel.MBeanDeploymentOperationStep;
import org.camunda.bpm.container.impl.jmx.kernel.MBeanServiceContainer;
import org.camunda.bpm.container.impl.jmx.services.JmxManagedProcessApplication;
import org.camunda.bpm.container.impl.metadata.spi.ProcessEngineXml;
import org.camunda.bpm.engine.ProcessEngineException;

/**
 *
Deployment operation responsible for stopping all process engines started by the deployment.

 *
 * @author Daniel Meyer
 *
 */
public class ProcessesXmlStopProcessEnginesStep extends MBeanDeploymentOperationStep {

  protected final static Logger LOGGER = Logger.getLogger(ProcessesXmlStopProcessEnginesStep.class.getName());

  public String getName() {
    return "Stopping process engines";
  }

  public void performOperationStep(MBeanDeploymentOperation operationContext) {

    final MBeanServiceContainer serviceContainer = operationContext.getServiceContainer();
    final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION);
    final JmxManagedProcessApplication deployedProcessApplication = serviceContainer.getService(ServiceTypes.PROCESS_APPLICATION, processApplication.getName());

    if(deployedProcessApplication == null) {
      throw new ProcessEngineException("Cannot find process application with name "+processApplication.getName()+".");
    }

    List<ProcessesXml> processesXmls = deployedProcessApplication.getProcessesXmls();
    for (ProcessesXml processesXml : processesXmls) {
      stopProcessEngines(processesXml.getProcessEngines(), operationContext);
    }

  }

  protected void stopProcessEngines(List<ProcessEngineXml> processEngine, MBeanDeploymentOperation operationContext) {
    for (ProcessEngineXml parsedProcessEngine : processEngine) {
      stopProcessEngine(parsedProcessEngine.getName(), operationContext);
    }
  }

  protected void stopProcessEngine(String processEngineName, MBeanDeploymentOperation operationContext) {

    final MBeanServiceContainer serviceContainer = operationContext.getServiceContainer();
    try {
      serviceContainer.stopService(ServiceTypes.PROCESS_ENGINE.getServiceName(processEngineName));

    } catch(Exception e) {
      LOGGER.log(Level.WARNING, "Could not stop managed process engine: "+e.getMessage(), e);

    }

  }

}


text:
void statemgr_push(State *s, void *data);
State *statemgr_pop();
State *statemgr_peek();

void statemgr_update();
void statemgr_draw();

#endif


text:
var gulp   = require('gulp');

var changed = require('gulp-changed');

var config = require('../../config').fonts.development;

/**
 * Copy fonts to folder
 */
gulp.task('fonts:development', function() {
  return gulp.src(config.src)
    .pipe(changed(config.dest))
    .pipe(gulp.dest(config.dest));
});


text:
package apps.stisser.karissa.feelgood;

/**
 * Created by yfadila on 3/4/2017.
 */

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MessagesBroker {

    public interface MessageCallBack {
        void onMessage(Message message);
    }

    public static Map<String, MessageCallBack> callBackMap = new HashMap<>();

    public static List<Message> getMessages(String chatRoom, MessageCallBack callBack){
        if (callBack !=null) {
            callBackMap.put(chatRoom, callBack);
        }
        List<Message> msgs = new ArrayList<>();
        for(int i=0; i< allMessages.size(); i++) {
            //(int id, String time, String from, String content, String topic)
            if (allMessages.get(i).getAsJsonArray().get(2).toString().replace("\"","").equals(chatRoom)) {
                Message e = new Message(allMessages.get(i).getAsJsonArray());
                msgs.add(e);
            }
        }
        return  msgs;
    }

    private static int lastId = 0;
    private static final String BASE_URL = "http://fadila.net/feelgood/index.php/messages";
    private static Gson gson = new Gson();
    private static JsonArray allMessages = new JsonArray();
    private static ScheduledThreadPoolExecutor executor = 	new ScheduledThreadPoolExecutor(2);
   // private static final Handler h = new Handler();
    public static JsonArray fetchMessages() {
        JsonArray records = null;

        try {
            URL url = new URL(BASE_URL + "?filter=id,gt," + lastId);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output = br.readLine();
            JsonElement jelem = gson.fromJson(output, JsonElement.class);
            records = jelem.getAsJsonObject().getAsJsonObject("messages").getAsJsonArray("records");
            if (records.size() > 0)
            {
                lastId = Integer.parseInt(records.get(records.size() - 1).getAsJsonArray().get(0).toString());
            }

            conn.disconnect();
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();
        }
        return records;
    }
    // bad practice, This is for 1st POC stage only.
    public static void addMessage(Message msg) {

        try {
            URL object = new URL(BASE_URL);
            HttpURLConnection con = (HttpURLConnection) object.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestMethod("POST");

            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(msg.getStringToPost());
            wr.flush();
            int HttpResult = con.getResponseCode();
            if (HttpResult != HttpURLConnection.HTTP_OK) {
                System.out.println(con.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void addMessageAsync(final Message msg) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                addMessage(msg);
            }
        });
    }

    public static void pollMessages(){
        final int delay = 2000; //milliseconds
       executor.scheduleAtFixedRate(new Runnable(){
            public void run(){
                JsonArray newMessgaes = fetchMessages();
                if (newMessgaes.size() != 0) {
                    allMessages.addAll(newMessgaes);
                    for (int i=0; i<newMessgaes.size(); i++) {
                        String chatroom = newMessgaes.get(i).getAsJsonArray().get(2).toString().replace("\"","");
                        if (callBackMap.get(chatroom) != null)
                            callBackMap.get(chatroom).onMessage(new Message(newMessgaes.get(i).getAsJsonArray()));
                    }
                }
                //h.postDelayed(this, delay);
            }
        },delay,delay, TimeUnit.MILLISECONDS);
    }

    public static String getQuestionByID(int id){

        return "question";
    }

    public static void submitQuestion(Message m){

    }

    public static void submitAnswer(Message m){

    }

    public static void main(String[] args) throws InterruptedException {
        pollMessages();
        addMessageAsync(new Message(943,"","vvv","slama","lilya"));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:scg="http://www.adobe.com/social/scg/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:mix="http://www.jcp.org/jcr/mix/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="cq:Page">
    <jcr:content
        cq:lastModified="{Date}2016-01-07T17:25:48.967+05:30"
        cq:lastModifiedBy="admin"
        cq:lastReplicated="{Date}2013-12-10T15:02:21.968-05:00"
        cq:lastReplicatedBy="admin"
        cq:lastReplicationAction="Activate"
        cq:template="/apps/scf/templates/page"
        jcr:isCheckedOut="{Boolean}true"
        jcr:mixinTypes="[mix:versionable]"
        jcr:primaryType="cq:PageContent"
        jcr:title="Blogs"
        jcr:uuid="b9bc2635-d2c6-4a45-9cba-8265f8f1cd4a"
        sling:resourceType="/apps/scf/components/page"
        navTitle="Blogs">
        <content
            jcr:primaryType="nt:unstructured"
            sling:resourceType="foundation/components/parsys">
            <title
                jcr:created="{Date}2013-12-06T11:35:15.808-05:00"
                jcr:createdBy="admin"
                jcr:lastModified="{Date}2013-12-06T11:35:15.808-05:00"
                jcr:lastModifiedBy="admin"
                jcr:primaryType="nt:unstructured"
                sling:resourceType="foundation/components/title"/>
            <clientlibslist
                jcr:created="{Date}2013-12-06T13:01:47.362-05:00"
                jcr:createdBy="admin"
                jcr:lastModified="{Date}2013-12-06T13:10:44.759-05:00"
                jcr:lastModifiedBy="admin"
                jcr:primaryType="nt:unstructured"
                scg:requiredClientLibs="apps.scf.ideation, cq.social.hbs.voting, cq.ckeditor"
                sling:resourceType="scf/components/clientlibslist"/>
            <forum
                jcr:created="{Date}2014-08-12T23:00:18.693-07:00"
                jcr:createdBy="admin"
                jcr:lastModified="{Date}2016-01-07T17:25:48.900+05:30"
                jcr:lastModifiedBy="admin"
                jcr:primaryType="nt:unstructured"
                sling:resourceType="scf/components/ideation/forum"
                allowTagging="true"
                allowVoting="true"
                flagModerateThreshold="1"
                flagViewThreshold="5"
                maxFileSize="104857600"
                maxImageFileSize="2097152"
                subscribeWorkflow="/etc/workflow/models/social/forum/forum_topic_subscription/jcr:content/model"
                taggingFilter="/etc/tags/scfTech"/>
        </content>
        <header
            jcr:primaryType="nt:unstructured"
            sling:resourceType="/apps/scf/components/header"/>
    </jcr:content>
</jcr:root>


text:
bart = ("Bart","Homero",(25,60))
todd = ("Todd","Ned",(15,80))
rafa = ("Rafa","Gorgory",(10,1))

nombre (n,_,_) = n
padre (_,p,_) = p
habilidad (_,_,h) = h

-- ( Tiro -> Bool, Tiro -> Tiro )
-- ((velocidad,precision,altura), efecto)
laguna largo = ((\(v,_,a) -> v>80 && between 10 50 a),(\(v,p,a) -> (v,p,a `div` largo)))
tunelConRampita = ((\(_,p,a) -> p>90 && a==0), (\(v,_,a) -> (v*2,100,0)))
hoyo = ((\(v,p,a) -> between 5 20 v && p>95 && a==0), (\ _ -> (0,0,0)))
between n m x = elem x [n .. m]

maximoSegun f = foldl1 (mayorSegun f)
mayorSegun f a b 	| f a >= f b = a
					| otherwise = b

-- Punto 1
--- parHabilidad es una tupla habilidad que se compone por fuerza y precision (fuerza,precision).
putter parHabilidad = (10,(snd parHabilidad)*2,0)
madera parHabilidad = (100,(snd parHabilidad)*2,5)
hierro n parHabilidad = ((fst parHabilidad) * n, quot (snd parHabilidad) n, n^2) -- Utilizo quot para que devuelva (Int, Int, Int)
-- Funcion pre-definida
palos = putter : madera : map hierro [1 .. 10]

-- Punto 2
--- Obtener el tiro con jugador y palo.
golpe jugador palo = (palo.habilidad) jugador

--- Averiguo si puedo superar un obstaculo recibiendo un tiro
puedeSuperar obstaculo tuplaTiro = fst obstaculo tuplaTiro

--- Defino los palos utiles
palosUtiles jugador obstaculo = (filter (puedeSuperar obstaculo).map (golpe jugador)) palos

-- Obtengo las personas que pueden superar todos los obstaculos de una lista
--- Voy a usar una función auxiliar para evaluar que la lista de palosUtiles no contenga la lista vacia. Si devuelve True, entonces puede con todos los obstaculos.
puedeSuperarTodosLosObstaculos listaObstaculos jugador = (not.elem [].map (palosUtiles jugador)) listaObstaculos

nombreDeLosQuePuedenSuperarTodos listaObstaculos listaJugadores = (map nombre.filter (puedeSuperarTodosLosObstaculos listaObstaculos)) listaJugadores

-- Punto 3
--- Saber cuantos obstaculos puede superar. Solo devuelve un Int con el valor de cantidad de obstaculos
sumadorDeObstaculos tiro [] = []
sumadorDeObstaculos tiro ((esTiroValido,efectoDeTiro):obstaculoTail) 	| esTiroValido tiro = (efectoDeTiro tiro):(sumadorDeObstaculos (efectoDeTiro tiro) obstaculoTail)
																		| otherwise = []

cuantosObstaculosSupera tiro listaObstaculos = length (sumadorDeObstaculos tiro listaObstaculos)

--- Determinar cual es el palo que permite superar mas obstaculos.
--- Recordamos del punto 2 que no se puede mostrar el nombre del palo, pero mostramos la tupla de tiro que genera.
paloMasUtil jugador listaObstaculos = snd(maximum(mapeoDeTuplas jugador listaObstaculos))
formarTuplaPalos jugador listaObstaculos palo = ((cuantosObstaculosSupera (golpe jugador palo) listaObstaculos),(golpe jugador palo))
mapeoDeTuplas jugador listaObstaculos = map (formarTuplaPalos jugador listaObstaculos) palos

-- Punto 4
--- Devolver puntos ganados por tipo de tiro.
dificultadDeLaguna obstaculo tiro listaLargo = [ snd obstaculo tiro == snd (laguna largo) tiro | largo <- listaLargo ]

nivelDeDificultad obstaculo tiro 	| snd obstaculo tiro == (0,0,0) || elem True (dificultadDeLaguna obstaculo tiro [1..5]) = "facil"
									| snd obstaculo tiro == snd tunelConRampita tiro || elem True (dificultadDeLaguna obstaculo tiro [6..10]) = "medio"
									| otherwise = "complejo"

puntosGanados obstaculo tiro 	| fst obstaculo tiro && nivelDeDificultad obstaculo tiro == "facil" = 50
								| fst obstaculo tiro && nivelDeDificultad obstaculo tiro == "medio" = 75
								| fst obstaculo tiro && nivelDeDificultad obstaculo tiro == "complejo" = 100
								| otherwise = 0

--- Determinar el padre de quien perdio la apuesta.
listadoDeSuperadores listaJugadores listaObstaculos = filter (puedeSuperarTodosLosObstaculos listaObstaculos) listaJugadores
-- Aca hay una cuestion, segun el enunciado, con la lista de prueba [tunelConRampita, laguna 1, hoyo] ganaria Todd. Pero si calculamos "cuantosObstaculosSupera" para ambos, ninguno de los dos pasa mas de uno, no cumpliendo con "Un niño gana si puede superar todos los obstaculos". Si, -puede-, pero no lo hace. Aceptando esa frase, solo necesito la lista de los que PUEDEN, y despues sumar puntos.
-- Esta funcion la armamos para calcular, en algun momento, que si supera la misma cantidad de "length(listaObstaculos)" entonces es el ganador.
-- El caso no se da.
-- cantidadDeObstaculos listaObstaculos jugador = cuantosObstaculosSupera (paloMasUtil jugador listaObstaculos) listaObstaculos
inversorPalos listaObstaculos jugador = paloMasUtil jugador listaObstaculos
armadoDePalos listaJugadores listaObstaculos = map (inversorPalos listaObstaculos) (listadoDeSuperadores listaJugadores listaObstaculos)

pierdeLaApuesta listaJugadores listaObstaculos = 0

-- Punto 6
-- funcionMrBurns :: (Num b) => (a, b -> b) -> (f -> b) -> (b -> d -> g) -> [f] -> Int
funcionMrBurns x y z = length.flip z 12.foldl1 (snd.x).map y

-- En primer lugar, sabemos que map es una función que recibe una función que aplicará a una lista, y devuelve un resultado.
-- De esto, sacamos dos cosas:
-- Que "y" es una funcion que recibe un valor y retorna otro, por lo cual su tipo sera (f -> b) y que, debido a que la función está aplicando
-- composición, funcionMrBurns recibe un parametro más después de "z", que será una lista de tipo [f].
-- snd es una función aplicada a tuplas binarias, por tanto x es una tupla binaria (a,b).
-- foldl1 toma una función y una lista, a la cual le aplica recursivamente la función. Por tanto, el segundo valor de la tupla "x" es una funcion.
-- La lista generada por "map y" es la que evaluará foldl1, por tanto la funcion (snd.x) evaluará argumentos del tipo b y devolverá el mismo tipo. Por esto es que la función "y" devuelve elementos b.
-- Flip es una función que recibe una función binaria y da vuelta el orden de sus argumentos. La función binaria z es entonces (b -> d -> g).
-- Por ultimo, length da el tamaño de una lista, tal que devuelve un Int, que es lo que devuelve nuestra funcionMrBurns.


text:
title: Delegation and the OIDC-conformant pipeline
topics:
  - api-authentication
  - oidc
  - delegation
contentType: concept
useCase:
  - secure-api
  - call-api
---

# Delegation and the OIDC-Conformant Pipeline

<%= include('../../../_includes/_deprecate-delegation') %>

<%= include('./_about.md') %>

[Delegation](/api/authentication#delegation) is used for many operations, depending on your particular use case:

* Exchanging an ID Token issued to one application for a new one issued to a different application
* Using a <dfn data-key="refresh-token">Refresh Token</dfn> to obtain a fresh ID Token
* Exchanging an ID Token for a third-party API token, such as Firebase or AWS.

Given that [ID Tokens should no longer be used as API tokens](/api-auth/tutorials/adoption/api-tokens) and that [Refresh Tokens should be used only at the token endpoint](/api-auth/tutorials/adoption/refresh-tokens), this endpoint is now considered deprecated.

Applications marked as [OIDC-conformant](/api-auth/tutorials/adoption/oidc-conformant) cannot be the source or target of Auth0-to-Auth0 delegation requests.

## Third-party APIs (such as Firebase or AWS)

At the moment there is no OIDC-compliant mechanism to obtain third-party API tokens.
In order to facilitate a gradual migration to the new authentication pipeline, delegation can still be used to obtain third-party API tokens.
This will be deprecated in future releases.

## Keep reading

<%= include('./_index.md') %>


text:
<?php

declare(strict_types=1);

namespace CriticalSectionTests\Driver;

require_once(__DIR__ . '/../bootstrap.php');

use Bileto\CriticalSection\Driver\FileDriver;
use Bileto\CriticalSection\Exception\CriticalSectionException;
use Mockery;
use Tester\Assert;
use Tester\TestCase;

class FileDriverTest extends TestCase
{

    const TEST_LABEL = "test";

    /** @var FileDriver */
    private $driver;

    /** @var string */
    private $filesDir;

    protected function setUp()
    {
        $this->filesDir = TEMP_DIR . '/critical-section';
        mkdir($this->filesDir, 0777, true);
        $this->driver = new FileDriver($this->filesDir);
    }

    protected function tearDown()
    {
        system('rm -rf ' . escapeshellarg($this->filesDir));
        Mockery::close();
    }

    public function testCanAcquireOnce()
    {
        Assert::true($this->driver->acquireLock(self::TEST_LABEL));
    }

    public function testCanReleaseOnceAndOnlyOnce()
    {
        Assert::true($this->driver->acquireLock(self::TEST_LABEL));
        Assert::true($this->driver->releaseLock(self::TEST_LABEL));
        Assert::false($this->driver->releaseLock(self::TEST_LABEL));
    }

    public function testReleaseWithoutAcquire()
    {
        Assert::false($this->driver->releaseLock(self::TEST_LABEL));
    }

    public function testCanAcquireAndReleaseMultipleTimes()
    {
        Assert::true($this->driver->acquireLock(self::TEST_LABEL));
        Assert::true($this->driver->releaseLock(self::TEST_LABEL));
        Assert::true($this->driver->acquireLock(self::TEST_LABEL));
        Assert::true($this->driver->releaseLock(self::TEST_LABEL));
        Assert::true($this->driver->acquireLock(self::TEST_LABEL));
        Assert::true($this->driver->releaseLock(self::TEST_LABEL));
    }

    public function testCannotCreateDirectory()
    {
        $path = TEMP_DIR . '/file';
        touch($path);
        Assert::exception(function () use ($path) {
            new FileDriver($path);
        }, CriticalSectionException::class);
        unlink($path);
    }

}

(new FileDriverTest)->run();


text:
package org.apache.hadoop.yarn.applications.distributedshell;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.yarn.api.records.ContainerId;

import java.nio.ByteBuffer;
import java.util.Map;

public class ContainerLaunchFailAppMaster extends ApplicationMaster {

  private static final Log LOG =
      LogFactory.getLog(ContainerLaunchFailAppMaster.class);

  public ContainerLaunchFailAppMaster() {
    super();
  }

  @Override
  NMCallbackHandler createNMCallbackHandler() {
    return new FailContainerLaunchNMCallbackHandler(this);
  }

  class FailContainerLaunchNMCallbackHandler
      extends ApplicationMaster.NMCallbackHandler {

    public FailContainerLaunchNMCallbackHandler(
        ApplicationMaster applicationMaster) {
      super(applicationMaster);
    }

    @Override
    public void onContainerStarted(ContainerId containerId,
        Map<String, ByteBuffer> allServiceResponse) {
      super.onStartContainerError(containerId,
          new RuntimeException("Inject Container Launch failure"));
    }

  }

  public static void main(String[] args) {
    boolean result = false;
    try {
      ContainerLaunchFailAppMaster appMaster =
          new ContainerLaunchFailAppMaster();
      LOG.info("Initializing ApplicationMaster");
      boolean doRun = appMaster.init(args);
      if (!doRun) {
        System.exit(0);
      }
      appMaster.run();
      result = appMaster.finish();
    } catch (Throwable t) {
      LOG.fatal("Error running ApplicationMaster", t);
      System.exit(1);
    }
    if (result) {
      LOG.info("Application Master completed successfully. exiting");
      System.exit(0);
    } else {
      LOG.info("Application Master failed. exiting");
      System.exit(2);
    }
  }

}


text:
set -ex

##
# Auxiliar functions

PORTUS_DB_ADAPTER=${PORTUS_DB_ADAPTER:-mysql2}

# Interacts with a daemon by taking two arguments:
#   1. The action (e.g. "start").
#   2. The service (e.g. "mysql").
# We do this to abstract the fact that Travis CI does not use systemd and we do.
function __daemon() {
    if [[ -z "$CI" ]]; then
        sudo systemctl $1 $2
    else
        sudo service $2 $1
    fi
}

# Performs systemctl calls to the current database adapter when used outside of
# a container.
function __database() {
    if [[ -f /.dockerenv ]]; then
        return
    fi

    if [[ "$PORTUS_DB_ADAPTER" == "mysql2" ]]; then
        __daemon $1 mysql
    else
        __daemon $1 postgresql
    fi
}

# Setup an insecure registry for the local docker.
function __docker_insecure() {
    if [[ ! -z "$CI" ]]; then
        sudo tee /etc/docker/daemon.json > /dev/null <<EOF
{
  "insecure-registries" : ["172.17.0.1:5000"]
}
EOF
    fi
    __daemon restart docker

    # Show version info
    docker --version
    docker-compose --version
}

if [ -z "$PORTUS_CI" ]; then
    echo "You have to set the PORTUS_CI environment variable."
    echo "Available values: unit and integration."
    exit 1
fi

##
# The actual run

if [ "$PORTUS_CI" = "unit" ] || [ "$PORTUS_CI" = "all" ]; then
    # Test commit messages
    bundle exec rake test:git

    # Style and security checks
    bundle exec rubocop -V
    bundle exec rubocop --extra-details --display-style-guide --display-cop-names

    # Check that MySQL and PostgreSQL have the same schema version
    bundle exec rails r bin/schema_check.rb

    # Compile assets
    bundle exec rake portus:assets:compile

    # Ruby tests
    __database restart
    bundle exec rspec spec

    # Note: it ignores a couple of files which use ruby 2.5 syntax which brakeman
    # does not know how to handle...
    bundle exec brakeman --skip-files lib/portus/background/sync.rb,lib/portus/registry_client.rb

    # JavaScript tests and style.
    yarn test
    yarn eslint
fi

# Integration tests.
if [ "$PORTUS_CI" = "integration" ] || [ "$PORTUS_CI" = "all" ]; then
    if [[ ! -f /.dockerenv ]]; then
        __docker_insecure
        bundle exec rake test:run
    fi
fi


text:
yum_key node['repo']['epel']['key'] do
  url  node['repo']['epel']['key_url']
  action :add
end

yum_repository "epel" do
  description "Extra Packages for Enterprise Linux"
  key node['repo']['epel']['key']
  mirrorlist node['repo']['epel']['url']
  action :add
end


text:
package exec

import (
	"context"
	"fmt"
	"runtime/debug"
)

// GenID is a simple UnitID generator.
type GenID struct {
	last int
}

// New returns a fresh ID.
func (g *GenID) New() UnitID {
	g.last++
	return UnitID(g.last)
}

// callNoPanic calls the given function and catches any panic.
func callNoPanic(ctx context.Context, fn func(context.Context) error) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic: %v %s", r, debug.Stack())
		}
	}()
	return fn(ctx)
}

// MultiStartBundle calls StartBundle on multiple nodes. Convenience function.
func MultiStartBundle(ctx context.Context, id string, data DataManager, list ...Node) error {
	for _, n := range list {
		if err := n.StartBundle(ctx, id, data); err != nil {
			return err
		}
	}
	return nil
}

// MultiFinishBundle calls StartBundle on multiple nodes. Convenience function.
func MultiFinishBundle(ctx context.Context, list ...Node) error {
	for _, n := range list {
		if err := n.FinishBundle(ctx); err != nil {
			return err
		}
	}
	return nil
}

// IDs returns the unit IDs of the given nodes.
func IDs(list ...Node) []UnitID {
	var ret []UnitID
	for _, n := range list {
		ret = append(ret, n.ID())
	}
	return ret
}


text:
<!DOCTYPE html>

  <title>url-utils-interfaces</title>


text:
/**
 *
 */
package org.activiti.designer.features;

import org.activiti.designer.util.CloneUtil;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.IPasteContext;
import org.eclipse.graphiti.features.context.impl.AddContext;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.mm.pictograms.PictogramElement;
import org.eclipse.graphiti.ui.features.AbstractPasteFeature;

/**
 * Paste feature for flow elements.
 *
 * @author Tiese Barrell
 * @since 0.6.1
 * @version 1
 *
 */
public class PasteFlowElementFeature extends AbstractPasteFeature {

  public static final int PASTE_OFFSET = 25;

  public PasteFlowElementFeature(IFeatureProvider fp) {
    super(fp);
  }

  public boolean canPaste(IPasteContext context) {
    // only support pasting directly in the diagram (nothing else selected)
    PictogramElement[] pes = context.getPictogramElements();

    if (pes.length != 1 || !isPasteableContext(pes)) {
      return false;
    }

    // can paste, if all objects on the clipboard are Flow elements
    Object[] fromClipboard = getFromClipboard();
    if (fromClipboard == null || fromClipboard.length == 0) {
      return false;
    }
    for (Object object : fromClipboard) {
      if (!(object instanceof FlowElement)) {
        return false;
      }
    }
    return true;
  }

  private boolean isPasteableContext(PictogramElement[] pes) {
    return (pes[0] instanceof Diagram) || (pes[0] instanceof ContainerShape);
  }

  public void paste(IPasteContext context) {
    // we already verified, that we paste directly in the diagram
    PictogramElement[] pes = context.getPictogramElements();

    Diagram diagram = null;
    if (pes[0] instanceof Diagram) {
      diagram = (Diagram) pes[0];
    } else if (pes[0] instanceof ContainerShape) {
      ContainerShape shape = (ContainerShape) pes[0];
      diagram = (Diagram) shape.eContainer();
    }

    // get the FlowElement from the clipboard without copying them
    // (only copy the pictogram element, not the business object)
    // then create new pictogram elements using the add feature
    Object[] objects = getFromClipboard();
    for (Object object : objects) {
      AddContext ac = new AddContext();

      FlowElement clone = CloneUtil.clone((FlowElement) object, diagram);

      ac.setLocation(CopyFlowElementFeature.copyX + PASTE_OFFSET, CopyFlowElementFeature.copyY + PASTE_OFFSET);
      ac.setTargetContainer(diagram);
      addGraphicalRepresentation(ac, clone);
    }
  }
}


text:
# ifndef HashMap
# define HashMap

# define KeyType char*
# define ValueType int

/*
 this is useful for you in answering the questions. if your write your code such
 that you call stringHash1 when HASHING_FUNCTION==1 and stringHash2 when
 HASHING_FUNCTION==2 then you only need to change this value in order to switch
 hashing functions that your code uses. you are not required to use this value
 though.
 */
# define HASHING_FUNCTION 1

# define LOAD_FACTOR_THRESHOLD 0.75

struct hashLink
{
   KeyType key; /*the key is what you use to look up a hashLink*/
   ValueType value; /*the value stored with the hashLink, an int in our case*/
   struct hashLink *next; /*notice how these are like linked list nodes*/
};

typedef struct hashLink hashLink;

struct hashMap
{
    hashLink ** table; /*array of pointers to hashLinks*/
    int tableSize; /*number of buckets in the table*/
    int count; /*number of hashLinks in the table*/
};

typedef struct hashMap hashMap;

/*the first hashing function you can use*/
int stringHash1(char * str);

/*the second hashing function you can use*/
int stringHash2(char * str);

/*initialize the supplied hashMap struct*/
void initMap (struct hashMap * ht, int tableSize);

struct hashMap *createMap(int tableSize);

void freeMap (struct hashMap * ht);
/*
 free all memory used for your hashMap, but do not free the pointer to ht. you
 can see why this would not work by examining main(). the hashMap passed into
 your functions was never malloc'ed, so it can't be free()'ed either.
 */
void deleteMap(struct hashMap *ht);

/*
 insert the following values into a hashLink, you must create this hashLink but
 only after you confirm that this key does not already exist in the table. you
 cannot have two hashLinks for the word "taco".

 if a hashLink already exists in the table for the key provided you should
 replace that hashLink (really this only requires replacing the value v).
 */
void insertMap (struct hashMap * ht, KeyType k, ValueType v);

/*
 this returns a POINTER to the value stored in a hashLink specified by the key k.

 if the user supplies the key "taco" you should find taco in the hashTable, then
 return a pointer to the value member of the hashLink that represents taco. keep
 in mind we are storing an int for value, so you don't use malloc or anything.

 if the supplied key is not in the hashtable return NULL.
 */
ValueType* atMap (struct hashMap * ht, KeyType k);

/*
 a simple yes/no if the key is in the hashtable. 0 is no, all other values are
 yes.
 */
int containsKey (struct hashMap * ht, KeyType k);

/*
 find the hashlink for the supplied key and remove it, also freeing the memory
 for that hashlink. it is not an error to be unable to find the hashlink, if it
 cannot be found do nothing (or print a message) but do not use an assert which
 will end your program.
 */
void removeKey (struct hashMap * ht, KeyType k);

/*
 returns the number of hashLinks in the table
 */
int size (struct hashMap *ht);

/*
 returns the number of buckets in the table
 */
int capacity(struct hashMap *ht);

/*
 returns the number of empty buckets in the table, these are buckets which have
 no hashlinks hanging off of them.
 */
int emptyBuckets(struct hashMap *ht);

/*
 returns the ratio of: (number of hashlinks) / (number of buckets)

 this value can range anywhere from zero (an empty table) to more then 1, which
 would mean that there are more hashlinks then buckets (but remember hashlinks
 are like linked list nodes so they can hang from each other)
 */
float tableLoad(struct hashMap *ht);

void printMap (struct hashMap * ht);

void printValue(ValueType v);

# endif


text:
/*
 * Created on Feb 16, 2007
 */
package edu.wustl.common.util.tag;

/**
 * @author Santosh Chandak
 * JSP tag for Autocomplete feature. The body of this tag is executed once for every call of the tag
 * when the page is rendered.
 * To use this tag, include AutocompleterCommon.jsp in your page
 */

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.util.global.Constants;

public class AutoCompleteTag extends TagSupport
{
	/**
	 * version ID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * property on which Autocompleter is to be applied
	 */
	private String property;

	/**
	 * Object containing values of the dropdown. Supported datatypes
	 * 1. String Array 2. List of Name Value Beans
	 *
	 */
	private Object optionsList;

	/**
	 * Default style
	 */
	private String styleClass = "formFieldSized15";

	/**
	 * Number of results to be shown
	 */
	private String numberOfResults = "10";

	/**
	 * Trigger matching when user enters these number of characters
	 */
	private String numberOfCharacters = "1";

	/**
	 * set to true if the textbox is readOnly
	 */
	private Object readOnly = "false";

	/**
	 * set to true if the textbox is disabled
	 */
	private Object disabled = "false";

	/**
	 * Functions to be called when textbox loses focus
	 */
	private String onChange = "";

	/**
	 * initial value in the textbox, this is compulsary attribute
	 */
	private Object initialValue = "";

	/**
	 * if the property is dependent on some other property
	 * eg. type depends on class
	 *
	 */
	private String dependsOn = "";

	/**
	 * size
	 */
	private String size = "300";

	/**
	 *  true - in case of static lists eg. class, type
	 *  false - in case of dynamic lists eg. site, user
	 */
	private String staticField = "true";

	/**
	 * A call back function, which gets executed by JSP runtime when opening tag
	 * for this custom tag is encountered.
	 */
	public int doStartTag() throws JspException
	{

		try {
			JspWriter out = pageContext.getOut();
			String autocompleteHTMLStr=null;
			if(staticField.equalsIgnoreCase("true"))
			{
			autocompleteHTMLStr = getAutocompleteHTML();
			}
			else
			{
				autocompleteHTMLStr = getAutocompleteHTMLForDynamicProperty();
			}

			  /**
			    *  Clearing the variables
			    */
			   onChange = "";
			   initialValue = "";
			   readOnly = "false";
			   dependsOn = "";
			   size="300";
			   disabled="false";

			out.print(autocompleteHTMLStr);

		} catch (IOException ioe) {
			throw new JspTagException("Error:IOException while writing to the user");
		}

		return SKIP_BODY;
	}

	@SuppressWarnings("unchecked")
	private String getAutocompleteHTML() {
	    String autoCompleteResult = "";

	    prepareCommonData();

		/**
		 *  Always pass the function with brackets, appending '()' will not be done
		 */

			if(onChange.equals(""))
			{
				onChange = "trimByAutoTag(this)";
			}
			else
			{
				onChange = "trimByAutoTag(this);" + onChange;
			}
	    String div = "divFor" + property;
	    autoCompleteResult += "
";
	    autoCompleteResult += "
";
	    autoCompleteResult += "<input type=\"text\" class=\"" + styleClass + "\" value=\"" + initialValue + "\"size=\"" + size + "\" id=\"" + property + "\" name=\"" + property + "\"" + "onmouseover=\"showTip(this.id)\" onmouseout=\"hideTip(this.id)\"";

	    if (readOnly.toString().equalsIgnoreCase("true"))
	    {
			autoCompleteResult += "readonly";
		} else
		{
			autoCompleteResult += "onblur=\"" + onChange + "\"";
		}

	    autoCompleteResult += "/>";
	    String nameOfArrow = property + "arrow";
	    autoCompleteResult += "<image id='" + nameOfArrow + "' src='images/autocompleter.gif'/>";
	    autoCompleteResult += "";

       return autoCompleteResult;
	}

	@SuppressWarnings("unchecked")
	private void prepareCommonData() {
		if(initialValue == null || initialValue.equals(""))
	    {
	    	initialValue = pageContext.getRequest().getParameter(property);

	    	 if(initialValue == null || initialValue.equals(""))
	 	    {
	    	  String[] title = (String[])
	    	  pageContext.getRequest().getParameterValues(property);

	    	  if (title != null && title.length > 0) { if (title[0] != null) {
	    	  initialValue = title[0]; } }

	 	    }
	    }
		if (initialValue == null) {
			initialValue = "";
		}

		/**
		 *  As Type depends on class, get the optionsList as List from optionsList which was passed as a map
		 */
		if(property.equalsIgnoreCase(Constants.SPECIMEN_TYPE) && dependsOn!=null && !dependsOn.equals(""))
		{
			 String className = dependsOn;
			 List specimenTypeList = (List) ((Map)optionsList).get(className);
			 optionsList = specimenTypeList;
	    }

		/**
		 *  Converting other data types to list of Name Value Beans
		 */

		if (optionsList instanceof String[]) {
			String[] stringArray = (String[]) optionsList;
			List tempNVBList = new ArrayList();
			if(stringArray!=null)
			{
				for(int i=0;i<stringArray.length;i++)
				{
					tempNVBList.add(new NameValueBean(stringArray[i],stringArray[i]));
				}
			}
			optionsList = tempNVBList;
		}

		if (optionsList instanceof List) {

			List nvbList = (List) optionsList;
			if (nvbList != null && nvbList.size() > 0) {

					// TODO other than NVB
					NameValueBean nvb1 = (NameValueBean) nvbList.get(0);
					if (nvb1.getName().equals(Constants.SELECT_OPTION)) {
						nvbList.remove(0);
					}

			}
			/* if(nvbList == null || nvbList.size() == 0)
			{
				initialValue = "No Records Present"; // needed?
			}  */
	}

	}

	/**
	 * This function prepares the HTML to be rendered
	 * @return String - containing HTML to be rendered
	 *
	 */
	@SuppressWarnings("unchecked")
	private String getAutocompleteHTMLForDynamicProperty() {
	    String autoCompleteResult = "";
	    String displayProperty = "display" + property;
	    prepareCommonData();

		/**
		 *  Always pass the function with brackets, appending '()' will not be done
		 */

		if(onChange.equals(""))
		{
			onChange = "trimByAutoTagAndSetIdInForm(this)";
		}
		else
		{
			onChange = "trimByAutoTagAndSetIdInForm(this);" + onChange;
		}
		String name = "";
		if(initialValue.equals("0") || initialValue.toString().equalsIgnoreCase("undefined") || initialValue.equals(""))
		{
			name = pageContext.getRequest().getParameter(displayProperty);

	    	 if(name == null || name.equals(""))
	 	    {
	    	  String[] title = (String[])
	    	  pageContext.getRequest().getParameterValues(displayProperty);

	    	  if (title != null && title.length > 0) { if (title[0] != null) {
	    		  name = title[0]; } }

	 	    }
		}

		if(name == null)
		{
			name = "";
		}
		String value = "";
		if (optionsList instanceof List) {

			List nvbList = (List) optionsList;

			for(int i=0;i<nvbList.size();i++)
			{
				NameValueBean nvb1 = (NameValueBean) nvbList.get(i);
				if(nvb1.getValue().equals(initialValue))
				{
					name = nvb1.getName();
					value = nvb1.getValue();
					break;
				}
			}

	}

	    String div = "divFor" + displayProperty;
	    autoCompleteResult += "
";
	    autoCompleteResult += "
";
	    autoCompleteResult += "<input type=\"text\" class=\"" + styleClass + "\" value=\"" + name + "\"size=\"" + size + "\" id=\"" + displayProperty + "\" name=\"" + displayProperty + "\"" + "onmouseover=\"showTip(this.id)\" onmouseout=\"hideTip(this.id)\"";

	    if (readOnly.toString().equalsIgnoreCase("true"))
	    {
			autoCompleteResult += "readonly";
		} else
		{
			autoCompleteResult += "onblur=\"" + onChange + "\"";
		}

	    if (disabled.toString().equalsIgnoreCase("true"))
	    {
			autoCompleteResult += "disabled=\"true\"";
		}

	    autoCompleteResult += "/>";
	    String nameOfArrow = property + "arrow";
	    autoCompleteResult += "<image id='" + nameOfArrow + "' src='images/autocompleter.gif'/>";
	    autoCompleteResult += "<input type=\"hidden\" id=\"" + property + "\" name=\"" + property + "\"value=\"" + value + "\"/>";
	    autoCompleteResult += "";

       return autoCompleteResult;
	}

	/**
     * A call back function
     */
	public int doEndTag() throws JspException
	{
		return EVAL_PAGE;
	}

	/**
	 * @return
	 */
	public String getNumberOfCharacters() {
		return numberOfCharacters;
	}

	/**
	 * @param numberOfCharacters
	 */
	public void setNumberOfCharacters(String numberOfCharacters) {
		this.numberOfCharacters = numberOfCharacters;
	}

	/**
	 * @return
	 */
	public String getNumberOfResults() {
		return numberOfResults;
	}

	/**
	 * @param numberOfResults
	 */
	public void setNumberOfResults(String numberOfResults) {
		this.numberOfResults = numberOfResults;
	}

	/**
	 * @return
	 */
	public Object getOptionsList() {
		return optionsList;
	}

	/**
	 * @param optionsList
	 */
	public void setOptionsList(Object optionsList) {
		this.optionsList = optionsList;
	}

	/**
	 * @return
	 */
	public String getProperty() {
		return property;
	}

	/**
	 * @param property
	 */
	public void setProperty(String property) {
		this.property = property;
	}

	/**
	 * @return
	 */
	public String getSize() {
		return size;
	}

	/**
	 * @param size
	 */
	public void setSize(String size) {
		this.size = size;
	}

	/**
	 * @return
	 */
	public String getStyleClass() {
		return styleClass;
	}

	/**
	 * @param styleClass
	 */
	public void setStyleClass(String styleClass) {
		this.styleClass = styleClass;
	}

	public Object getInitialValue() {
		return initialValue;
	}

	public void setInitialValue(Object initialValue) {
		if (initialValue != null) {
			this.initialValue = initialValue.toString();
		}
	}

	/**
	 * @return Returns the onChange.
	 */
	public String getOnChange() {
		return onChange;
	}

	/**
	 * @param onChange The onChange to set.
	 */
	public void setOnChange(String onChange) {
		this.onChange = onChange;
	}

	/**
	 * @return Returns the readOnly.
	 */
	public Object getReadOnly() {
		return readOnly;
	}

	/**
	 * @param readOnly The readOnly to set.
	 */
	public void setReadOnly(Object readOnly) {
		this.readOnly = readOnly;
	}

	/**
	 * @return Returns the dependsOn.
	 */
	public String getDependsOn() {
		return dependsOn;
	}

	/**
	 * @param dependsOn The dependsOn to set.
	 */
	public void setDependsOn(String dependsOn) {
		this.dependsOn = dependsOn;
	}

	/**
	 * @return Returns the staticField.
	 */
	public String getStaticField() {
		return staticField;
	}

	/**
	 * @param staticField The staticField to set.
	 */
	public void setStaticField(String staticField) {
		this.staticField = staticField;
	}

	/**
	 * @return Returns the disabled.
	 */
	public Object getDisabled() {
		return disabled;
	}

	/**
	 * @param disabled The disabled to set.
	 */
	public void setDisabled(Object disabled) {
		this.disabled = disabled;
	}

}


text:
import tkinter as tk
from tkinter import ttk

import postgresql
import wget
from os.path import isfile, join
from cosmo.tools import simple_form
from cosmo.tools import empty

def conectadb():
    user = "dof_read"
    passwd = "eU9Za2ofNGfGUGe8"
    server = "bbdd.cmima.csic.es"
    datab = "dof"
    db = postgresql.open("pq://"+user+":"+passwd+"@"+server+"/"+datab)
    db.connect()
    return db

# A partir d'un nom d'experiment i del conector a la db recuperem les
# boies
def get_buoys_from_exp(db,name):
    query = "SELECT a.name FROM d_experiment as a INNER JOIN drifter_exp_test as b ON b.id = a.exp_id " \
            "WHERE b.name='CONECTA-2016' ORDER by a.id"
    ps = db.prepare(query)
    items = [ps()[i][0] for i in range(len(ps()))]
    return items

# Recuperem tots els experiment fets a l'ICM
def get_exp(db):
    query = "SELECT * FROM drifter_exp_test ORDER by id"
    ps = db.prepare(query)
    items = [list(ps()[i][:]) for i in range(len(ps()))]
    return items

def select_exp():
# =================

  # Connect to DB
  # Obtain experiments
  DB = conectadb()
  a = get_exp(DB)

  DBNAME = tk.StringVar()
  URL = tk.StringVar()

  BDLIST = []
  URLIST = []
  for i in range(len(a)):
    BDLIST.append(a[i][1])
    URLIST.append(a[i][8])

  DBNAME.set(BDLIST[0])
  URL.set(URLIST[0])

  a = get_buoys_from_exp(DB,DBNAME.get())
  FLIST = []
  for i in range(len(a)):
    FLIST.append(join(URL.get(),a[i]+'.geojson'))

  def _cancel():
  # ===========
    FLIST  = []
    win.destroy()

  def _get():
  # ===========
    out = tk.filedialog.askdirectory(parent=win,title='Target folder')

    #out = simple_form('Output folder for download files','path','./')
    if empty(out):
      out = None
    for i in range(len(FLIST)):
      bb = wget.download(FLIST[i],out=out)

  def _done():
  # ===========
    win.destroy()

  def _selection():
  # ===============
    i = BDLIST.index(DBNAME.get())
    URL.set(URLIST[i])
    a = get_buoys_from_exp(DB,DBNAME.get())
    FLIST = []
    for i in range(len(a)):
      FLIST.append(join(URL.get(),a[i]+'.geojson'))

  win = tk.Toplevel()
  win.title('Database Selector')
  win.resizable(False,False)
  win.protocol('WM_DELETE_WINDOW',_cancel)

  F0 = ttk.Frame(win,padding=5)
  _source = ttk.Combobox(F0,textvariable=DBNAME, \
                         values=BDLIST,width=20)
  _source.grid(row=0,column=0,columnspan=2,padx=3)
  _source.bind('<<ComboboxSelected>>',lambda e: _selection())
  _entry = ttk.Entry(F0,textvariable=URL,width=60)
  _entry.grid(row=0,column=2,columnspan=6,padx=3)
  _entry.configure(state='readonly')
  ttk.Button(F0,text='Cancel',command=_cancel).grid(row=1,column=3,padx=0)
  ttk.Button(F0,text='Download a copy',command=_get).grid(row=1,column=4,columnspan=3,padx=0)
  ttk.Button(F0,text='Done',command=_done).grid(row=1,column=7,padx=0)
  F0.grid()

  win.wait_window(win)
  return FLIST


text:
// Header for CPropCalendarServer class

#ifndef __CPropCalendarServer__MULBERRY__
#define __CPropCalendarServer__MULBERRY__

#include "CCalendarPropPanel.h"

// Constants

// Panes
const	PaneIDT		paneid_PropCalendarServer = 1843;
const	PaneIDT		paneid_CalendarServerState = 'ICON';
const	PaneIDT		paneid_CalendarServerName = 'NAME';
const	PaneIDT		paneid_CalendarServerType = 'TYPE';
const	PaneIDT		paneid_CalendarServerGreeting = 'GRET';
const	PaneIDT		paneid_CalendarServerCapability = 'CAPS';
const	PaneIDT		paneid_CalendarServerConnectionTitle = 'CONT';
const	PaneIDT		paneid_CalendarServerConnection = 'CONN';
const	PaneIDT		paneid_CalendarServerViewCert = 'CERT';

// Resources
const ResIDT	RidL_CPropCalendarServerBtns = 1843;

// Mesages
const	MessageT	msg_CalendarServerViewCert = 'CERT';

// Classes
class CTextDisplay;
class CTextFieldX;
class LIconControl;
class LPushButton;
class LIconControl;
class LStaticText;

class CPropCalendarServer : public CCalendarPropPanel,
								public LListener
{
private:
	LIconControl*		mIconState;
	CTextFieldX*		mName;
	CTextFieldX*		mType;
	CTextDisplay*		mGreeting;
	CTextDisplay*		mCapability;
	LStaticText*		mConnectionTitle;
	CTextFieldX*		mConnection;
	LPushButton*		mViewCert;

	calstore::CCalendarProtocol*	mProto;

public:
	enum { class_ID = 'CSer' };

					CPropCalendarServer(LStream *inStream);
	virtual 		~CPropCalendarServer();

	virtual void	ListenToMessage(MessageT inMessage, void *ioParam);

	virtual void	SetCalList(calstore::CCalendarStoreNodeList* cal_list);		// Set cal list
	virtual void	SetProtocol(calstore::CCalendarProtocol* proto);			// Set protocol
	virtual void	ApplyChanges(void);						// Force update of mboxes

protected:
	virtual void	FinishCreateSelf(void);					// Do odds & ends

			void	OnViewCert();
};

#endif


text:
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/practices/2013/entlib/semanticlogging/etw">

  <traceEventService sessionNamePrefix="Microsoft.SemanticLogging.Etw.Diff1" />

  <sinks>
    <flatFileSink name="FlatFileEventListener1" fileName="FlatFile.log">
      <sources>
        <eventSource name="Test" level="Error" matchAnyKeyword="1"/>
        <eventSource name="Diff2" level="Error" matchAnyKeyword="1"/>
      </sources>
      <eventTextFormatter header="Dif3" footer="" verbosityThreshold="Verbose" dateTimeFormat="o"/>
    </flatFileSink>
  </sinks>

</configuration>


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Hospname;

/**
 * HospnameSearch represents the model behind the search form about `frontend\models\Hospname`.
 */
class HospnameSearch extends Hospname {

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['id'], 'integer'],
            [['hospname'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios() {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params) {
        $query = Hospname::find()->orderBy(['(id)' => SORT_DESC]);

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' =>
            [
                'pageSize' => 7,
            ]
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
        ]);

        $query->andFilterWhere(['like', 'hospname', $this->hospname]);

        return $dataProvider;
    }

}


text:
#pragma once
#include <string>

namespace schrodinger
{
namespace mae
{

const char* const MAE_FORMAT_VERSION = "s_m_m2io_version";
const char* const CT_BLOCK = "f_m_ct";
const char* const CT_TITLE = "s_m_title";
const char* const ATOM_BLOCK = "m_atom";
const char* const ATOM_ATOMIC_NUM = "i_m_atomic_number";
const char* const ATOM_X_COORD = "r_m_x_coord";
const char* const ATOM_Y_COORD = "r_m_y_coord";
const char* const ATOM_Z_COORD = "r_m_z_coord";
const char* const ATOM_FORMAL_CHARGE = "i_m_formal_charge";
const char* const ATOM_PARTIAL_CHARGE = "r_m_charge1";
const char* const BOND_BLOCK = "m_bond";
const char* const BOND_ATOM_1 = "i_m_from";
const char* const BOND_ATOM_2 = "i_m_to";
const char* const BOND_ORDER = "i_m_order";
const char* const DEPEND_BLOCK = "m_depend";

/**
 * These are the prefixes used to store stereochemical properties in Maestro
 * files. Each of those properties will be associated to one of these prefixes
 * plus an integer (integers don't have any particular meaning, they just
 * prevent the property names from clashing), e.g.:
 *
 * s_st_Chirality_1 :        2_R_1_3_5_4
 * s_st_Chirality_2 :        6_ANR_1_5_7
 *
 * Syntax of chirality and pseudochirality properties is the same:
 *  1. Index of the chiral/pseudochiral atom.
 *  2. Chiral/pseudochiral label (R/S or ANR/ANS).
 *  3. Sequence of atoms around the chiral one, ordered by decreasing
 *     Cahn-Ingold-Prelog rank, or atom index, in the case of ANR/ANS.
 *  Elements are separated by underscores. For cases in which only 3 neighboring
 *  indexes are specified, an implicit Hydrogen atom needs to be considered.
 *
 *
 * s_st_EZ_2 :               1_2_3_4_E
 *
 * Syntax for bond stereochemistry properties is similar:
 *  1. Highest C-I-P ranked stereogenical atom at one side of the group.
 *  2. List of intermediate atoms in the stereochemical group. These are
 *     typically 2 atoms bonded by a double bond, but can be more atoms and not
 *     necessarily bonded by double bonds (e.g. in case of allenes or
 *     allene-like structures)
 *  3. Highest C-I-P ranked stereogenical atom at the other side of the group.
 *  4. Stereochemical label for the bond (E/Z)
 *  As in chiral/pseudochiral properties, values are separated by underscores.
 */
const std::string CT_CHIRALITY_PROP_PREFIX = "s_st_Chirality_";
const std::string CT_EZ_PROP_PREFIX = "s_st_EZ_";

/**
 * This prefix has been deprecated, and will not be used in future Schrodinger
 * Suite releases. It is included in this header only for the purpose of
 * documentation and backwards compatibility. The format of the property string
 * is identical as the one presented in the example for chirality.
 */
const std::string CT_PSEUDOCHIRALITY_PROP_PREFIX = "s_st_AtomNumChirality_";

} // End namespace mae
} // End namespace schrodinger


text:
@interface SDLShowConstantTBT : SDLRPCRequest {}

-(id) init;
-(id) initWithDictionary:(NSMutableDictionary*) dict;

@property(strong) NSString* navigationText1;
@property(strong) NSString* navigationText2;
@property(strong) NSString* eta;
@property(strong) NSString* timeToDestination;
@property(strong) NSString* totalDistance;
@property(strong) SDLImage* turnIcon;
@property(strong) SDLImage* nextTurnIcon;
@property(strong) NSNumber* distanceToManeuver;
@property(strong) NSNumber* distanceToManeuverScale;
@property(strong) NSNumber* maneuverComplete;
@property(strong) NSMutableArray* softButtons;

@end


text:
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Publisher(models.Model):
    """
    An application publisher.
    """

    name = models.CharField(max_length=80)

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Department(models.Model):
    """
    An application category.
    """

    name = models.CharField(max_length=40)

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Keyword(models.Model):
    """
    A descriptive keyword.
    """

    name = models.CharField(max_length=40)

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Application(models.Model):
    """
    An Ubuntu Touch application.
    """

    # Although an integer would make a better primary key, the identity of the
    # app is literally tied to this identifier, which is guaranteed to be unique
    name = models.CharField(
        max_length=100,
        primary_key=True,
    )

    icon_url = models.ImageField(upload_to='apps/icons')

    title = models.CharField(max_length=100)
    version = models.CharField(max_length=20)
    description = models.TextField()
    license = models.CharField(max_length=40)

    website = models.URLField()
    download_url = models.URLField()
    download_size = models.PositiveIntegerField()

    publisher = models.ForeignKey(Publisher)
    department = models.ForeignKey(Department)
    keywords = models.ManyToManyField(Keyword)

    rating = models.PositiveSmallIntegerField()

    last_updated = models.DateTimeField()
    date_published = models.DateTimeField()

    def __str__(self):
        return self.title

@python_2_unicode_compatible
class Screenshot(models.Model):
    """
    A screenshot for an application.
    """

    application = models.ForeignKey(Application)
    image = models.ImageField(upload_to='apps/screenshots')

    def __str__(self):
        return self.application.title


text:
"""
Minimal example of the CEFBrowser widget use. Here you don't have any controls
(back / forth / reload) or whatsoever. Just a kivy app displaying the
chromium-webview.
"""

from kivy.app import App
from kivy.garden.cefpython import CEFBrowser

if __name__ == '__main__':
    class SimpleBrowserApp(App):
        def build(self):
            return CEFBrowser(url="http://jegger.ch/datapool/app/test_input.html")

    SimpleBrowserApp().run()