text:
title: <%= hoc_s(:title_signup_thanks) %>
layout: wide
nav: how_to_nav

social:
  "og:title": "<%= hoc_s(:meta_tag_og_title) %>"
  "og:description": "<%= hoc_s(:meta_tag_og_description) %>"
  "og:image": "http://<%=request.host%>/images/hourofcode-2015-video-thumbnail.png"
  "og:image:width": 1440
  "og:image:height": 900
  "og:url": "http://<%=request.host%>"

  "twitter:card": player
  "twitter:site": "@codeorg"
  "twitter:url": "http://<%=request.host%>"
  "twitter:title": "<%= hoc_s(:meta_tag_twitter_title) %>"
  "twitter:description": "<%= hoc_s(:meta_tag_twitter_description) %>"
  "twitter:image:src": "http://<%=request.host%>/images/hourofcode-2015-video-thumbnail.png"
---

<%
  facebook = {:u=>"http://#{request.host}/us"}

  twitter = {:url=>"http://hourofcode.com", :related=>'codeorg', :hashtags=>'', :text=>hoc_s(:twitter_default_text)}
  twitter[:hashtags] = 'HourOfCode' unless hoc_s(:twitter_default_text).include? '#HourOfCode'
%>

# Grazie per esserti iscritto per organizzare un evento dell'Ora del Codice!

Stai facendo sì che gli studenti di tutto il mondo possano provare un'Ora del Codice che può *cambiare il resto delle loro vite*, <%= campaign_date('full') %>. Saremo in contatto per i premi, le nuove esercitazioni e altri aggiornamenti interessanti. Cosa puoi fare ora?

## 1. Diffondi la notizia

Ti sei appena unito al movimento dell'Ora del Codice. Dillo ai tuoi amici con **#HourOfCode**!

<%= view :share_buttons, facebook:facebook, twitter:twitter %>

## 2. Find a local volunteer to help you with your event.

[Search our volunteer map](<%= resolve_url('https://code.org/volunteer/local') %>) for volunteers who can visit your classroom or video chat remotely to inspire your students about the breadth of possibilities with computer science.

## 3. Chiedi alla tua scuola di organizzare un'Ora del Codice

[Invia questo messaggio di posta elettronica](<%= resolve_url('/promote/resources#sample-emails') %>) al Dirigente Scolastico della tua scuola e invita ogni classe ad iscriversi.

## 4. Chiedi al tuo datore di lavoro di partecipare

[Invia questo messaggio di posta elettronica](<%= resolve_url('/promote/resources#sample-emails') %>) al tuo responsabile, o all'Amministratore Delegato della tua azienda.

## 5. Promuovi l'Ora del Codice fra i tuoi conoscenti

