text:
from cmdtree.parser import AParser

def _mk_cmd_node(cmd_name, cmd_obj):
    return {
        "name": cmd_name,
        "cmd": cmd_obj,
        "children": {}
    }

class CmdTree(object):
    """
    A tree that manages the command references by cmd path like
    ['parent_cmd', 'child_cmd'].
    """

    def __init__(self, root_parser=None):
        """
        :type root_parser: cmdtree.parser.AParser
        """
        if root_parser is not None:
            self.root = root_parser
        else:
            self.root = AParser()
        self.tree = {
            "name": "root",
            "cmd": self.root,
            "children": {}
        }

    def get_cmd_by_path(self, existed_cmd_path):
        """
        :return:
        {
            "name": cmd_name,
            "cmd": Resource instance,
            "children": {}
        }
        """
        parent = self.tree
        for cmd_name in existed_cmd_path:
            try:
                parent = parent['children'][cmd_name]
            except KeyError:
                raise ValueError(
                    "Given key [%s] in path %s does not exist in tree."
                    % (cmd_name, existed_cmd_path)
                )
        return parent

    def _add_node(self, cmd_node, cmd_path):
        """
        :type cmd_path: list or tuple
        """
        parent = self.tree
        for cmd_key in cmd_path:
            if cmd_key not in parent['children']:
                break
            parent = parent['children'][cmd_key]
        parent["children"][cmd_node['name']] = cmd_node
        return cmd_node

    @staticmethod
    def _get_paths(full_path, end_index):
        if end_index is None:
            new_path, existed_path = [], full_path
        else:
            new_path, existed_path = full_path[end_index:], full_path[:end_index]
        return new_path, existed_path

    def add_commands(self, cmd_path, func, help=None):
        cmd_name = cmd_path[-1]
        parent = self.add_parent_commands(cmd_path[:-1])
        sub_command = parent['cmd'].add_cmd(name=cmd_name, func=func, help=help)
        node = _mk_cmd_node(cmd_name, sub_command)
        self._add_node(node, cmd_path=cmd_path)
        return sub_command

    def add_parent_commands(self, cmd_path, help=None):
        """
        Create parent command object in cmd tree then return
        the last parent command object.
        :rtype: dict
        """
        existed_cmd_end_index = self.index_in_tree(cmd_path)
        new_path, existed_path = self._get_paths(
            cmd_path,
            existed_cmd_end_index,
        )
        parent_node = self.get_cmd_by_path(existed_path)

        last_one_index = 1
        new_path_len = len(new_path)
        _kwargs = {}
        for cmd_name in new_path:
            if last_one_index >= new_path_len:
                _kwargs['help'] = help
            sub_cmd = parent_node['cmd'].add_cmd(
                cmd_name, **_kwargs
            )
            parent_node = _mk_cmd_node(cmd_name, sub_cmd)
            self._add_node(
                parent_node,
                existed_path + new_path[:new_path.index(cmd_name)]
            )
            last_one_index += 1
        return parent_node

    def index_in_tree(self, cmd_path):
        """
        Return the start index of which the element is not in cmd tree.
        :type cmd_path: list or tuple
        :return: None if cmd_path already indexed in tree.
        """
        current_tree = self.tree
        for key in cmd_path:
            if key in current_tree['children']:
                current_tree = current_tree['children'][key]
            else:
                return cmd_path.index(key)
        return None


text:
#include "tcl.h"
#include "sqlite3ext.h"

#ifndef SQLITE_OMIT_LOAD_EXTENSION
static SQLITE_EXTENSION_INIT1

/*
** The sqr() SQL function returns the square of its input value.
*/
static void sqrFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double r = sqlite3_value_double(argv[0]);
  sqlite3_result_double(context, r*r);
}

/*
** This is the entry point to register the extension for the sqr() function.
*/
static int sqr_init(
  sqlite3 *db,
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
  sqlite3_create_function(db, "sqr", 1, SQLITE_ANY, 0, sqrFunc, 0, 0);
  return 0;
}