[ Recluta un po' di persone](<%= resolve_url('/promote/resources#sample-emails') %>) — tra i boy-scout, in parrocchia, all'università, tra gli esperti, al sindacato o tra i tuoi amici. Non c'è bisogno di stare a scuola per acquisire nuove competenze. Utilizza questi [poster, banner, adesivi, video e altro](<%= resolve_url('/promote/resources') %>) per il tuo evento.

## 6. Proponi ad un rappresentante eletto di sostenere L'Ora del Codice

[Invia questo messaggio di posta elettronica](<%= resolve_url('/promote/resources#sample-emails') %>) agli Amministratori Locali, al Consiglio Comunale o al Consiglio Scolastico per invitarli a visitare la tua scuola. Può aiutare a costruire un supporto per l'informatica nella tua zona che va oltre un ora.

## 7. Plan your Hour of Code

Choose an Hour of Code activity and [review this how-to guide](<%= resolve_url('/how-to') %>).

<%= view 'popup_window.js' %>


text:
#ifndef MI_MI_COMMON_H
#define MI_MI_COMMON_H

#include "interps.h"

struct mi_console_file;

/* Represents the reason why GDB is sending an asynchronous command to
   the front end.  NOTE: When modifing this, don't forget to update
   gdb.texinfo!  */
enum async_reply_reason
{
  EXEC_ASYNC_BREAKPOINT_HIT = 0,
  EXEC_ASYNC_WATCHPOINT_TRIGGER,
  EXEC_ASYNC_READ_WATCHPOINT_TRIGGER,
  EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER,
  EXEC_ASYNC_FUNCTION_FINISHED,
  EXEC_ASYNC_LOCATION_REACHED,
  EXEC_ASYNC_WATCHPOINT_SCOPE,
  EXEC_ASYNC_END_STEPPING_RANGE,
  EXEC_ASYNC_EXITED_SIGNALLED,
  EXEC_ASYNC_EXITED,
  EXEC_ASYNC_EXITED_NORMALLY,
  EXEC_ASYNC_SIGNAL_RECEIVED,
  EXEC_ASYNC_SOLIB_EVENT,
  EXEC_ASYNC_FORK,
  EXEC_ASYNC_VFORK,
  EXEC_ASYNC_SYSCALL_ENTRY,
  EXEC_ASYNC_SYSCALL_RETURN,
  EXEC_ASYNC_EXEC,
  /* This is here only to represent the number of enums.  */
  EXEC_ASYNC_LAST
};

const char *async_reason_lookup (enum async_reply_reason reason);

/* An MI interpreter.  */

class mi_interp final : public interp
{
public:
  mi_interp (const char *name)
    : interp (name)
  {}

  void init (bool top_level) override;
  void resume () override;
  void suspend () override;
  gdb_exception exec (const char *command_str) override;
  ui_out *interp_ui_out () override;
  void set_logging (ui_file_up logfile, bool logging_redirect) override;
  void pre_command_loop () override;

  /* MI's output channels */
  mi_console_file *out;
  mi_console_file *err;
  mi_console_file *log;
  mi_console_file *targ;
  mi_console_file *event_channel;

  /* Raw console output.  */
  struct ui_file *raw_stdout;

  /* Save the original value of raw_stdout here when logging, so we
     can restore correctly when done.  */
  struct ui_file *saved_raw_stdout;

  /* MI's builder.  */
  struct ui_out *mi_uiout;

  /* MI's CLI builder (wraps OUT).  */
  struct ui_out *cli_uiout;
};

#endif /* MI_MI_COMMON_H */

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import renderer from 'react-test-renderer';
import Content from './Content';

describe('Content', () => {
  it('renders correctly', () => {
    const props = {
      title: 'test',
      body: '
test
'
    };

    const tree = renderer.create(<Content {...props} />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});


text:
package hprose.example.io;

import hprose.io.ByteBufferStream;
import hprose.io.HproseClassManager;
import hprose.io.HproseReader;
import hprose.io.HproseWriter;
import java.io.IOException;
import java.util.Arrays;

public class ReaderExam {
    public static void main(String[] args) throws IOException {
        HproseClassManager.register(User.class, "my_package_User");
        ByteBufferStream stream = new ByteBufferStream();
        HproseWriter writer = new HproseWriter(stream.getOutputStream());
        writer.serialize(0);
        writer.serialize(1);
        writer.serialize(2);
        writer.serialize(3);
        writer.serialize(123);
        writer.serialize(3.14);
        writer.serialize("hello");
        writer.serialize("你好🇨🇳");
        writer.serialize(new char[] {'x', 'y', 'z'});
        writer.serialize(new Object[] {"x", "y", "z"});
        User user = new User();
        user.name = "Tom";
        user.age = 18;
        writer.serialize(user);
        stream.flip();
        HproseReader reader = new HproseReader(stream.getInputStream());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(reader.unserialize());
        System.out.println(Arrays.toString(reader.unserialize(char[].class)));
        System.out.println(reader.unserialize());
        User user2 = reader.unserialize(User.class);
        System.out.println(user2.name);
        System.out.println(user2.age);
    }
}


text:
/**
 * @typedef Options
 *   Configuration (optional).
 * @property {string|null|Array<string|null|undefined>} [align]
 *   One style for all columns, or styles for their respective columns.
 *   Each style is either `'l'` (left), `'r'` (right), or `'c'` (center).
 *   Other values are treated as `''`, which doesn't place the colon in the
 *   alignment row but does align left.
 *   *Only the lowercased first character is used, so `Right` is fine.*
 * @property {boolean} [padding=true]
 *   Whether to add a space of padding between delimiters and cells.
 *
 *   When `true`, there is padding:
 *
 *   ```markdown
 *   | Alpha | B     |
 *   | ----- | ----- |
 *   | C     | Delta |
 *   ```
 *
 *   When `false`, there is no padding:
 *
 *   ```markdown
 *   |Alpha|B    |
 *   |-----|-----|
 *   |C    |Delta|
 *   ```
 * @property {boolean} [delimiterStart=true]
 *   Whether to begin each row with the delimiter.
 *
 *   > 👉 **Note**: please don't use this: it could create fragile structures
 *   > that aren't understandable to some markdown parsers.
 *
 *   When `true`, there are starting delimiters:
 *
 *   ```markdown
 *   | Alpha | B     |
 *   | ----- | ----- |
 *   | C     | Delta |
 *   ```
 *
 *   When `false`, there are no starting delimiters:
 *
 *   ```markdown
 *   Alpha | B     |
 *   ----- | ----- |
 *   C     | Delta |
 *   ```
 * @property {boolean} [delimiterEnd=true]
 *   Whether to end each row with the delimiter.
 *
 *   > 👉 **Note**: please don't use this: it could create fragile structures
 *   > that aren't understandable to some markdown parsers.
 *
 *   When `true`, there are ending delimiters:
 *
 *   ```markdown
 *   | Alpha | B     |
 *   | ----- | ----- |
 *   | C     | Delta |
 *   ```
 *
 *   When `false`, there are no ending delimiters:
 *
 *   ```markdown
 *   | Alpha | B
 *   | ----- | -----
 *   | C     | Delta
 *   ```
 * @property {boolean} [alignDelimiters=true]
 *   Whether to align the delimiters.
 *   By default, they are aligned:
 *
 *   ```markdown
 *   | Alpha | B     |
 *   | ----- | ----- |
 *   | C     | Delta |
 *   ```
 *
 *   Pass `false` to make them staggered:
 *
 *   ```markdown
 *   | Alpha | B |
 *   | - | - |
 *   | C | Delta |
 *   ```
 * @property {(value: string) => number} [stringLength]
 *   Function to detect the length of table cell content.
 *   This is used when aligning the delimiters (`|`) between table cells.
 *   Full-width characters and emoji mess up delimiter alignment when viewing
 *   the markdown source.
 *   To fix this, you can pass this function, which receives the cell content
 *   and returns its "visible" size.
 *   Note that what is and isn't visible depends on where the text is displayed.
 *
 *   Without such a function, the following:
 *
 *   ```js
 *   markdownTable([
 *     ['Alpha', 'Bravo'],
 *     ['中文', 'Charlie'],
 *     ['👩❤👩', 'Delta']
 *   ])
 *   ```
 *
 *   Yields:
 *
 *   ```markdown
 *   | Alpha | Bravo |
 *   | - | - |
 *   | 中文 | Charlie |
 *   | 👩❤👩 | Delta |
 *   ```
 *
 *   With [`string-width`](https://github.com/sindresorhus/string-width):
 *
 *   ```js
 *   import stringWidth from 'string-width'
 *
 *   markdownTable(
 *     [
 *       ['Alpha', 'Bravo'],
 *       ['中文', 'Charlie'],
 *       ['👩❤👩', 'Delta']
 *     ],
 *     {stringLength: stringWidth}
 *   )
 *   ```
 *
 *   Yields:
 *
 *   ```markdown
 *   | Alpha | Bravo   |
 *   | ----- | ------- |
 *   | 中文  | Charlie |
 *   | 👩❤👩    | Delta   |
 *   ```
 */

/**
 * @typedef {Options} MarkdownTableOptions
 * @todo
 *   Remove next major.
 */

/**
 * Generate a markdown ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables)) table..
 *
 * @param {Array<Array<string|null|undefined>>} table
 *   Table data (matrix of strings).
 * @param {Options} [options]
 *   Configuration (optional).
 * @returns {string}
 */
export function markdownTable(table, options = {}) {
  const align = (options.align || []).concat()
  const stringLength = options.stringLength || defaultStringLength
  /** @type {Array<number>} Character codes as symbols for alignment per column. */
  const alignments = []
  /** @type {Array<Array<string>>} Cells per row. */
  const cellMatrix = []
  /** @type {Array<Array<number>>} Sizes of each cell per row. */
  const sizeMatrix = []
  /** @type {Array<number>} */
  const longestCellByColumn = []
  let mostCellsPerRow = 0
  let rowIndex = -1

  // This is a superfluous loop if we don't align delimiters, but otherwise we'd
  // do superfluous work when aligning, so optimize for aligning.
  while (++rowIndex < table.length) {
    /** @type {Array<string>} */
    const row = []
    /** @type {Array<number>} */
    const sizes = []
    let columnIndex = -1

    if (table[rowIndex].length > mostCellsPerRow) {
      mostCellsPerRow = table[rowIndex].length
    }

    while (++columnIndex < table[rowIndex].length) {
      const cell = serialize(table[rowIndex][columnIndex])

      if (options.alignDelimiters !== false) {
        const size = stringLength(cell)
        sizes[columnIndex] = size

        if (
          longestCellByColumn[columnIndex] === undefined ||
          size > longestCellByColumn[columnIndex]
        ) {
          longestCellByColumn[columnIndex] = size
        }
      }

      row.push(cell)
    }

    cellMatrix[rowIndex] = row
    sizeMatrix[rowIndex] = sizes
  }

  // Figure out which alignments to use.
  let columnIndex = -1

  if (typeof align === 'object' && 'length' in align) {
    while (++columnIndex < mostCellsPerRow) {
      alignments[columnIndex] = toAlignment(align[columnIndex])
    }
  } else {
    const code = toAlignment(align)

    while (++columnIndex < mostCellsPerRow) {
      alignments[columnIndex] = code
    }
  }

  // Inject the alignment row.
  columnIndex = -1
  /** @type {Array<string>} */
  const row = []
  /** @type {Array<number>} */
  const sizes = []

  while (++columnIndex < mostCellsPerRow) {
    const code = alignments[columnIndex]
    let before = ''
    let after = ''

    if (code === 99 /* `c` */) {
      before = ':'
      after = ':'
    } else if (code === 108 /* `l` */) {
      before = ':'
    } else if (code === 114 /* `r` */) {
      after = ':'
    }

    // There *must* be at least one hyphen-minus in each alignment cell.
    let size =
      options.alignDelimiters === false
        ? 1
        : Math.max(
            1,
            longestCellByColumn[columnIndex] - before.length - after.length
          )

    const cell = before + '-'.repeat(size) + after

    if (options.alignDelimiters !== false) {
      size = before.length + size + after.length

      if (size > longestCellByColumn[columnIndex]) {
        longestCellByColumn[columnIndex] = size
      }

      sizes[columnIndex] = size
    }

    row[columnIndex] = cell
  }

  // Inject the alignment row.
  cellMatrix.splice(1, 0, row)
  sizeMatrix.splice(1, 0, sizes)

  rowIndex = -1
  /** @type {Array<string>} */
  const lines = []

  while (++rowIndex < cellMatrix.length) {
    const row = cellMatrix[rowIndex]
    const sizes = sizeMatrix[rowIndex]
    columnIndex = -1
    /** @type {Array<string>} */
    const line = []

    while (++columnIndex < mostCellsPerRow) {
      const cell = row[columnIndex] || ''
      let before = ''
      let after = ''

      if (options.alignDelimiters !== false) {
        const size =
          longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)
        const code = alignments[columnIndex]

        if (code === 114 /* `r` */) {
          before = ' '.repeat(size)
        } else if (code === 99 /* `c` */) {
          if (size % 2) {
            before = ' '.repeat(size / 2 + 0.5)
            after = ' '.repeat(size / 2 - 0.5)
          } else {
            before = ' '.repeat(size / 2)
            after = before
          }
        } else {
          after = ' '.repeat(size)
        }
      }

      if (options.delimiterStart !== false && !columnIndex) {
        line.push('|')
      }

      if (
        options.padding !== false &&
        // Don't add the opening space if we're not aligning and the cell is
        // empty: there will be a closing space.
        !(options.alignDelimiters === false && cell === '') &&
        (options.delimiterStart !== false || columnIndex)
      ) {
        line.push(' ')
      }

      if (options.alignDelimiters !== false) {
        line.push(before)
      }

      line.push(cell)

      if (options.alignDelimiters !== false) {
        line.push(after)
      }

      if (options.padding !== false) {
        line.push(' ')
      }

      if (
        options.delimiterEnd !== false ||
        columnIndex !== mostCellsPerRow - 1
      ) {
        line.push('|')
      }
    }

    lines.push(
      options.delimiterEnd === false
        ? line.join('').replace(/ +$/, '')
        : line.join('')
    )
  }

  return lines.join('\n')
}

/**
 * @param {string|null|undefined} [value]
 * @returns {string}
 */
function serialize(value) {
  return value === null || value === undefined ? '' : String(value)
}

/**
 * @param {string} value
 * @returns {number}
 */
function defaultStringLength(value) {
  return value.length
}

/**
 * @param {string|null|undefined} value
 * @returns {number}
 */
function toAlignment(value) {
  const code = typeof value === 'string' ? value.codePointAt(0) : 0

  return code === 67 /* `C` */ || code === 99 /* `c` */
    ? 99 /* `c` */
    : code === 76 /* `L` */ || code === 108 /* `l` */
    ? 108 /* `l` */
    : code === 82 /* `R` */ || code === 114 /* `r` */
    ? 114 /* `r` */
    : 0
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>R: Parent-Duchatelet's time-series data on the number of...</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="R.css">

Prostitutes	R Documentation

Parent-Duchatelet's time-series data on the number of prostitutes in Paris

Description

A table indicating month by month, for the years 1812-1854, the number of prostitutes on the
registers of the administration of the city of Paris.

Usage

data(Prostitutes)

Format

A data frame with 516 observations on the following 5 variables.

Year

a numeric vector

month

a factor with levels Apr Aug Dec Feb Jan Jul Jun Mar May Nov Oct Sep

count

a numeric vector: number of prostitutes

mon

a numeric vector: numeric month

date

a Date

Details

The data table was digitally scanned with OCR, and errors were corrected by comparing the
yearly totals recorded in the table to the row sums of the scanned data.

Source

Parent-Duchatelet, A. (1857), De la prostitution dans la ville de Paris, 3rd ed,  p. 32, 36

Examples

data(Prostitutes)
## maybe str(Prostitutes) ; plot(Prostitutes) ...


text:
clear
now=$(date)
echo "Running setup_ubuntu_desktop.sh at $now
 _____             _         _    _          _
|     |___ ___ ___| |_ ___ _| |  | |_ _ _   |_|
|   --|  _| -_| .'|  _| -_| . |  | . | | |   _
|_____|_| |___|__,|_| |___|___|  |___|_  |  |_|
                                     |___|

 _____ _       _     _           _              _____    __    _____
|     | |_ ___|_|___| |_ ___ ___| |_ ___ ___   |     |__|  |  |   __|___ ___ _ _
|   --|   |  _| |_ -|  _| . | . |   | -_|  _|  | | | |  |  |  |  |  |  _| .'| | |
|_____|_|_|_| |_|___|_| |___|  _|_|_|___|_|    |_|_|_|_____|  |_____|_| |__,|_  |
                            |_|                                             |___|
\r\n \r\n
Version:  0.0.12                             \r\n
Last Updated:  2/1/2022
\r\n \r\n"

wait
sudo apt autoremove -y

sudo add-apt-repository universe
sudo apt-get install -y linux-generic-hwe-20.04 linux-headers-generic-hwe-20.04 linux-image-generic-hwe-20.04

#------------
sudo apt install -y software-properties-common apt-transport-https
sudo apt-get update
sudo apt-get upgrade -y

sudo apt-get install -y snapd

#--- General ---
sudo apt install -y net-tools curl ssh
sudo apt-get install -y iftop htop hping3 slurm bmon tcpdump tcl8.6 ncat gimp wget
# slurm -z -c -L -i ens16

#-- VNC Server
# https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-vnc-on-ubuntu-18-04
#sudo apt-get install -y vnc4server vnc-java x11-xfs-utils tightvncserver tightvnc-java
# vncserver
#mv ~/.vnc/xstartup ~/.vnc/xstartup.bak

# #!/bin/bash
# xrdb $HOME/.Xresources
# startxfce4 &

#sudo chmod +x ~/.vnc/xstartup

#echo "to CHECK the status of VNC Server use:    netstat -tulpn   \r\n \r\n"
#echo "To KILL VNCServer use:  vncserver -kill :1  \r\n \r\n"
#echo "set VNC Password: vncpasswd  \r\n \r\n"

#Password too long - only the first 8 characters will be used
#sudo vncserver

# --- Themes and looks ---
# https://www.howtogeek.com/358049/how-to-install-desktop-themes-on-ubuntu-18.04-lts/
sudo apt install -y gnome-tweaks gnome-shell-extensions unity-tweak-tool
sudo apt install -y adwaita-icon-theme-full
sudo apt install -y numix-gtk-theme numix-icon-theme arc-theme

# --- Hot corners --- https://ubuntuhandbook.org/index.php/2020/07/set-up-hot-corners-ubuntu-20-04/
sudo apt install -y chrome-gnome-shell
echo "Go To in Firefox or chome:  https://extensions.gnome.org/extension/1362/custom-hot-corners/ "
# https://luanlmd.medium.com/ubuntu-20-04-enable-hot-corners-82b15b542a8
gsettings set org.gnome.desktop.interface enable-hot-corners true

#-- Bonus Screensavers
#sudo apt-get install -y xscreensaver xscreensaver-gl-extra xscreensaver-data-extra
#xscreensaver &
#sudo apt-get remove gnome-screensaver

#-- Utilities ----
sudo apt-get install -y gnome-startup-applications
gnome-session-properties

#sudo add-apt-repository ppa:transmissionbt/ppa

#--- Chrome ---
echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome-stable_current_amd64.deb
#-- delete after installing ---
rm google-chrome-stable_current_amd64.deb

#--- Download VSCode ---
#sudo snap install code --classic
wget -q https://packages.microsoft.com/keys/microsoft.asc -O- | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main"
sudo apt upgrade
sudo apt install code
# Run with:  code

#--- Postman ---
sudo snap install -y postman

#--- Wireshark ---
sudo apt-get install -y libcap2-bin wireshark mmdb-bin qt5-image-formats-plugins qtwayland5 snmp-mibs-downloader wireshark-doc

#--- NMap ---
sudo apt-get install -y nmap

#--- Filezilla ---
sudo apt-get install -y filezilla

#--- Sublime Text ---
wget -qO - https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add -
echo "deb https://download.sublimetext.com/ apt/stable/" | sudo tee /etc/apt/sources.list.d/sublime-text.list
sudo apt-get update
sudo apt-get install -y sublime-text

#--- Termius ---
#wget https://www.termius.com/download/linux/Termius.deb
#chmod u+x Termius.deb
#sudo apt install -y ./Termius.deb

#---- Others ----
#sudo snap install -y vlc

#--- widgets ----
sudo add-apt-repository ppa:kasra-mp/ubuntu-indicator-weather
sudo apt update
sudo apt install -y indicator-weather

sudo apt install -y conky

#--- Temp Sensors ---
#sudo apt-get install -y lm-sensors hddtemp acpi xsensors
#sudo service kmod start
#sudo hddtemp /dev/sda

#sudo add-apt-repository -y ppa:jfi/ppa
#sudo apt-get update
#sudo apt-get install -y psensor
#sudo sensors-detect
#sensors


text:
from ..cw_model import CWModel

class CompanyTeam(CWModel):

    def __init__(self, json_dict=None):
        self.id = None  # (Integer)
        self.company = None  # (CompanyReference)
        self.teamRole = None  # *(TeamRoleReference)
        self.locationId = None  # (Integer)
        self.businessUnitId = None  # (Integer)
        self.contact = None  # (ContactReference)
        self.member = None  # (MemberReference)
        self.accountManagerFlag = None  # (Boolean)
        self.techFlag = None  # (Boolean)
        self.salesFlag = None  # (Boolean)
        self._info = None  # (Metadata)

        # initialize object with json dict
        super().__init__(json_dict)


text:
<?php

$container->loadFromExtension('framework', array(
    'serializer' => array(
        'enabled' => false,
    ),
    'messenger' => array(
        'serializer' => array(
            'enabled' => true,
        ),
        'transports' => array(
            'default' => 'amqp://localhost/%2f/messages',
        ),
    ),
));


text:
'use strict';

const kScope = '/cookie-store/does/not/exist';

// Resolves when the service worker receives the 'activate' event.
const kServiceWorkerActivatedPromise = new Promise((resolve) => {
  self.addEventListener('activate', event => { resolve(); });
});

// Resolves when a cookiechange event is received.
const kCookieChangeReceivedPromise = new Promise(resolve => {
  self.addEventListener('cookiechange', event => { resolve(event); });
});

promise_test(async testCase => {
  await kServiceWorkerActivatedPromise;

  const subscriptions = [{ name: 'cookie-name', url: `${kScope}/path` }];
  await registration.cookies.subscribe(subscriptions);
  testCase.add_cleanup(() => registration.cookies.unsubscribe(subscriptions));

  await cookieStore.set('cookie-name', 'cookie-value');
  testCase.add_cleanup(async () => {
    await cookieStore.delete('cookie-name');
  });

  const event = await kCookieChangeReceivedPromise;
  assert_equals(event.type, 'cookiechange');
  assert_equals(event.changed.length, 1);
  assert_equals(event.changed[0].name, 'cookie-name');
  assert_equals(event.changed[0].value, 'cookie-value');
  assert_equals(event.deleted.length, 0);
  assert_true(event instanceof ExtendableCookieChangeEvent);
  assert_true(event instanceof ExtendableEvent);
}, 'cookiechange dispatched with cookie change that matches subscription ' +
   'to cookiechange event handler registered with addEventListener');


text:
- Start Date: 2021-02-17
- RFC PR: https://github.com/linkedin/datahub/pull/2112
- Discussion Issue: (GitHub issue this was discussed in before the RFC, if any)
- Implementation PR(s): (leave this empty)

# Tags

## Summary

We suggest a generic, global tagging solution for Datahub. As the solution is quite generic and flexible, it can also
hopefully serve as an stepping stone for new, cool features in the future.

## Motivation

Currently some entities, such as Datasets, can be tagged using strings, but unfortunately this solution is quite
limited.

A general tag implementation will allow us to define and attach a new and simple type of metadata to all type of
entities. As the tags would be defined globally, tagging multiple objects with the same tag will give us the possibility
to define and search based on a new kind of relationship, for example which datasets and ML Models that are tagged to
include PII data. This allows for describing relationships between object that would otherwise not have a direct lineage
relationship. Moreover, tags would lower that bar to add simple metadata to any object in the Datahub instance and open
the door to crowd-sourcing metadata. Remembering that tags themselves are entities, it would also be possible to tag
tags, enabling a hierarchy of sorts.

The solution is meant to be quite generic and flexible, and we're not trying to be too opinionated about how a user
should use the feature. We hope that this initial generic solution can serve as a stepping stone for cool futures in the
future.

## Requirements

- Ability to associate tags with any type of entity, even other tags!
- Ability to tag the same entity with multiple tags.
- Ability to tag multiple objects with the same tag instance.
- To the point above, ability to make easy tag-based searches later on.
- Metadata on tags is TBD

### Extensibility

The normal new-entity-onboarding work is obviously required.

Hopefully this can serve as a stepping stone to work on special cases such as the tag-based privacy tagging mentioned in
the roadmap.

## Non-Requirements

Let's leave the UI work required for this to another time.

## Detailed design

We want to introduce some new under `datahub/metadata-models/src/main/pegasus/com/linkedin/common/`.

### `Tag` entity

First we create a `TagMetadata` entity, which defines the actual tag-object.

The edit property defines the edit rights of the tag, as some tags (like sensitivity tags) should be read-only for a
majority of users

```
/**
 * Tag information
 */
record TagMetadata {
   /**
   * Tag URN, e.g. urn:li:tag:<name>
   */
   urn: TagUrn

   /**
   * Tag value.
   */
   value: string

   /**
   * Optional tag description
   */
   description: optional string

   /**
   * Audit stamp associated with creation of this tag
   */
   createStamp: AuditStamp
}
```

### `TagAttachment`

We define a `TagAttachment`-model, which describes the application of a tag to a entity

```
/**
 * Tag information
 */
record TagAttachment {

  /**
   * Tag in question
   */
  tag: TagUrn

  /**
   * Who has edit rights to this employment.
   * WIP, pending access-control support in Datahub.
   * Relevant for privacy tags at least.
   * We might also want to add view rights?
   */
  edit: union[None, any, role-urn]

   /**
   * Audit stamp associated with employment of this tag to this entity
   */
   attachmentStamp: AuditStamp
}
```

### `Tags` container

Then we define a `Tags`-aspect, which is used as a container for tag employments.

```
namespace com.linkedin.common

/**
 * Tags information
 */
record Tags {

   /**
   * List of tag employments
   */
   elements: array[TagAttachment] = [ ]
}
```

This can easily be taken into use with wall entities that we want to be able to use tags, e.g. `Datasets`. As we see a
lot of potential in tagging individual dataset fields as well, we can either add a reference to a Tags-object in the
`SchemaField` object, or alternative create a new `DatasetFieldTags`, similar to `DatasetFieldMapping`.

## How we teach this

We should create/update user guides to educate users for:

- Suggestions on how to use tags: low threshold metadata-addition, and the possibility of doing new types of searches

## Drawbacks

This is definitely more complex than just adding strings to an array.

## Alternatives

An array of string is a simple solution but does allow for the same functionality as suggested here.

Another alternative would be simplify the models by removing some of the metadata in the `TagMetadata` and
`TagAttachment` entities, such as the the edit/view permission field, the audit stamps, and the descriptions.

Apache Atlas uses a similar approach. The require you to create a Tag instance before it can be associated with an
"asset", and the attachment is done using a dropdown list. The tags can also have attributes and a description. See
[here](https://docs.cloudera.com/HDPDocuments/HDP2/HDP-2.5.3/bk_data-governance/content/ch_working_with_atlas_tags.html)
for an example. The tags are a central piece in the UI and readably searchable, as easily as datasets.

Atlas also has concept very closely related to tags, called _classification_. Classifications are similar to tags in
that they need to be created separately, can have attributes (but no description?) and are attached to assets is done
using a dropdown list. Classifications have the added functionality of propagation, which means that they are
automatically applied to downstream assets, unless specifically set to not do so. Any change to a classification (say an
attribute change) also flows downstream, and in downstream assets you're able to see from where the classification
propagated from. See
[here](https://docs.cloudera.com/HDPDocuments/HDP3/HDP-3.1.5/using-atlas/content/propagate_classifications_to_derived_entities.html)
for an example.

## Rollout / Adoption Strategy

Using the functionality is optional and does not break other functionality as is. The solution is generic enough that
the users can easily take into use. It can be take into use as any other entity and aspect.

## Future Work

- add `Tags` to aspects for entities.
- Implement relationship builders as needed.
- The implementation of and need for access control to tags is an open question
- As this is first and foremost a tool for discovery, the UI work is extensible:
  - Creating tags in a way that makes duplication and spelling mistakes difficult.
  - Attaching tags to entities: autocomplete, dropdown, etc.
  - Visualizing existing tags, and which are most popular?
- Explore the idea about a special "classification" type, that propagates downstream, as in Atlas.

## Unresolved questions

- How do we want to map dataset fields to tags?
- Do we want to implement edit/view rights?


text:
/* eslint-env mocha */

'use strict'

const CID = require('cids')
const chai = require('aegir/utils/chai')
const expect = chai.expect
const {
  multihash
} = require('multihashing-async')

const DAGLink = require('../src/dag-link/dagLink')
const {
  serialize,
  deserialize,
  cid
} = require('../src/util')

describe('util', () => {
  it('should serialize an empty node', () => {
    const result = serialize({})
    expect(result).to.be.an.instanceof(Uint8Array)
    expect(result).to.be.empty()
  })

  it('should serialize a node with data', () => {
    const data = Uint8Array.from([0, 1, 2, 3])
    const result = serialize({ Data: data })
    expect(result).to.be.an.instanceof(Uint8Array)

    const node = deserialize(result)
    expect(node.Data).to.deep.equal(data)
  })

  it('should serialize a node with Uint8Array data', () => {
    const data = Uint8Array.from([0, 1, 2, 3])
    const result = serialize({ Data: data })
    expect(result).to.be.an.instanceof(Uint8Array)

    const node = deserialize(result)
    expect(node.Data).to.deep.equal(Uint8Array.from([0, 1, 2, 3]))
  })

  it('should serialize a node with links', () => {
    const links = [
      new DAGLink('', 0, 'QmWDtUQj38YLW8v3q4A6LwPn4vYKEbuKWpgSm6bjKW6Xfe')
    ]
    const result = serialize({ Links: links })
    expect(result).to.be.an.instanceof(Uint8Array)

    const node = deserialize(result)
    expect(node.Links).to.containSubset([{
      Name: '',
      Tsize: 0,
      Hash: new CID('QmWDtUQj38YLW8v3q4A6LwPn4vYKEbuKWpgSm6bjKW6Xfe')
    }])
  })

  it('should serialize a node with links as plain objects', () => {
    const links = [{
      Name: '',
      Tsize: 0,
      Hash: new CID('QmWDtUQj38YLW8v3q4A6LwPn4vYKEbuKWpgSm6bjKW6Xfe')
    }]
    const result = serialize({ Links: links })
    expect(result).to.be.an.instanceof(Uint8Array)

    const node = deserialize(result)
    expect(node.Links).to.containSubset(links)
  })

  it('should ignore invalid properties when serializing', () => {
    // @ts-ignore invalid properties
    const result = serialize({ foo: 'bar' })
    expect(result).to.be.empty()
  })

  describe('cid', () => {
    it('should allow the identity hash', async () => {
      const buffer = serialize({ Data: new Uint8Array(0), Links: [] })
      const id = await cid(buffer, {
        hashAlg: multihash.names.identity
      })

      const result = multihash.decode(id.multihash)

      expect(result).to.have.property('name', 'identity')
    })
  })
})


text:
#ifndef SPINE_EVENT_H_
#define SPINE_EVENT_H_

#include <spine/EventData.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct spEvent spEvent;
struct spEvent {
	spEventData* const data;
	int intValue;
	float floatValue;
	const char* stringValue;
};

spEvent* spEvent_create (spEventData* data);
void spEvent_dispose (spEvent* self);

#ifdef SPINE_SHORT_NAMES
typedef spEvent Event;
#define Event_create(...) spEvent_create(__VA_ARGS__)
#define Event_dispose(...) spEvent_dispose(__VA_ARGS__)
#endif

#ifdef __cplusplus
}
#endif

#endif /* SPINE_EVENT_H_ */


text:
class AddScoreSetToPhrase < ActiveRecord::Migration[5.1]
  def change
    add_column :phrases, :score_set, :jsonb, default: {}
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.dnastack</groupId>
        <artifactId>bob-client</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>bob-client-impl</artifactId>
    <description>Beacon Network Client Implementation</description>

    <dependencies>
        <dependency>
            <groupId>com.dnastack</groupId>
            <artifactId>bob-client-api</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>retrofit</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-jackson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
            <classifier>standalone</classifier>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>
    </dependencies>
</project>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
    public class DrawGUI : MonoBehaviour {
    // Use this for initialization
    public GameObject overlay;
        private void Update()
        {
            if (Input.GetButtonDown("PS4_TRIANGLE"))
            {
                overlay.gameObject.SetActive(false);
            }

        }

    }


text:
class PasswordsController < Devise::PasswordsController
  layout "admin_layout"
  before_action :record_password_reset_request, only: :create # rubocop:disable Rails/LexicallyScopedActionFilter
  before_action :record_reset_page_loaded, only: :edit

  def edit
    super

    user = user_from_params
    unless user && user.reset_password_period_valid?
      record_reset_page_loaded_token_expired
      render "devise/passwords/reset_error", layout: "admin_layout"
    end
  end

  def update
    super do |resource|
      if resource.errors.empty?
        record_password_reset_success(resource)
      else
        record_password_reset_failure(resource)
      end
    end
  end

private

  def record_password_reset_request
    user = User.find_by(email: params[:user][:email]) if params[:user].present?
    EventLog.record_event(user, EventLog::PASSWORD_RESET_REQUEST, ip_address: user_ip_address) if user
    GovukStatsd.increment("users.password_reset_request")
  end

  def record_reset_page_loaded
    EventLog.record_event(user_from_params, EventLog::PASSWORD_RESET_LOADED, ip_address: user_ip_address) if user_from_params
  end

  def record_password_reset_success(user)
    EventLog.record_event(user, EventLog::SUCCESSFUL_PASSWORD_RESET, ip_address: user_ip_address)
  end

  def record_reset_page_loaded_token_expired
    EventLog.record_event(user_from_params, EventLog::PASSWORD_RESET_LOADED_BUT_TOKEN_EXPIRED, ip_address: user_ip_address) if user_from_params
  end

  def record_password_reset_failure(user)
    message = "(errors: #{user.errors.full_messages.join(', ')})".truncate(255)
    EventLog.record_event(user, EventLog::PASSWORD_RESET_FAILURE, trailing_message: message, ip_address: user_ip_address)
  end

  def user_from_params
    token = Devise.token_generator.digest(self, :reset_password_token, params[:reset_password_token])
    User.find_by(reset_password_token: token)
  end
end


text: Omniauth strategy for connecting to the beatport api


text:
import inspect

from django.contrib.auth.models import User
from django.http import HttpResponse
from django.conf import settings

from taggit.models import Tag

from haystack import indexes

from wheelcms_axle.content import Content
from wheelcms_axle.node import Node
from wheelcms_axle.forms import formfactory, FileFormfactory

from wheelcms_axle.registries import core

from wheelcms_axle.models import type_registry
from wheelcms_axle.templates import template_registry
from wheelcms_axle import permissions as p, roles

from .context import ContextWrappable

from .impexp import WheelSerializer
from .actions import action, tab

from .utils import classproperty, json

from warnings import warn

import auth

from drole.models import RolePermission
from drole.types import Role, Permission

class SpokeCharField(indexes.CharField):
    def __init__(self, spoke, *args, **kw):
        super(SpokeCharField, self).__init__(*args, **kw)
        self.spoke = spoke

    def prepare(self, obj):
        instance = self.spoke(obj)
        ma = getattr(instance, self.model_attr, None)
        if ma:
            if callable(ma):
                res = ma()
            else:
                res = ma
        if res is None:
            return super(SpokeCharField, self).prepare(obj)

        return self.convert(res)

def indexfactory(spoke):
    """ return a generic index definition bound to 'spoke' """
    class WheelIndex(indexes.SearchIndex, indexes.Indexable):
        text = SpokeCharField(spoke=spoke, document=True,
                              model_attr='searchable_text')
        title = indexes.CharField(stored=True, indexed=False,
                                  model_attr="title")
        language = indexes.CharField(stored=True, indexed=True,
                                  model_attr="language")
        description = indexes.CharField(stored=True, indexed=False,
                              model_attr='description')
        state = indexes.CharField(stored=True, indexed=True,
                                  model_attr='state')
        meta_type = indexes.CharField(stored=True, indexed=True,
                                      model_attr='meta_type')
        path = indexes.CharField(stored=True, indexed=True,
                              model_attr='get_absolute_url')
        slug = indexes.CharField(stored=True, indexed=True,
                                  model_attr='node__slug', default='')
        created = indexes.DateField(stored=True, indexed=True,
                                    model_attr="created")
        modified = indexes.DateField(stored=True, indexed=True,
                                     model_attr="modified")
        publication = indexes.DateField(stored=True, indexed=True,
                                        model_attr="publication")
        expire = indexes.DateField(stored=True, indexed=True,
                                   model_attr="expire", null=True)
        icon = SpokeCharField(spoke=spoke, stored=True, indexed=False,
                              model_attr="full_icon_path")
        owner = SpokeCharField(spoke=spoke, stored=True, indexed=True,
                               model_attr="owner_name")

        def index_queryset(self, using=None):
            """ Should the content to be indexed restricted here?
                Or index everything and apply filters depending on
                context? """
            ## only index content that's attached.
            return spoke.model.objects.filter(node__isnull=False)

        def get_model(self):
            return spoke.model

    return WheelIndex

class Spoke(ContextWrappable):

    model = Content  ## is it smart to set this to Content? A nonsensible default..
    permissions = dict(
        create=p.create_content,
        edit=p.edit_content,
        view=p.view_content,
        delete=p.delete_content,
        list=p.list_content,
    )

    permission_assignment = {
        p.view_content: (roles.owner, roles.editor, roles.admin),
        p.edit_content: (roles.owner, roles.editor, roles.admin),
        p.create_content: (roles.owner, roles.editor, roles.admin),
        p.delete_content: (roles.owner, roles.editor, roles.admin),
        p.list_content: (roles.owner, roles.editor, roles.admin),
        p.change_auth_content: (roles.owner, roles.admin),
        p.modify_settings: (roles.admin,),
    }

    basetabs = (
        dict(id="attributes", label="Attributes", action="edit",
             permission=p.edit_content),
    )

    ## None means no restrictions, () means no subcontent allowed
    children = None

    ## The primary sub content. Used to create a quick shortcut
    primary = None

    ## can it be implicitly added?
    implicit_add = True

    ## explicit children - explicit children that can be added
    explicit_children = None

    ## is content discussable? Iow, is commenting allowed?
    discussable = False

    serializer = WheelSerializer

    ## default language - None to let the system decide,
    ## or an explicit language (usually 'any') to provide an overriding
    ## default
    default_language = None

    document_fields = ('title', 'description')

    ## index this type of content?
    add_to_index = True

    type_icon = icon = "page.png"

    def __init__(self, o):
        self.instance = o

    def __eq__(self, other):
        """ it may be useful to test equality of spokes in tests """
        return other and self.__class__ is other.__class__ and \
               self.instance == other.instance

    def __ne__(self, other):
        """ it may be useful to test equality of spokes in tests """
        return not self.__eq__(other)

    def tabs(self):
        """ Provide a hook to modify the tabs depending on the spoke
            context """
        decorated_tabs = []

        explicit_tabs = {}

        from .actions import action_registry

        for (name, a) in action_registry.iteritems():
            for (h, epath, espoke) in a:
                # import pdb; pdb.set_trace()
                if getattr(h, 'action', False) and getattr(h, 'tab', False):
                    if h.condition and not h.condition(self):
                        continue

                    if espoke and espoke != self.__class__:
                        continue

                    decorated_tabs.append(dict(id=h.tab_id, label=h.tab_label,
                                              action="+"+name,
                                              permission=h.permission))
                    explicit_tabs[name] = True

        for (name, m) in inspect.getmembers(self, inspect.ismethod):
            ##
            if name in explicit_tabs:
                continue

            #if name == "test_tab":
            #    import pytest; pytest.set_trace()
            if getattr(m, 'action', False) and getattr(m, 'tab', False):
                if m.condition and not m.condition(self):
                    continue
                id = getattr(m, 'tab_id', name)
                label = getattr(m, 'tab_label', id)
                decorated_tabs.append(dict(id=id, label=label, action="+"+name,
                                           permission=m.permission))
        return self.basetabs + tuple(decorated_tabs)

    def assign_perms(self):
        """ invoked by a signal handler upon creation: Set initial
            permissions """
        auth.assign_perms(self.instance, self.permission_assignment)

    def update_perms(self, perms):
        """ Update specific permissions, e.g. after a workflow change """
        auth.update_perms(self.instance, perms)

    @property
    def o(self):
        warn("{0}.o is obsolete, please use {0}.instance".format(self),
             DeprecationWarning, stacklevel=2)
        return self.instance

    def icon_base(self):
        return settings.STATIC_URL + "img/icons"

    def full_icon_path(self):
        """ return the full icon path. Used for storing the icon in the
            search index """
        return self.icon_base() + '/' + self.icon

    @classmethod
    def full_type_icon_path(cls):
        """
            Icons are instance specific, this allows an spoke to change its
            content depending on the content it holds. E.g. turn a generic
            file icon into a pdf file icon.

            But in certain cases we want a generic type icon without an
            instance, e.g. in the create popup
        """
        return settings.STATIC_URL + "img/icons/" + cls.type_icon

    def owner_name(self):
        """ return the owner's name, as good as possible """
        try:
            owner = self.instance.owner
        except User.DoesNotExist:
            return "Anonymous"

        if owner is None:
            return "Anonymous"

        name = owner.get_full_name()

        return name.strip() or owner.username

    ## Experimental API
    @property
    def node(self):
        """
            Return the node this Spoke is attached to
        """
        return self.instance.node

    @classmethod
    def fromNode(cls, node, slug=None):
        """
            Retrieve a spoke from a node, optionally resolving a childnode
        """
        if slug:
            node = node.child(slug)
            if node is None:
                return None
        content = node.content()
        if content is None:
            return None
        return content.spoke()

    @classmethod
    def create(cls, **kw):
        """
            Create a spoke with its instance, not connected
            to a specific node.
        """
        return cls(cls.model(**kw))

    def save(self, *a, **kw):
        """ save the instance """
        self.instance.save(*a, **kw)
        return self

    @classmethod
    def index(cls):
        """ generate the search index definition """
        return indexfactory(cls)

    @classproperty
    def form(cls):
        return formfactory(cls.model)

    @classproperty
    def light_form(cls):
        """ a smaller, lightweight form with minimal requirements """
        return cls.form

    @classmethod
    def name(cls):
        """ This needs namespacing. But a model determines its name based
            on the classname and doesn't know about namespaces or packages """
        return cls.model.get_name()

    @classproperty
    def title(cls):
        """ The title for this type, not for it's specific content """
        ## XXX somewhat inconsistent with spoke.description
        return cls.model._meta.object_name + " content"

    def description(self):
        """ attempt to provide some sort of description """
        warn("Spoke.description is deprecated, "
             "use context or .instance.description", stacklevel=2)
        return self.instance.description

    def workflow(self):
        """ the workflow, initialized to this spoke """
        return core.workflow[self.__class__](self)

    def state(self):
        """ current workflow state information for this spoke """
        return dict(key=self.instance.state, label=self.workflow().state())

    @classmethod
    def create_template(self, request, parent):
        """ If we're about to create, there's no actual instance of
            the spoke yet, hence the classmethod
            parent may be unattached, so we can't ask for a parent spoke
            instance
        """
        return "wheelcms_axle/create.html"

    def update_template(self):
        return "wheelcms_axle/update.html"

    def view_template(self):
        if not self.instance.template or \
           not template_registry.valid_for_model(self.model,
                                                 self.instance.template):
            default = template_registry.defaults.get(self.model)
            if default:
                return default

            all = template_registry.get(self.model, [])
            if len(all) == 1:
                return all[0][0]

            return "wheelcms_axle/content_view.html"

        return self.instance.template

    def list_template(self):
        ## perform a lookup for a registered LIST template?
        return "wheelcms_axle/contents.html"

    def detail_template(self):
        """ A small detail template, used in browse modal """
        return "wheelcms_axle/popup_detail.html"

    def fields(self):
        """ iterate over fields in model """
        for i in self.instance._meta.fields:
            yield (i.name, getattr(self.instance, i.name))

    def allow_spokes(self, types):
        """ Set which children are allowed as subcontent """
        self.instance.allowed = ",".join(t.name() for t in types)

    def allowed_spokes(self):
        """
            Return the spokes that can be added to the current instance.
            This can be either the spoke's class default, or an instance
            specific config (instance.allowed).

            If the specific config is an empty string, no subcontent is
            allowed.

            If the specific config is a list of comma separated type names,
            those are allowed (even non-implicit ones)

            If the specific config is None, de class default applies.
        """
        def addable(t):
            """ check it it's addable, implicitly or explicitly """
            if t.implicit_add:
                return True
            explicit = set(self.children or ()) | \
                       set(self.explicit_children or ())
            return t in explicit

        if self.instance.allowed == "":
            ch = ()
        elif self.instance.allowed is None:
            # Class default
            if self.children is None:
                ch = [t for t in type_registry.values() if addable(t)]
            else:
                ch = self.children
        else:
            ch = [type_registry.get(p)
                  for p in self.instance.allowed.split(",")]
            ## filter out stale entries. Log?
            ch = filter(None, ch)
        return ch

    def addable_children(self):
        """ deprecated name """
        warn("Spoke.addable_children is obsolete, "
             "please use allowed_spokes in stead",
             DeprecationWarning, stacklevel=2)
        return self.allowed_spokes()

    def searchable_text(self):
        """ collect, if possible, the value of all fields in 'document_fields'
            and return their values combined. This is to be used as the main
            document index value """
        res = u""
        for f in self.document_fields:
            if hasattr(self.instance, f):
                ff = getattr(self.instance, f)
                if callable(ff):
                    res += " " + ff()
                else:
                    res += " " + ff

        res += " ".join(t.name for t in self.instance.tags.all())

        return res

    def path(self):
        try:
            return self.instance.node.path or '/'
        except Node.DoesNotExist:
            return None

    def context(self, handler, request, node):
        """ hook to add additional data to the context """
        return {'spoke':self}

    def can_discuss(self):
        """ determine if content can be discussed. Either by explicit
            database setting or by content default. """
        explicit = self.instance.discussable
        if explicit is None:
            return self.discussable
        return explicit

    @tab(p.change_auth_content, id="auth", label="Roles/Perms")
    def auth(self, handler, request, action):
        ##
        ## If post, handle/reset perm changes

        if request.method == "POST":
            existing = RolePermission.assignments(self.instance)
            assignments = request.POST.getlist('assignment')
            for e in existing:
                if "{0}/{1}".format(e.permission, e.role) not in assignments:
                    e.delete()

            for assignment in assignments:
                perm, role = assignment.split('/', 1)
                RolePermission.assign(self.instance, Role(role),
                                      Permission(perm)).save()

        ctx = {'spoke':self}

        roles = Role.all()
        permissions = []

        ## order roles, permissions (alphabetically?)
        for perm in Permission.all():
            d = dict(perm=perm, roles=[])
            perms_per_role = RolePermission.assignments(
                                        self.instance).filter(
                                        permission=perm.id,
                                        ).values_list('role', flat=True)
            r = []
            for role in roles:
                r.append(dict(role=role, checked=role.id in perms_per_role))

            d['roles'] = r

            permissions.append(d)

        ctx['roles'] = roles
        ctx['permissions'] = permissions
        return handler.template("wheelcms_axle/edit_permissions.html", **ctx)

    @action
    @json
    def tags(self, handler, request, action):
        q = request.GET.get('query', '').lower()
        tags = list(Tag.objects.filter(name__istartswith=q
                    ).values_list("name", flat=True).all())
        return tags

class FileSpoke(Spoke):
    @classproperty
    def form(cls):
        return FileFormfactory(cls.model)

    @classproperty
    def light_form(cls):
        return FileFormfactory(cls.model, light=True)

    @action
    def download(self, handler, request, action):
        """ provide a direct download

            What's the best option: redirect to {{MEDIA_URL}}/<path> or
            serve from the cms? The former is far more efficient (can be handled
            by the application server), the latter allows more restrictions,
            headers, mangling, etc.

            For now, let's choose the inefficient option
        """
        ## test workflow state / permissions! XXX

        filename = self.instance.filename or self.instance.title
        content_type = self.instance.content_type or "application/octet-stream"

        response = HttpResponse(self.instance.storage, content_type=content_type)
        response['Content-Type'] = content_type

        response['Content-Disposition'] = 'attachment; filename=%s' % filename
        return response


text:
namespace engine
{
	SETTINGS_START(config_t, debug)
		SETTINGS_SET(bool, global_test_setting, true)
		SETTINGS_SET(bool, app_game_test_setting, true)
		SETTINGS_SET(bool, local_test_setting, true)
	SETTINGS_END()

	SETTINGS_START(config_t, release)
		SETTINGS_SET(bool, global_test_setting, false)
		SETTINGS_SET(bool, app_game_test_setting, false)
		SETTINGS_SET(bool, local_test_setting, false)
	SETTINGS_END()

	SETTINGS_START(config_storage_t, normal)
		SETTINGS_SET(ustring_t, key_for_global_test_setting, "global_test_setting"_u)
		SETTINGS_SET(ustring_t, key_for_app_game_test_setting, "app_game_test_setting"_u)
		SETTINGS_SET(ustring_t, key_for_local_test_setting, "local_#1#_test_setting"_u)
	SETTINGS_END()
}

#endif


text:
package com.foreveross.qdp.application.system.auth;

import java.util.Date;
import org.iff.infra.domain.InstanceFactory;
import org.iff.infra.test.AbstractIntegratedTestCase;
import org.iff.infra.util.mybatis.plugin.Page;
import org.junit.Test;

import com.foreveross.qdp.application.system.auth.AuthResourceApplication;
import com.foreveross.qdp.infra.vo.system.auth.AuthResourceVO;

/**
 * Test for AuthResource.
 * @author Tyler Chen
 * @since 2017-11-09
 * @version 1.0.0
 * auto generate by qdp v3.0.
 */
public class AuthResourceApplicationTest extends AbstractIntegratedTestCase {

	protected String[] getDataSetFilePaths() {
		return new String[] { "dataset/AuthResource.xml" };
	}

	@Test
	public void test_getAuthResource() {
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
	}

	@Test
	public void test_getAuthResourceById(){
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
	}

	@Test
	public void test_pageFindAuthResource() {
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
		Page page = Page.pageable(10, 1, 0, null);
		AuthResourceVO vo = new AuthResourceVO();
		System.out.println(application.pageFindAuthResource(vo, page));
	}

	@Test
	public void test_addAuthResource() {
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
		AuthResourceVO vo = new AuthResourceVO();
		//application.addAuthResource(vo);
	}

	@Test
	public void test_updateAuthResource() {
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
		AuthResourceVO vo = new AuthResourceVO();
		//application.updateAuthResource(vo);
	}

	@Test
	public void test_removeAuthResource() {
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
	}

	@Test
	public void test_removeAuthResourceById(){
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
	}

	@Test
	public void test_removeAuthResourceByIds(){
		AuthResourceApplication application = InstanceFactory.getInstance(AuthResourceApplication.class);
	}

}


text:
// Type definitions for command-line-args 4.0.6
// Project: https://github.com/75lb/command-line-args
// Definitions by: CzBuCHi <https://github.com/CzBuCHi/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/**
 * Returns an object containing all options set on the command line. By default it parses the global  [`process.argv`](https://nodejs.org/api/process.html#process_process_argv) array.
 *
 * By default, an exception is thrown if the user sets an unknown option (one without a valid [definition](#exp_module_definition--OptionDefinition)). To enable __partial parsing__, invoke `commandLineArgs` with the `partial` option - all unknown arguments will be returned in the `_unknown` property.
 *
 *
 * @param {module:definition[]} - An array of [OptionDefinition](#exp_module_definition--OptionDefinition) objects
 * @param [options] {object} - Options.
 * @param [options.argv] {string[]} - An array of strings, which if passed will be parsed instead  of `process.argv`.
 * @param [options.partial] {boolean} - If `true`, an array of unknown arguments is returned in the `_unknown` property of the output.
 * @returns {object}
 * @throws `UNKNOWN_OPTION` if `options.partial` is false and the user set an undefined option
 * @throws `NAME_MISSING` if an option definition is missing the required `name` property
 * @throws `INVALID_TYPE` if an option definition has a `type` value that's not a function
 * @throws `INVALID_ALIAS` if an alias is numeric, a hyphen or a length other than 1
 * @throws `DUPLICATE_NAME` if an option definition name was used more than once
 * @throws `DUPLICATE_ALIAS` if an option definition alias was used more than once
 * @throws `DUPLICATE_DEFAULT_OPTION` if more than one option definition has `defaultOption: true`
 * @alias module:command-line-args
 */
declare function commandLineArgs(optionDefinitions: commandLineArgs.OptionDefinition[], options?: commandLineArgs.Options): any;

declare module commandLineArgs {

    export interface OptionDefinition {
        /**
         * The only required definition property is name, the value of each option will be either a Boolean or string.
         */
        name: string,
        /**
         * The type value is a setter function (you receive the output from this), enabling you to be specific about the type and value received.
         */
        type?: (arg: string) => any,
        /**
         * getopt-style short option names. Can be any single character (unicode included) except a digit or hypen.
         */
        alias?: string,
        /**
         * Set this flag if the option takes a list of values. You will receive an array of values, each passed through the type function (if specified).
         */
        multiple?: boolean,
        /**
         * Any unclaimed command-line args will be set on this option. This flag is typically set on the most commonly-used option to make for more concise usage (i.e. $ myapp *.js instead of $ myapp --files *.js).
         */
        defaultOption?: boolean,
        /**
         * An initial value for the option.
         */
        defaultValue?: any,
        /**
         * When your app has a large amount of options it makes sense to organise them in groups.
         * There are two automatic groups: _all (contains all options) and _none (contains options without a group specified in their definition).
         */
        group?: string | string[],
    }

    export interface Options {
        /**
         * An array of strings, which if passed will be parsed instead  of `process.argv`.
         */
        argv?: string[];
        /**
         * If `true`, an array of unknown arguments is returned in the `_unknown` property of the output.
         */
        partial?: boolean;
    }
}

export = commandLineArgs;


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 330543 $ -->
<refentry xml:id="collator.asort" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>Collator::asort</refname>
  <refname>collator_asort</refname>
  <refpurpose>Sort array maintaining index association</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <para>&style.oop;</para>
  <methodsynopsis>
   <modifier>public</modifier>
   <type>bool</type>
   <methodname>Collator::asort</methodname>
   <methodparam><type>array</type><parameter role="reference">arr</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>sort_flag</parameter></methodparam>
  </methodsynopsis>
  <para>
   &style.procedural;
  </para>
  <methodsynopsis>
   <type>bool</type>
   <methodname>collator_asort</methodname>
   <methodparam><type>Collator</type><parameter>coll</parameter></methodparam>
   <methodparam><type>array</type><parameter role="reference">arr</parameter></methodparam>
   <methodparam choice="opt"><type>int</type><parameter>sort_flag</parameter></methodparam>
  </methodsynopsis>
  <para>
   This function sorts an array such that array indices maintain their
   correlation with the array elements they are associated with. This is used
   mainly when sorting associative arrays where the actual element order is
   significant. Array elements will have sort order according to current
   locale rules.
  </para>
  <para>
   Equivalent to standard PHP
   <function>asort</function>.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>coll</parameter></term>
     <listitem>
      <para>
       <classname>Collator</classname> object.
      </para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>arr</parameter></term>
     <listitem>
      <para>Array of strings to sort.</para>
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>sort_flag</parameter></term>
     <listitem>
      <para>
       Optional sorting type, one of the following:
       <itemizedlist>
        <listitem>
         <para>
          <constant>Collator::SORT_REGULAR</constant>
          - compare items normally (don't change types)
         </para>
        </listitem>
        <listitem>
         <para>
          <constant>Collator::SORT_NUMERIC</constant>
          - compare items numerically
         </para>
        </listitem>
        <listitem>
         <para>
          <constant>Collator::SORT_STRING</constant>
          - compare items as strings
         </para>
        </listitem>
       </itemizedlist>
      </para>
      <para>
       Default $sort_flag value is
       <constant>Collator::SORT_REGULAR</constant>.
       It is also used if an invalid $sort_flag value has been specified.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &return.success;
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>collator_asort</function>example</title>
    <programlisting role="php">
<![CDATA[
<?php
$coll = collator_create( 'en_US' );
$arr = array(
     'a' => '100',
     'b' => '50',
     'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><link linkend="intl.collator-constants"><classname>Collator</classname> constants</link></member>
    <member><function>collator_sort</function></member>
    <member><function>collator_sort_with_sort_keys</function></member>
   </simplelist>
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
 Local variables:
 mode: sgml
 sgml-omittag:t
 sgml-shorttag:t
 sgml-minimize-attributes:nil
 sgml-always-quote-attributes:t
 sgml-indent-step:1
 sgml-indent-data:t
 indent-tabs-mode:nil
 sgml-parent-document:nil
 sgml-default-dtd-file:"~/.phpdoc/manual.ced"
 sgml-exposed-tags:nil
 sgml-local-catalogs:nil
 sgml-local-ecat-files:nil
 End:
 vim600: syn=xml fen fdm=syntax fdl=2 si
 vim: et tw=78 syn=sgml
 vi: ts=1 sw=1
-->


text:
/*!40101 SET NAMES binary*/;
/*!40014 SET FOREIGN_KEY_CHECKS=0*/;

CREATE TABLE `columns_priv` (
  `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Db` char(64) COLLATE utf8_bin NOT NULL DEFAULT '',
  `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Table_name` char(64) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Column_name` char(64) COLLATE utf8_bin NOT NULL DEFAULT '',
  `Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Column_priv` set('Select','Insert','Update','References') CHARACTER SET utf8 NOT NULL DEFAULT '',
  PRIMARY KEY (`Host`,`Db`,`User`,`Table_name`,`Column_name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Column privileges';


text:
use crate::spec::{Target, TargetOptions};

pub fn target() -> Target {
    Target {
        llvm_target: "armv5te-unknown-linux-gnueabi".to_string(),
        pointer_width: 32,
        data_layout: "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
        arch: "arm".to_string(),
        options: TargetOptions {
            abi: "eabi".to_string(),
            features: "+soft-float,+strict-align".to_string(),
            // Atomic operations provided by compiler-builtins
            max_atomic_width: Some(32),
            mcount: "\u{1}__gnu_mcount_nc".to_string(),
            has_thumb_interworking: true,
            ..super::linux_gnu_base::opts()
        },
    }
}


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

#include "chrome_frame/dll_redirector.h"

#include "base/memory/shared_memory.h"
#include "base/strings/utf_string_conversions.h"
#include "base/version.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "chrome_frame/test/chrome_frame_test_utils.h"
#include "gtest/gtest.h"

extern "C" IMAGE_DOS_HEADER __ImageBase;

const char kMockVersionString[] = "42.42.42.42";
const char kMockVersionString2[] = "133.33.33.7";

const HMODULE kMockModuleHandle = reinterpret_cast<HMODULE>(42);
const HMODULE kMockModuleHandle2 = reinterpret_cast<HMODULE>(43);

const char kTestVersionBeaconName[] = "DllRedirectorTestVersionBeacon";
const uint32 kSharedMemorySize = 128;

// The maximum amount of time we are willing to let a test that Waits timeout
// before failing.
const uint32 kWaitTestTimeout = 20000;

class MockDllRedirector : public DllRedirector {
 public:
  explicit MockDllRedirector(const char* beacon_name)
      : DllRedirector(beacon_name) {}

  virtual HMODULE LoadVersionedModule() {
    return kMockModuleHandle;
  }

  virtual Version* GetCurrentModuleVersion() {
    return new Version(kMockVersionString);
  }

  virtual HMODULE GetFirstModule() {
    return DllRedirector::GetFirstModule();
  }

  Version* GetFirstModuleVersion() {
    // Lazy man's copy.
    return new Version(dll_version_->GetString());
  }

  base::SharedMemory* shared_memory() {
    return shared_memory_.get();
  }
};

class MockDllRedirector2 : public MockDllRedirector {
 public:
  explicit MockDllRedirector2(const char* beacon_name)
      : MockDllRedirector(beacon_name) {}

  virtual HMODULE LoadVersionedModule() {
    return kMockModuleHandle2;
  }

  virtual Version* GetCurrentModuleVersion() {
    return new Version(kMockVersionString2);
  }
};

class MockDllRedirectorNoPermissions : public MockDllRedirector {
 public:
  explicit MockDllRedirectorNoPermissions(const char* beacon_name)
    : MockDllRedirector(beacon_name) {}

  virtual bool BuildSecurityAttributesForLock(
      ATL::CSecurityAttributes* sec_attr) {
    return false;
  }

  virtual bool SetFileMappingToReadOnly(base::SharedMemoryHandle mapping) {
    return true;
  }
};

class DllRedirectorTest : public testing::Test {
 public:
  virtual void SetUp() {
    shared_memory_.reset(new base::SharedMemory);
    mock_version_.reset(new Version(kMockVersionString));
    mock_version2_.reset(new Version(kMockVersionString2));
  }

  virtual void TearDown() {
    CloseBeacon();
  }

  void CreateVersionBeacon(const std::string& name,
                           const std::string& version_string) {
    // Abort the test if we can't create and map a new named memory object.
    EXPECT_TRUE(shared_memory_->CreateNamed(name, false,
                                            kSharedMemorySize));
    EXPECT_TRUE(shared_memory_->Map(0));
    EXPECT_TRUE(shared_memory_->memory());

    if (shared_memory_->memory()) {
      memcpy(shared_memory_->memory(),
             version_string.c_str(),
             std::min(kSharedMemorySize, version_string.length() + 1));
    }
  }

  // Opens the named beacon and returns the version.
  Version* OpenAndReadVersionFromBeacon(const std::string& name) {
    // Abort the test if we can't open and map the named memory object.
    EXPECT_TRUE(shared_memory_->Open(name, true /* read_only */));
    EXPECT_TRUE(shared_memory_->Map(0));
    EXPECT_TRUE(shared_memory_->memory());

    char buffer[kSharedMemorySize] = {0};
    memcpy(buffer, shared_memory_->memory(), kSharedMemorySize - 1);
    scoped_ptr<Version> version(new Version(buffer));
    if (!version->IsValid())
      version.reset();
    return version.release();
  }

  void CloseBeacon() {
    shared_memory_->Close();
  }

  // Shared memory segment that contains the version beacon.
  scoped_ptr<base::SharedMemory> shared_memory_;
  scoped_ptr<Version> mock_version_;
  scoped_ptr<Version> mock_version2_;
};

TEST_F(DllRedirectorTest, RegisterAsFirstModule) {
  scoped_ptr<MockDllRedirector> redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(redirector->RegisterAsFirstCFModule());

  base::SharedMemory* redirector_memory = redirector->shared_memory();
  char buffer[kSharedMemorySize] = {0};
  memcpy(buffer, redirector_memory->memory(), kSharedMemorySize - 1);
  Version redirector_version(buffer);
  ASSERT_TRUE(redirector_version.IsValid());
  EXPECT_TRUE(redirector_version.Equals(*mock_version_.get()));
  redirector_memory = NULL;

  scoped_ptr<Version> memory_version(
      OpenAndReadVersionFromBeacon(kTestVersionBeaconName));
  ASSERT_TRUE(memory_version.get());
  EXPECT_TRUE(redirector_version.Equals(*memory_version.get()));
  CloseBeacon();

  redirector.reset();
  EXPECT_FALSE(shared_memory_->Open(kTestVersionBeaconName, true));
}

TEST_F(DllRedirectorTest, SecondModuleLoading) {
  scoped_ptr<MockDllRedirector> first_redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  scoped_ptr<MockDllRedirector2> second_redirector(
      new MockDllRedirector2(kTestVersionBeaconName));
  EXPECT_FALSE(second_redirector->RegisterAsFirstCFModule());

  scoped_ptr<Version> first_redirector_version(
      first_redirector->GetFirstModuleVersion());
  scoped_ptr<Version> second_redirector_version(
      second_redirector->GetFirstModuleVersion());

  EXPECT_TRUE(
      second_redirector_version->Equals(*first_redirector_version.get()));
  EXPECT_TRUE(
      second_redirector_version->Equals(*mock_version_.get()));
}

// This test ensures that the beacon remains alive as long as there is a single
// module that used it to determine its version still loaded.
TEST_F(DllRedirectorTest, TestBeaconOwnershipHandoff) {
  scoped_ptr<MockDllRedirector> first_redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  scoped_ptr<MockDllRedirector2> second_redirector(
      new MockDllRedirector2(kTestVersionBeaconName));
  EXPECT_FALSE(second_redirector->RegisterAsFirstCFModule());

  scoped_ptr<Version> first_redirector_version(
      first_redirector->GetFirstModuleVersion());
  scoped_ptr<Version> second_redirector_version(
      second_redirector->GetFirstModuleVersion());

  EXPECT_TRUE(
      second_redirector_version->Equals(*first_redirector_version.get()));
  EXPECT_TRUE(
      second_redirector_version->Equals(*mock_version_.get()));

  // Clear out the first redirector. The second, still holding a reference
  // to the shared memory should ensure that the beacon stays alive.
  first_redirector.reset();

  scoped_ptr<MockDllRedirector2> third_redirector(
      new MockDllRedirector2(kTestVersionBeaconName));
  EXPECT_FALSE(third_redirector->RegisterAsFirstCFModule());

  scoped_ptr<Version> third_redirector_version(
      third_redirector->GetFirstModuleVersion());

  EXPECT_TRUE(
      third_redirector_version->Equals(*second_redirector_version.get()));
  EXPECT_TRUE(
      third_redirector_version->Equals(*mock_version_.get()));

  // Now close all remaining redirectors, which should destroy the beacon.
  second_redirector.reset();
  third_redirector.reset();

  // Now create a fourth, expecting that this time it should be the first in.
  scoped_ptr<MockDllRedirector2> fourth_redirector(
      new MockDllRedirector2(kTestVersionBeaconName));
  EXPECT_TRUE(fourth_redirector->RegisterAsFirstCFModule());

  scoped_ptr<Version> fourth_redirector_version(
      fourth_redirector->GetFirstModuleVersion());

  EXPECT_TRUE(
      fourth_redirector_version->Equals(*mock_version2_.get()));
}

struct LockSquattingThreadParams {
  base::win::ScopedHandle is_squatting;
  base::win::ScopedHandle time_to_die;
};

DWORD WINAPI LockSquattingThread(void* in_params) {
  LockSquattingThreadParams* params =
      reinterpret_cast<LockSquattingThreadParams*>(in_params);
  DCHECK(params);

  // Grab the lock for the shared memory region and hold onto it.
  base::SharedMemory squatter(ASCIIToWide(kTestVersionBeaconName));
  base::SharedMemoryAutoLock squatter_lock(&squatter);

  // Notify our caller that we're squatting.
  BOOL ret = ::SetEvent(params->is_squatting);
  DCHECK(ret);

  // And then wait to be told to shut down.
  DWORD result = ::WaitForSingleObject(params->time_to_die, kWaitTestTimeout);
  EXPECT_EQ(WAIT_OBJECT_0, result);

  return 0;
}

// Test that the Right Thing happens when someone else is holding onto the
// beacon lock and not letting go. (The Right Thing being that the redirector
// assumes that it is the right version and doesn't attempt to use the shared
// memory region.)
TEST_F(DllRedirectorTest, LockSquatting) {
  scoped_ptr<MockDllRedirector> first_redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  LockSquattingThreadParams params;
  params.is_squatting.Set(::CreateEvent(NULL, FALSE, FALSE, NULL));
  params.time_to_die.Set(::CreateEvent(NULL, FALSE, FALSE, NULL));
  DWORD tid = 0;
  base::win::ScopedHandle lock_squat_thread(
      ::CreateThread(NULL, 0, LockSquattingThread, &params, 0, &tid));

  // Make sure the squatter has started squatting.
  DWORD wait_result = ::WaitForSingleObject(params.is_squatting,
                                            kWaitTestTimeout);
  EXPECT_EQ(WAIT_OBJECT_0, wait_result);

  scoped_ptr<MockDllRedirector2> second_redirector(
      new MockDllRedirector2(kTestVersionBeaconName));
  EXPECT_TRUE(second_redirector->RegisterAsFirstCFModule());

  scoped_ptr<Version> second_redirector_version(
      second_redirector->GetFirstModuleVersion());
  EXPECT_TRUE(
      second_redirector_version->Equals(*mock_version2_.get()));

  // Shut down the squatting thread.
  DWORD ret = ::SetEvent(params.time_to_die);
  DCHECK(ret);

  wait_result = ::WaitForSingleObject(lock_squat_thread, kWaitTestTimeout);
  EXPECT_EQ(WAIT_OBJECT_0, wait_result);
}

TEST_F(DllRedirectorTest, BadVersionNumber) {
  std::string bad_version("I am not a version number");
  CreateVersionBeacon(kTestVersionBeaconName, bad_version);

  // The redirector should fail to read the version number and defer to
  // its own version.
  scoped_ptr<MockDllRedirector> first_redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  HMODULE first_module = first_redirector->GetFirstModule();
  EXPECT_EQ(NULL, first_module);
}

// TODO(robertshield): These tests rely on simulating access checks from a low
// integrity process using impersonation. This may not be exactly identical to
// actually having a separate low integrity process.
TEST_F(DllRedirectorTest, LowIntegrityAccess) {
  scoped_ptr<MockDllRedirector> first_redirector(
      new MockDllRedirector(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  // Ensure that we can acquire the mutex from medium integrity:
  {
    base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName));
    bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL);
    EXPECT_TRUE(mutex_locked);

    // Ensure that the shared memory is read-only:
    EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false));
    shared_memory.Close();
    EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, true));
    shared_memory.Close();

    if (mutex_locked)
      shared_memory.Unlock();
  }

  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    // Now move to low integrity
    chrome_frame_test::LowIntegrityToken low_integrity_token;
    ASSERT_TRUE(low_integrity_token.Impersonate());

    // Ensure that we can also acquire the mutex from low integrity.
    base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName));
    bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL);
    EXPECT_TRUE(mutex_locked);

    // Ensure that the shared memory is read-only:
    EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false));
    shared_memory.Close();
    EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, true));
    shared_memory.Close();

    if (mutex_locked)
      shared_memory.Unlock();
  }
}

TEST_F(DllRedirectorTest, LowIntegrityAccessDenied) {
  // Run this test with a mock DllRedirector that doesn't set permissions
  // on the shared memory.
  scoped_ptr<MockDllRedirectorNoPermissions> first_redirector(
      new MockDllRedirectorNoPermissions(kTestVersionBeaconName));
  EXPECT_TRUE(first_redirector->RegisterAsFirstCFModule());

  // Ensure that we can acquire the mutex from medium integrity:
  {
    base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName));
    bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL);
    EXPECT_TRUE(mutex_locked);

    // We should be able to open the memory as read/write.
    EXPECT_TRUE(shared_memory.Open(kTestVersionBeaconName, false));
    shared_memory.Close();

    if (mutex_locked)
      shared_memory.Unlock();
  }

  if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
    // Now move to low integrity
    chrome_frame_test::LowIntegrityToken low_integrity_token;
    low_integrity_token.Impersonate();

    // Ensure that we can't acquire the mutex without having set the
    // Low Integrity ACE in the SACL.
    base::SharedMemory shared_memory(ASCIIToWide(kTestVersionBeaconName));
    bool mutex_locked = shared_memory.Lock(kWaitTestTimeout, NULL);
    EXPECT_FALSE(mutex_locked);

    // We shouldn't be able to open the memory.
    EXPECT_FALSE(shared_memory.Open(kTestVersionBeaconName, false));
    shared_memory.Close();

    if (mutex_locked)
      shared_memory.Unlock();
  }
}


text: {{ instance.content|safe }}


text:
struct A {
    int a;
    int b;
    usertype user_value;
    usertype user_value{'A'};
    int a[] = {1,2,3};
    scoped::templated<type> value;
    compound<typename templated::type *>::type value;
};

int a;
int b;
usertype user_value;
usertype user_value{'A'};
scoped::templated<type> value;
compound<typename templated::type *>::type value;
int a[] = {1,2,3};
void function_declaration(int *, usertype user_value);


text:
<?PHP

/* OmniCore
*  Version 0.1
*  Developed by Matt Howard, Phil Lopreiato
*  OmniCore
*/

//include 'common'.'Common' contains all necessary includes.
include "includes/common.php";

//connect to mySQL
mySQLConnect();

//get page info
$page = new url();
$page->init();

//user permissions
$editable = userPermissions(1);

if($page->error404 || !userPermissions(0)){
	header("HTTP/1.0 404 Not Found");
	echo file_get_contents("/omni/error.php?errorCode=404");
	exit;
	}

$menu = drawMenu();

//render final output
$skinVars = array();
$skinVars["additionalHead"] = "";
$skinVars["mainColumn"] = renderModules($page->pageId);
$skinVars["secondColumn"] = renderModules(0);
$skinVars["title"] = $page->title;
$skinVars["currentPage"] = $page->fullUrl;
$skinVars["sessionId"] = $user->data["session_id"];
$skinVars["pageId"] = $page->pageId;
$skinVars["topMenu"] = $menu[0];
$skinVars["secondMenu"] = $menu[1];
$skinVars["breadcrumbs"] = $page->breadCrumbs();