/*
** The cube() SQL function returns the cube of its input value.
*/
static void cubeFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  double r = sqlite3_value_double(argv[0]);
  sqlite3_result_double(context, r*r*r);
}

/*
** This is the entry point to register the extension for the cube() function.
*/
static int cube_init(
  sqlite3 *db,
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi);
  sqlite3_create_function(db, "cube", 1, SQLITE_ANY, 0, cubeFunc, 0, 0);
  return 0;
}

/*
** This is a broken extension entry point
*/
static int broken_init(
  sqlite3 *db,
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  char *zErr;
  SQLITE_EXTENSION_INIT2(pApi);
  zErr = sqlite3_mprintf("broken autoext!");
  *pzErrMsg = zErr;
  return 1;
}

/*
** tclcmd:   sqlite3_auto_extension_sqr
**
** Register the "sqr" extension to be loaded automatically.
*/
static int autoExtSqrObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)sqr_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

/*
** tclcmd:   sqlite3_auto_extension_cube
**
** Register the "cube" extension to be loaded automatically.
*/
static int autoExtCubeObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)cube_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

/*
** tclcmd:   sqlite3_auto_extension_broken
**
** Register the broken extension to be loaded automatically.
*/
static int autoExtBrokenObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  int rc = sqlite3_auto_extension((void*)broken_init);
  Tcl_SetObjResult(interp, Tcl_NewIntObj(rc));
  return SQLITE_OK;
}

#endif /* SQLITE_OMIT_LOAD_EXTENSION */

/*
** tclcmd:   sqlite3_reset_auto_extension
**
** Reset all auto-extensions
*/
static int resetAutoExtObjCmd(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
  Tcl_Obj *CONST objv[]
){
  sqlite3_reset_auto_extension();
  return SQLITE_OK;
}

/*
** This procedure registers the TCL procs defined in this file.
*/
int Sqlitetest_autoext_Init(Tcl_Interp *interp){
#ifndef SQLITE_OMIT_LOAD_EXTENSION
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_sqr",
          autoExtSqrObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_cube",
          autoExtCubeObjCmd, 0, 0);
  Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_broken",
          autoExtBrokenObjCmd, 0, 0);
#endif
  Tcl_CreateObjCommand(interp, "sqlite3_reset_auto_extension",
          resetAutoExtObjCmd, 0, 0);
  return TCL_OK;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace RR\RestaurantBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class HoraireType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('ouverture1')
            ->add('fermeture1')
            ->add('ouverture2')
            ->add('fermeture2')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'RR\RestaurantBundle\Entity\Horaire'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'rr_restaurantbundle_horaire';
    }
}


text:
#pragma once

#include <iostream>
#include <string>
#include <mraa/aio.h>

namespace upm {
  /**
   * @brief GP2Y0A-based IR Proximity Sensors
   * @defgroup gp2y0a libupm-gp2y0a
   * @ingroup seeed analog light
   */

  /**
   * @library gp2y0a
   * @sensor gp2y0a
   * @comname Analog Infrared (IR) Based Distance Sensor
   * @altname Grove 80cm IR Proximity Sensor
   * @type light
   * @man seeed
   * @con analog
   * @web http://wiki.seeed.cc/Grove-80cm_Infrared_Proximity_Sensor/
   *
   * @brief API for the GP2Y0A family of IR Proximity Sensors
   *
   * Sensors of this family return an analog voltage corresponding to the distance
   * of an object from the sensor. The voltage is lower when objects
   * are far away; the voltage increases as objects get closer
   * to the sensor.
   *
   * @image html gp2y0a.jpg
   * @snippet gp2y0a.cxx Interesting
   */
  class GP2Y0A {
  public:

    /**
     * GP2Y0A sensor constructor
     *
     * @param pin Analog pin to use
     */
    GP2Y0A(int pin);

    /**
     * GP2Y0A destructor
     */
    ~GP2Y0A();