$options = array("ISHOME"=>($page->pageId==1));

//html tidy
// Specify configuration
$config = array(
           'indent'         => true,
		   'doctype'		=> "user",
           'wrap'           => 200);

$html = parseSkin($skinVars,"main",$options);

// Tidy
/*$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair(); */

echo $html;
?>


text:
package org.araqne.log.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.araqne.log.api.impl.FileUtils;

public class DirectoryWatchLogger extends AbstractLogger implements Reconfigurable {
	private final org.slf4j.Logger slog = org.slf4j.LoggerFactory.getLogger(DirectoryWatchLogger.class.getName());

	public DirectoryWatchLogger(LoggerSpecification spec, LoggerFactory factory) {
		super(spec, factory);
		File dataDir = new File(System.getProperty("araqne.data.dir"), "araqne-log-api");
		dataDir.mkdirs();

		// try migration at boot
		File oldLastFile = getLastLogFile(dataDir);
		if (oldLastFile.exists()) {
			Map<String, LastPosition> lastPositions = LastPositionHelper.readLastPositions(oldLastFile);
			setStates(LastPositionHelper.serialize(lastPositions));
			oldLastFile.renameTo(new File(oldLastFile.getAbsolutePath() + ".migrated"));
		}
	}

	@Override
	public void onConfigChange(Map<String, String> oldConfigs, Map<String, String> newConfigs) {
		if (!oldConfigs.get("base_path").equals(newConfigs.get("base_path"))
				|| !oldConfigs.get("filename_pattern").equals(newConfigs.get("filename_pattern"))) {
			setStates(new HashMap<String, Object>());
		}
	}

	@Override
	protected void runOnce() {
		Map<String, String> configs = getConfigs();

		String basePath = configs.get("base_path");
		Pattern fileNamePattern = Pattern.compile(configs.get("filename_pattern"));

		List<File> logFiles = FileUtils.matches(basePath, fileNamePattern);
		Map<String, LastPosition> lastPositions = LastPositionHelper.deserialize(getStates());

		for (File f : logFiles) {
			processFile(lastPositions, f, fileNamePattern);
		}

		lastPositions = updateLastSeen(lastPositions, logFiles);
		setStates(LastPositionHelper.serialize(lastPositions));
	}

	private Map<String, LastPosition> updateLastSeen(Map<String, LastPosition> lastPositions, List<File> logFiles) {
		Map<String, LastPosition> updatedLastPositions = new HashMap<String, LastPosition>();
		Set<String> filePaths = new HashSet<String>();
		for (File f : logFiles)
			filePaths.add(f.getAbsolutePath());

		long currentTime = new Date().getTime();
		for (String path : lastPositions.keySet()) {
			LastPosition p = lastPositions.get(path);
			if (p.getLastSeen() != null) {
				long limitTime = p.getLastSeen().getTime() + 3600000L;
				if (filePaths.contains(path)) {
					p.setLastSeen(null);
				} else if (limitTime <= currentTime) {
					continue;
				}
			} else {
				if (!filePaths.contains(path)) {
					p.setLastSeen(new Date());
				}
			}

			updatedLastPositions.put(path, p);
		}
		return updatedLastPositions;
	}