    /**
     * Gets an average voltage value from the sensor
     *
     * @param aref Reference voltage in use (usually 5.0V or 3.3V)
     * @param samples Number of samples to average over
     * @return Average voltage reading
     */
    float value(float aref, uint8_t samples);

  private:
    mraa_aio_context m_aio;
    // ADC resolution
    int m_aRes;
  };
}


text:
@interface BlocksTableViewController : TLTableViewController

@end


text:
"""
Procfs for SunOS.

"""

import os
import struct

from pycopia.aid import sortedlist

# from man -s 4 proc
#     typedef struct psinfo {
#          int pr_flag;              /* process flags */
#          int pr_nlwp;              /* number of lwps in the process */
#          pid_t pr_pid;             /* process id */
#          pid_t pr_ppid;            /* process id of parent */
#          pid_t pr_pgid;            /* process id of process group leader */
#          pid_t pr_sid;             /* session id */
#          uid_t pr_uid;             /* real user id */
#          uid_t pr_euid;            /* effective user id */
#          gid_t pr_gid;             /* real group id */
#          gid_t pr_egid;            /* effective group id */
#          uintptr_t pr_addr;        /* address of process */
#          size_t pr_size;           /* size of process image in Kbytes */
#          size_t pr_rssize;         /* resident set size in Kbytes */
#          dev_t pr_ttydev;          /* controlling tty device (or PRNODEV) */
#          ushort_t pr_pctcpu;       /* % of recent cpu time used by all lwps */
#          ushort_t pr_pctmem;       /* % of system memory used by process */
#          timestruc_t pr_start;     /* process start time, from the epoch */
#          timestruc_t pr_time;      /* cpu time for this process */
#          timestruc_t pr_ctime;     /* cpu time for reaped children */
#          taskid_t pr_taskid;       /* task id */
#          projid_t pr_projid;       /* project id */
#          char pr_fname[PRFNSZ];    /* name of exec'ed file */
#          char pr_psargs[PRARGSZ];  /* initial characters of arg list */
#          int pr_wstat;             /* if zombie, the wait() status */
#          int pr_argc;              /* initial argument count */
#          uintptr_t pr_argv;        /* address of initial argument vector */
#          uintptr_t pr_envp;        /* address of initial environment vector */
#          char pr_dmodel;           /* data model of the process */
#          lwpsinfo_t pr_lwp;        /* information for representative lwp */
#     } psinfo_t;

class ProcStat(object):
    """Status information about a process. """
    _FF = "/proc/%d/psinfo"
    _STATINDEX = {
    "command": 0,
    "pid": 1,
    "ppid": 2,
    "pgid": 3,
    "sid": 4,
    "ctty": 5,
    "flags": 6,
    "start": 7,
    "ut": 8,
    "st": 9,
    "wchan": 10,
    "euid": 11,
    "ruid": 12,
    "groups": 13,
    }

    def __init__(self, pid=None):
        self.pid = None
        self.read(pid)

    # so sorting works
    def __lt__(self, other):
        return self.pid < other.pid

    def __gt__(self, other):
        return self.pid > other.pid

    def __eq__(self, other):
        return self.pid == other.pid

    def _toint(self, it):
        try:
            return int(it)
        except ValueError:
            return it

    def reread(self):
        self.read(self.pid)
        return self

    def read(self, pid=None):
        if pid is not None:
            self.pid = int(pid)
        if self.pid is not None:
            try:
                self.stats = self._get_psinfo(pid)
            except IOError: # no such process
                self.pid = None
                self.stats = None
        else:
            self.stats = None
        return self

    def _get_psinfo(self, pid):
        return None # XXX

    def statestr(self):
        return NotImplemented

    def RSS(self):
        return NotImplemented

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self.pid)

    def __str__(self):
        if self.stats is None:
            return "no stats - invalid pid?"
        else:
            s = ["%15s: %s" % ("cmdline", self.get_cmdline())]
            names = self._STATINDEX.keys()
            names.sort()
            #for name, i in self._STATINDEX.items():
            for name in names:
                i = self._STATINDEX[name]
                s.append("%15s: %s" % (name, self.stats[i]))
            return "\n".join(s)

    def get_attributes(self):
        return NotImplemented

    def get_cmdline(self):
        return NotImplemented
    cmdline = property(get_cmdline, None, None, "Command line")