	protected void processFile(Map<String, LastPosition> lastPositions, File f, Pattern fileNamePattern) {
		if (!f.canRead()) {
			slog.debug("araqne log api: cannot read file [{}], logger [{}]", f.getAbsolutePath(), getFullName());
			return;
		}

		FileInputStream is = null;
		String path = f.getAbsolutePath();
		try {
			// get date pattern-matched string from filename
			String dateFromFileName = null;
			Matcher fileNameDateMatcher = fileNamePattern.matcher(f.getName());
			while (fileNameDateMatcher.find()) {
				int fileNameGroupCount = fileNameDateMatcher.groupCount();
				if (fileNameGroupCount > 0) {
					StringBuffer sb = new StringBuffer();
					for (int i = 1; i <= fileNameGroupCount; ++i) {
						sb.append(fileNameDateMatcher.group(i));
					}
					dateFromFileName = sb.toString();
				}
			}

			// skip previous read part
			long offset = 0;
			if (lastPositions.containsKey(path)) {
				LastPosition inform = lastPositions.get(path);
				offset = inform.getPosition();
				slog.trace("araqne log api: target file [{}] skip offset [{}]", path, offset);
			}

			AtomicLong lastPosition = new AtomicLong(offset);
			File file = new File(path);
			if (file.length() <= offset)
				return;

			is = new FileInputStream(file);
			is.skip(offset);

			Receiver receiver = new Receiver(getConfigs().get("file_tag"), file.getName());
			MultilineLogExtractor extractor = MultilineLogExtractor.build(this, receiver);
			extractor.extract(is, lastPosition, dateFromFileName);

			slog.debug("araqne log api: updating file [{}] old position [{}] new last position [{}]", new Object[] { path,
					offset, lastPosition.get() });
			LastPosition inform = lastPositions.get(path);
			if (inform == null) {
				inform = new LastPosition(path);
			}
			inform.setPosition(lastPosition.get());
			lastPositions.put(path, inform);
		} catch (FileNotFoundException e) {
			if (slog.isTraceEnabled())
				slog.trace("araqne log api: [" + getName() + "] logger read failure: file not found: {}", e.getMessage());
		} catch (Throwable e) {
			slog.error("araqne log api: [" + getName() + "] logger read error", e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
	}

	protected File getLastLogFile(File dataDir) {
		return new File(dataDir, "dirwatch-" + getName() + ".lastlog");
	}

	private class Receiver extends AbstractLogPipe {
		private String fileTag;
		private String fileName;

		public Receiver(String fileTag, String fileName) {
			this.fileTag = fileTag;
			this.fileName = fileName;
		}

		@Override
		public void onLog(Logger logger, Log log) {
			if (fileTag != null)
				log.getParams().put(fileTag, fileName);
			write(log);
		}

		@Override
		public void onLogBatch(Logger logger, Log[] logs) {
			if (fileTag != null) {
				for (Log log : logs) {
					log.getParams().put(fileTag, fileName);
				}
			}
			writeBatch(logs);
		}

	}
}