#   ttyname = property(_get_ttyname, None, None, None)

    def get_stat(self, name):
        if not self.stats:
            raise ValueError, "no stats - run read(pid)"
        try:
            return self.stats[self._STATINDEX[name]]
        except KeyError:
            raise ValueError, "no attribute %s" % name

    def __getattr__(self, name):
        try:
            return self.get_stat(name)
        except ValueError, err:
            raise AttributeError, err

    def __getitem__(self, name):
        try:
            return getattr(self, name)
        except AttributeError, err:
            raise KeyError, err

class ProcStatTable(object):
    """ProcStatTable()
A collection of all processes running, like the standard 'ps' command. """
    def __init__(self, fmt="%(pid)6s %(ppid)6s %(ttyname)6.6s %(cmdline).55s"):
        self.fmt = fmt
        self._ptable = None

    def read(self):
        rv = self._ptable = {}
        for pfile in os.listdir("/proc"):
            try:
                pid = int(pfile) # filter out non-numeric entries in /proc
            except ValueError:
                continue
            rv[pid] = ProcStat(pid)

    def __len__(self):
        return len(self._ptable)

    def __getitem__(self, pid):
        return self._ptable[pid]

    def __iter__(self):
        return self._ptable.itervalues()

    def __repr__(self):
        return "%s(%r)" % (self.__class__.__name__, self.fmt)

    def __str__(self):
        self.read()
        s = []
        k = self._ptable.keys()
        k.sort()
        for pid in k:
            s.append(self.fmt % self._ptable[pid])
        return "\n".join(s)

    # this is here because $#%@# FreeBSD ps can't print a tree of procs (a
    # helpful debugging aid)
    def tree(self):
        class _pholder:
            pass
        self.read()
        if not self._ptable.has_key(0):
            p0 = self._ptable[0] = _pholder()
            p0.pid = p0.ppid = 0
            p0.cmdline = "<kernel>"
        for p in self._ptable.values():
            try:
                self._ptable[p.ppid]._children.append(p.pid)
            except AttributeError: # no child list yet
                self._ptable[p.ppid]._children = sortedlist([p.pid])

        pslist = self._tree_helper(self._ptable[0], 0, [])
        return "\n".join(pslist)

    # recursive helper to indent according to child depth
    def _tree_helper(self, obj, level, rv):
        rv.append("%s%6d %.60s" % ("  "*level, obj.pid, obj.cmdline) )
        if not hasattr(obj, "_children"):
            return rv
        for cpid in obj._children:
            if cpid != obj.pid:
                self._tree_helper(self._ptable[cpid], level+1, rv)
        return rv

def _test(argv):
    pass # XXX

if __name__ == "__main__":
    import sys
    _test(sys.argv)


text:
'use strict';

var React = require('react-native');
var {
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  WebView
} = React;

var HEADER = '#3b5998';
var BGWASH = 'rgba(255,255,255,0.8)';
var DISABLED_WASH = 'rgba(255,255,255,0.25)';

var TEXT_INPUT_REF = 'urlInput';
var WEBVIEW_REF = 'webview';
var DEFAULT_URL = 'https://m.facebook.com';

var WebViewExample = React.createClass({

  getInitialState: function() {
    return {
      url: DEFAULT_URL,
      status: 'No Page Loaded',
      backButtonEnabled: false,
      forwardButtonEnabled: false,
      loading: true,
      scalesPageToFit: true,
    };
  },

  inputText: '',

  handleTextInputChange: function(event) {
    var url = event.nativeEvent.text;
    if (!/^[a-zA-Z-_]+:/.test(url)) {
      url = 'http://' + url;
    }
    this.inputText = url;
  },

  render: function() {
    this.inputText = this.state.url;

    return (
      <View style={[styles.container]}>
        <View style={[styles.addressBarRow]}>
          <TouchableOpacity
            onPress={this.goBack}
            style={this.state.backButtonEnabled ? styles.navButton : styles.disabledButton}>
            <Text>
               {'<'}
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={this.goForward}
            style={this.state.forwardButtonEnabled ? styles.navButton : styles.disabledButton}>
            <Text>
              {'>'}
            </Text>
          </TouchableOpacity>
          <TextInput
            ref={TEXT_INPUT_REF}
            autoCapitalize="none"
            defaultValue={this.state.url}
            onSubmitEditing={this.onSubmitEditing}
            onChange={this.handleTextInputChange}
            clearButtonMode="while-editing"
            style={styles.addressBarTextInput}
          />
          <TouchableOpacity onPress={this.pressGoButton}>
            <View style={styles.goButton}>
              <Text>
                 Go!
              </Text>
            </View>
          </TouchableOpacity>
        </View>
        <WebView
          ref={WEBVIEW_REF}
          automaticallyAdjustContentInsets={false}
          style={styles.webView}
          source={{uri: this.state.url}}
          javaScriptEnabled={true}
          domStorageEnabled={true}
          decelerationRate="normal"
          onNavigationStateChange={this.onNavigationStateChange}
          onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
          startInLoadingState={true}
          scalesPageToFit={this.state.scalesPageToFit}
        />
        <View style={styles.statusBar}>
          <Text style={styles.statusBarText}>{this.state.status}</Text>
        </View>
      </View>
    );
  },

  goBack: function() {
    this.refs[WEBVIEW_REF].goBack();
  },

  goForward: function() {
    this.refs[WEBVIEW_REF].goForward();
  },

  reload: function() {
    this.refs[WEBVIEW_REF].reload();
  },

  onShouldStartLoadWithRequest: function(event) {
    // Implement any custom loading logic here, don't forget to return!
    return true;
  },

  onNavigationStateChange: function(navState) {
    this.setState({
      backButtonEnabled: navState.canGoBack,
      forwardButtonEnabled: navState.canGoForward,
      url: navState.url,
      status: navState.title,
      loading: navState.loading,
      scalesPageToFit: true
    });
  },

  onSubmitEditing: function(event) {
    this.pressGoButton();
  },

  pressGoButton: function() {
    var url = this.inputText.toLowerCase();
    if (url === this.state.url) {
      this.reload();
    } else {
      this.setState({
        url: url,
      });
    }
    // dismiss keyboard
    this.refs[TEXT_INPUT_REF].blur();
  },

});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 20,
    backgroundColor: HEADER,
  },
  addressBarRow: {
    flexDirection: 'row',
    padding: 8,
  },
  webView: {
    backgroundColor: BGWASH,
    height: 350,
  },
  addressBarTextInput: {
    backgroundColor: BGWASH,
    borderColor: 'transparent',
    borderRadius: 3,
    borderWidth: 1,
    height: 24,
    paddingLeft: 10,
    paddingTop: 3,
    paddingBottom: 3,
    flex: 1,
    fontSize: 14,
  },
  navButton: {
    width: 20,
    padding: 3,
    marginRight: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: BGWASH,
    borderColor: 'transparent',
    borderRadius: 3,
  },
  disabledButton: {
    width: 20,
    padding: 3,
    marginRight: 3,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: DISABLED_WASH,
    borderColor: 'transparent',
    borderRadius: 3,
  },
  goButton: {
    height: 24,
    padding: 3,
    marginLeft: 8,
    alignItems: 'center',
    backgroundColor: BGWASH,
    borderColor: 'transparent',
    borderRadius: 3,
    alignSelf: 'stretch',
  },
  statusBar: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 5,
    height: 22,
  },
  statusBarText: {
    color: 'white',
    fontSize: 13,
  },
  spinner: {
    width: 20,
    marginRight: 6,
  },
});

module.exports = WebViewExample;