text:
class PlatformRemoteGDBServer : public lldb_private::Platform
{
public:

    static void
    Initialize ();

    static void
    Terminate ();

    static lldb_private::Platform*
    CreateInstance (bool force, const lldb_private::ArchSpec *arch);

    static lldb_private::ConstString
    GetPluginNameStatic();

    static const char *
    GetDescriptionStatic();

    PlatformRemoteGDBServer ();

    virtual
    ~PlatformRemoteGDBServer();

    //------------------------------------------------------------
    // lldb_private::PluginInterface functions
    //------------------------------------------------------------
    virtual lldb_private::ConstString
    GetPluginName()
    {
        return GetPluginNameStatic();
    }

    virtual uint32_t
    GetPluginVersion()
    {
        return 1;
    }

    //------------------------------------------------------------
    // lldb_private::Platform functions
    //------------------------------------------------------------
    virtual lldb_private::Error
    ResolveExecutable (const lldb_private::FileSpec &exe_file,
                       const lldb_private::ArchSpec &arch,
                       lldb::ModuleSP &module_sp,
                       const lldb_private::FileSpecList *module_search_paths_ptr);

    virtual const char *
    GetDescription ();

    virtual lldb_private::Error
    GetFileWithUUID (const lldb_private::FileSpec &platform_file,
                     const lldb_private::UUID *uuid_ptr,
                     lldb_private::FileSpec &local_file);

    virtual bool
    GetProcessInfo (lldb::pid_t pid,
                    lldb_private::ProcessInstanceInfo &proc_info);

    virtual uint32_t
    FindProcesses (const lldb_private::ProcessInstanceInfoMatch &match_info,
                   lldb_private::ProcessInstanceInfoList &process_infos);

    virtual lldb_private::Error
    LaunchProcess (lldb_private::ProcessLaunchInfo &launch_info);

    virtual lldb::ProcessSP
    DebugProcess (lldb_private::ProcessLaunchInfo &launch_info,
                  lldb_private::Debugger &debugger,
                  lldb_private::Target *target,       // Can be NULL, if NULL create a new target, else use existing one
                  lldb_private::Listener &listener,
                  lldb_private::Error &error);

    virtual lldb::ProcessSP
    Attach (lldb_private::ProcessAttachInfo &attach_info,
            lldb_private::Debugger &debugger,
            lldb_private::Target *target,       // Can be NULL, if NULL create a new target, else use existing one
            lldb_private::Listener &listener,
            lldb_private::Error &error);

    virtual bool
    GetSupportedArchitectureAtIndex (uint32_t idx, lldb_private::ArchSpec &arch);

    virtual size_t
    GetSoftwareBreakpointTrapOpcode (lldb_private::Target &target,
                                     lldb_private::BreakpointSite *bp_site);

    virtual bool
    GetRemoteOSVersion ();

    virtual bool
    GetRemoteOSBuildString (std::string &s);

    virtual bool
    GetRemoteOSKernelDescription (std::string &s);

    // Remote Platform subclasses need to override this function
    virtual lldb_private::ArchSpec
    GetRemoteSystemArchitecture ();

    virtual lldb_private::ConstString
    GetRemoteWorkingDirectory();

    virtual bool
    SetRemoteWorkingDirectory(const lldb_private::ConstString &path);

    // Remote subclasses should override this and return a valid instance
    // name if connected.
    virtual const char *
    GetHostname ();

    virtual const char *
    GetUserName (uint32_t uid);

    virtual const char *
    GetGroupName (uint32_t gid);

    virtual bool
    IsConnected () const;

    virtual lldb_private::Error
    ConnectRemote (lldb_private::Args& args);

    virtual lldb_private::Error
    DisconnectRemote ();

    virtual lldb_private::Error
    MakeDirectory (const char *path, uint32_t file_permissions);

    virtual lldb_private::Error
    GetFilePermissions (const char *path, uint32_t &file_permissions);

    virtual lldb_private::Error
    SetFilePermissions (const char *path, uint32_t file_permissions);

    virtual lldb::user_id_t
    OpenFile (const lldb_private::FileSpec& file_spec,
              uint32_t flags,
              uint32_t mode,
              lldb_private::Error &error);

    virtual bool
    CloseFile (lldb::user_id_t fd,
               lldb_private::Error &error);

    virtual uint64_t
    ReadFile (lldb::user_id_t fd,
              uint64_t offset,
              void *data_ptr,
              uint64_t len,
              lldb_private::Error &error);

    virtual uint64_t
    WriteFile (lldb::user_id_t fd,
               uint64_t offset,
               const void* data,
               uint64_t len,
               lldb_private::Error &error);

    virtual lldb::user_id_t
    GetFileSize (const lldb_private::FileSpec& file_spec);

    virtual lldb_private::Error
    PutFile (const lldb_private::FileSpec& source,
             const lldb_private::FileSpec& destination,
             uint32_t uid = UINT32_MAX,
             uint32_t gid = UINT32_MAX);

    virtual lldb_private::Error
    CreateSymlink (const char *src, const char *dst);

    virtual bool
    GetFileExists (const lldb_private::FileSpec& file_spec);

    virtual lldb_private::Error
    Unlink (const char *path);

    virtual lldb_private::Error
    RunShellCommand (const char *command,           // Shouldn't be NULL
                     const char *working_dir,       // Pass NULL to use the current working directory
                     int *status_ptr,               // Pass NULL if you don't want the process exit status
                     int *signo_ptr,                // Pass NULL if you don't want the signal that caused the process to exit
                     std::string *command_output,   // Pass NULL if you don't want the command output
                     uint32_t timeout_sec);         // Timeout in seconds to wait for shell program to finish

    virtual void
    CalculateTrapHandlerSymbolNames ();

protected:
    GDBRemoteCommunicationClient m_gdb_client;
    std::string m_platform_description; // After we connect we can get a more complete description of what we are connected to

private:
    DISALLOW_COPY_AND_ASSIGN (PlatformRemoteGDBServer);

};

#endif  // liblldb_PlatformRemoteGDBServer_h_


text:
# IApplication.UpdateAsync Method

Update an application

**Namespace:** Bandwidth.Net.Api
**Assembly:** Bandwidth.Net (in Bandwidth.Net.dll) Version: 3.0.3

## Syntax

**C#**

``` C#
Task UpdateAsync(
	string applicationId,
	UpdateApplicationData data,
	Nullable<CancellationToken> cancellationToken = null
)
```

#### Parameters

applicationId

Type: System.String
Id of application to change

data

Type: Bandwidth.Net.Api.UpdateApplicationData
Changed data

cancellationToken (Optional)

Type: System.Nullable(CancellationToken)
Optional token to cancel async operation

#### Return Value
Type: Task
Task instance for async operation

## Examples

```
await client.Application.UpdateAsync("applicationId", new UpdateApplicationData {Name = "NewName"});
```

## See Also

#### Reference
IApplication Interface
Bandwidth.Net.Api Namespace

redpajama_set_name: RedPajamaGithub


text:
Found a bug? Awesome! First of all, let's collect some information:

1. What are the exact steps to reproduce the bug?
2. What is happening?
3. What would you expect to happen instead?

If you got these, head on over to the [issues section](https://github.com/opsbears/owc-dic/issues). Please make sure
that the issue hasn't been reported before, and then submit your issue. That's it!

## Pull requests

Have a fix for something? Awesome! Here's what you need to do:

1. Make sure you read and understand the license agreement for this repo.
2. Fork the repo into your GitHub account.
3. Apply the fix in a branch.
4. Make sure you have ONLY the changes relevant to that fix in the branch. No whitespace changes and other stuff, that will prevent us from merging it.
5. Open a [pull request](https://github.com/opsbears/owc-dic/pulls) and make sure you are describing your fix in detail.
6. We'll get back to you as soon as possible!


text:
@implementation AsyncMediaTouchableImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.userInteractionEnabled = YES;

    }
    return self;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([self.delegate respondsToSelector:(@selector(asyncMediaImageTouched:))])
        [(UIView <AsyncMediaTouchableImageViewDelegate> *)self.delegate asyncMediaImageTouched:self];
}

@end


text:
title: 'Great Architecture Movies'
date: 2011-03-28T14:35:00.000-06:00
draft: false
slug: great-architecture-movies
tags: [Architecture Movies]
---

Do you need something positive to watch from time to time to help you vision your perfect way of being in the world and in your space? Here are some movies, websites, and videos that we've been inspired by!

_Architecture through history_

42nd Street

Aboriginal Architecture Living Architecture

Aeon Flux

Agora

Alphaville

Architectures

Bangkok Dangerous

Barton Fink

Batman Begins

Beauty and the Beast (1946)

Blade Runner

Brazil

Chartres Cathedral - A Sacred Geometry

Chronos: A Visual And Musical Journey Through Time

City of Dreams

Dancing About Architecture

Dark City

Days of Heaven

Die Hard

Downton Abbey

Dodes'ka-den (Kurosawa)

Drawing by numbers

e2: Design (PBS video)

Empire

Future by Design

Gattaca

Ghostbusters

Gosford park

Hausu

Housekeeping

Imagine

Inception

The International

Karate Kid 3

Kikuchi

Last Year at Mirienbad

Magnificent Ambersons

Marie Antoinette

Memoirs of a Geisha

Metropolis

Midnight in Paris

Mildred Pierce

Mon Oncle

Mystic Pizza

Nosfaratu

Oscar and Lucinda

Paranormal Activity

Paperhouse

Psycho

Quo Vadis

Rear Window

Rebecca

Riddles in Stone - Secret Mysteries of America's Beginnings Volume II: Secret Architecture of Washington, D.C.

Ring/Ju-on

Rome: Engineering an Empire

Rosemary's Baby

Russian Ark

Skyscraper

Skyscraper Souls

Sliver

Sunrise

Suspiria

The 13th Floor

The 14 Wonders of the World ancient and new

The Alamo

The Black Cat

The Clock

The Da Vinci Code

The Eagle (Roman design)

The Enchanted Cottage

The Fall of the Roman Empire

The Haunting

The Heiress

The House of Usher

The Hudsucker Proxy

The International

The Gold Rush

The Lady and The Duke

The Lake House

The Last Samurai

The Magnificent Ambersons

The Man With the Movie Camera

The Money Pit

The Naked City

The Orphanage (Spanish, 2007)

The Terminal

Thirteen Ghosts

Ultimate Heist (French version) with Jean Reno

Un couple (tout à l'envers)

Under the Tuscan Sun

Vicky Christina Barcelona

Wavelength

Weekend at the Waldorf

Wings of Desire

_Architects in the Movies_

12 Angry Men

A Moment to Remember

Antonio Gaudi

Atlas Shrugged

Belly of an Architect

D' Annunzio's Cave

Die Architekten

Frank Lloyd Wright - A film by Ken Burns and Lynn Novick

Garbage Warrior

Houselife - Rem Koolhaas

I.M. Pei - First Person Singular/The Museum on the Mountain

Indecent Proposal

Inspirations

Intersection

Life as a House

Learning from Bob and Denise

Maya Lin: A Strong Clear Vision

Modern Marvels - Gothic Cathedrals (History Channel) (A&E DVD Archives)

Mr. Blandings Builds His Dream House

My Architect: A Son's Journey

Pi

Salaam Namaste

Sketches of Frank Gehry by Sydney Pollack

Sleepless in Seattle

Strangers When We Meet

The Architect

The Architects

The Belly of an Architect

The Films of Charles & Ray Eames - The Powers of 10

The Fountainhead

The Homes of Frank Lloyd Wright (A&E DVD Archives)

The Towering Inferno

Visual Acoustics: The Modernism of Julius Schulman

When Harry Met Sally

_Design Inspirations_

Between the Folds

Dirt! The Movie

Freakonomics


text:
/*jshint esversion: 6 */

import './boolean-radios.js';


text:
#ifndef _UAPI_LINUX_KD_H
#define _UAPI_LINUX_KD_H
#include <linux/types.h>
#include <linux/compiler.h>
#define GIO_FONT 0x4B60
#define PIO_FONT 0x4B61
#define GIO_FONTX 0x4B6B
#define PIO_FONTX 0x4B6C
struct consolefontdesc {
  unsigned short charcount;
  unsigned short charheight;
  char __user * chardata;
};
#define PIO_FONTRESET 0x4B6D
#define GIO_CMAP 0x4B70
#define PIO_CMAP 0x4B71
#define KIOCSOUND 0x4B2F
#define KDMKTONE 0x4B30
#define KDGETLED 0x4B31
#define KDSETLED 0x4B32
#define LED_SCR 0x01
#define LED_NUM 0x02
#define LED_CAP 0x04
#define KDGKBTYPE 0x4B33
#define KB_84 0x01
#define KB_101 0x02
#define KB_OTHER 0x03
#define KDADDIO 0x4B34
#define KDDELIO 0x4B35
#define KDENABIO 0x4B36
#define KDDISABIO 0x4B37
#define KDSETMODE 0x4B3A
#define KD_TEXT 0x00
#define KD_GRAPHICS 0x01
#define KD_TEXT0 0x02
#define KD_TEXT1 0x03
#define KDGETMODE 0x4B3B
#define KDMAPDISP 0x4B3C
#define KDUNMAPDISP 0x4B3D
typedef char scrnmap_t;
#define E_TABSZ 256
#define GIO_SCRNMAP 0x4B40
#define PIO_SCRNMAP 0x4B41
#define GIO_UNISCRNMAP 0x4B69
#define PIO_UNISCRNMAP 0x4B6A
#define GIO_UNIMAP 0x4B66
struct unipair {
  unsigned short unicode;
  unsigned short fontpos;
};
struct unimapdesc {
  unsigned short entry_ct;
  struct unipair __user * entries;
};
#define PIO_UNIMAP 0x4B67
#define PIO_UNIMAPCLR 0x4B68
struct unimapinit {
  unsigned short advised_hashsize;
  unsigned short advised_hashstep;
  unsigned short advised_hashlevel;
};
#define UNI_DIRECT_BASE 0xF000
#define UNI_DIRECT_MASK 0x01FF
#define K_RAW 0x00
#define K_XLATE 0x01
#define K_MEDIUMRAW 0x02
#define K_UNICODE 0x03
#define K_OFF 0x04
#define KDGKBMODE 0x4B44
#define KDSKBMODE 0x4B45
#define K_METABIT 0x03
#define K_ESCPREFIX 0x04
#define KDGKBMETA 0x4B62
#define KDSKBMETA 0x4B63
#define K_SCROLLLOCK 0x01
#define K_NUMLOCK 0x02
#define K_CAPSLOCK 0x04
#define KDGKBLED 0x4B64
#define KDSKBLED 0x4B65
struct kbentry {
  unsigned char kb_table;
  unsigned char kb_index;
  unsigned short kb_value;
};
#define K_NORMTAB 0x00
#define K_SHIFTTAB 0x01
#define K_ALTTAB 0x02
#define K_ALTSHIFTTAB 0x03
#define KDGKBENT 0x4B46
#define KDSKBENT 0x4B47
struct kbsentry {
  unsigned char kb_func;
  unsigned char kb_string[512];
};
#define KDGKBSENT 0x4B48
#define KDSKBSENT 0x4B49
struct kbdiacr {
  unsigned char diacr, base, result;
};
struct kbdiacrs {
  unsigned int kb_cnt;
  struct kbdiacr kbdiacr[256];
};
#define KDGKBDIACR 0x4B4A
#define KDSKBDIACR 0x4B4B
struct kbdiacruc {
  unsigned int diacr, base, result;
};
struct kbdiacrsuc {
  unsigned int kb_cnt;
  struct kbdiacruc kbdiacruc[256];
};
#define KDGKBDIACRUC 0x4BFA
#define KDSKBDIACRUC 0x4BFB
struct kbkeycode {
  unsigned int scancode, keycode;
};
#define KDGETKEYCODE 0x4B4C
#define KDSETKEYCODE 0x4B4D
#define KDSIGACCEPT 0x4B4E
struct kbd_repeat {
  int delay;
  int period;
};
#define KDKBDREP 0x4B52
#define KDFONTOP 0x4B72
struct console_font_op {
  unsigned int op;
  unsigned int flags;
  unsigned int width, height;
  unsigned int charcount;
  unsigned char __user * data;
};
struct console_font {
  unsigned int width, height;
  unsigned int charcount;
  unsigned char * data;
};
#define KD_FONT_OP_SET 0
#define KD_FONT_OP_GET 1
#define KD_FONT_OP_SET_DEFAULT 2
#define KD_FONT_OP_COPY 3
#define KD_FONT_FLAG_DONT_RECALC 1
#endif


text:
namespace Logging {

namespace {

std::string formatPattern(const std::string& pattern, const std::string& category, Level level, boost::posix_time::ptime time) {
  std::stringstream s;

  for (const char* p = pattern.c_str(); p && *p != 0; ++p) {
    if (*p == '%') {
      ++p;
      switch (*p) {
      case 0:
        break;
      case 'C':
        s << category;
        break;
      case 'D':
        s << time.date();
        break;
      case 'T':
        s << time.time_of_day();
        break;
      case 'L':
        s << ILogger::LEVEL_NAMES[level];
        break;
      default:
        s << *p;
      }
    } else {
      s << *p;
    }
  }

  return s.str();
}

}

void CommonLogger::operator()(const std::string& category, Level level, boost::posix_time::ptime time, const std::string& body) {
  if (level <= logLevel && disabledCategories.count(category) == 0) {
    std::string body2 = body;
    if (!pattern.empty()) {
      size_t insertPos = 0;
      if (!body2.empty() && body2[0] == ILogger::COLOR_DELIMETER) {
        size_t delimPos = body2.find(ILogger::COLOR_DELIMETER, 1);
        if (delimPos != std::string::npos) {
          insertPos = delimPos + 1;
        }
      }

      body2.insert(insertPos, formatPattern(pattern, category, level, time));
    }

    doLogString(body2);
  }
}

void CommonLogger::setPattern(const std::string& pattern) {
  this->pattern = pattern;
}

void CommonLogger::enableCategory(const std::string& category) {
  disabledCategories.erase(category);
}

void CommonLogger::disableCategory(const std::string& category) {
  disabledCategories.insert(category);
}

void CommonLogger::setMaxLevel(Level level) {
  logLevel = level;
}

CommonLogger::CommonLogger(Level level) : logLevel(level), pattern("%D %T %L [%C] ") {
}

void CommonLogger::doLogString(const std::string& message) {
}

}


text:
package juja.google.spreadsheet.api.gdata;

import com.google.gdata.data.spreadsheet.CustomElementCollection;
import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.util.ServiceException;
import juja.google.spreadsheet.api.Cell;
import juja.google.spreadsheet.api.SpreadSheetReader;

import java.io.IOException;

public class GdataCell implements Cell {

    private final ListEntry entry;
    private final String searchColumn;
    private final String header;

    public GdataCell(
            SpreadSheetReader spreadsheet, String searchColumn, String header, String colValue
    ) throws IOException, ServiceException {
        this.searchColumn = searchColumn;
        this.header = header;

        entry = spreadsheet.findRowByColumnValue(header, colValue);
    }

    @Override
    public void update(String value) throws IOException, ServiceException {
        CustomElementCollection customElements = entry.getCustomElements();
        customElements.setValueLocal(searchColumn, value);
        String escaped = escapePlus(customElements.getValue(header));
        customElements.setValueLocal(header, escaped);

        entry.update();
    }

    private String escapePlus(String value) {
        StringBuilder res = new StringBuilder();
        if (value.startsWith("+")) {
            res.append("'").append(value);
        } else {
            res.append(value);
        }
        return res.toString();
    }

    @Override
    public String value() {
        return this.entry.getCustomElements().getValue(searchColumn);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<fileResource exportedWithPermissions="true" dataFile="sort_filter_icons_sprite.png.data">
    <folder>/organizations/organization_1/themes/default/images</folder>
    <name>sort_filter_icons_sprite.png</name>
    <version>0</version>
    <label>sort_filter_icons_sprite.png</label>
    <creationDate>2015-05-27T15:05:03.670-07:00</creationDate>
    <updateDate>2015-05-27T15:05:03.670-07:00</updateDate>
    <fileType>img</fileType>
</fileResource>


text:
using CrmCodeGenerator.VSPackage.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrmCodeGenerator.VSPackage
{
    public class Configuration
    {

        #region Singleton
        private static Configuration _instance;
        private static Object SyncLock = new System.Object();
        public static Configuration Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Configuration();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        public Configuration()
        {
            Settings = new CrmCodeGenerator.VSPackage.Model.Settings();
            Settings.CrmSdkUrl = @"https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc";
            Settings.ProjectName = "";
            Settings.Domain = "";
            Settings.T4Path = System.IO.Path.Combine(DteHelper.AssemblyDirectory(), @"Resources\Templates\CrmSvcUtil.tt");
            Settings.Template = "";
            Settings.CrmOrg = "DEV-CRM";
            Settings.EntitiesToIncludeString = "account,contact,lead,opportunity,systemuser";
            Settings.OutputPath = "";
            Settings.Username = "@XXXXX.onmicrosoft.com";
            Settings.Password = "";
            Settings.Namespace = "";
            Settings.Dirty = false;
        }
        public CrmCodeGenerator.VSPackage.Model.Settings Settings { get; set; }
        public EnvDTE80.DTE2 DTE { get; set; }
    }
}


text:
var ebml = require('../lib/ebml/index.js'),
    assert = require('assert');

describe('embl', function() {
    describe('Pipeline', function() {
        it('should output input buffer', function(done) {
            var decoder = new ebml.Decoder();
            var encoder = new ebml.Encoder();
            var buffer = new Buffer([0x1a, 0x45, 0xdf, 0xa3, 0x84, 0x42, 0x86, 0x81, 0x00]);
            encoder.on('data', function(chunk) {
                assert.equal(chunk.toString('hex'), buffer.toString('hex'));
                done();
            });
            decoder.pipe(encoder);
            decoder.write(buffer);
        });

        it('should support end === -1', function (done) {
            var decoder = new ebml.Decoder();
            var encoder = new ebml.Encoder();

            encoder.write(['start', {name: 'Cluster', start: 0, end: -1}]);
            encoder.write(['end', {name: 'Cluster', start: 0, end: -1}]);

            encoder.pipe(decoder).on('data', function (data) {
                assert.equal(data[1].name, 'Cluster');
                assert.equal(data[1].start, 0);
                assert.equal(data[1].end, -1);
                done();
            });
        });
    });
});


text:
package edu.coldserenity.tij.ch06.ex23;

/**
 * Exercise 23: (2)
 * <p/>
 * Prove that class loading takes place only once. Prove that loading
 * may be caused by either the creation of the first instance of that
 * class or by the access of a static member.
 */
public class ClassLoadingTest {
    public static void main(String[] args) {
        // initialization happened on constructor access
        new Class1();

        // initialization on static field access
        int k = Class2.i;

        // initialization on static method access
        Class3.test();

        // Class4 initialization never happens
    }
}

class Base {
    static {
        System.out.println("Base class has been initialized. This happens only once");
    }

    protected static int initializeInt(int val) {
        System.out.println("Initialized " + val);
        return val;
    }
}

class Class1 extends Base {
    static int i = initializeInt(1);
}

class Class2 extends Base {
    static int i = initializeInt(2);
}

class Class3 extends Base {
    static int i = initializeInt(3);

    static int test() {
        return 100;
    }
}

class Class4 extends Base {
    static int i = initializeInt(4);
}


text:
package com.comtop.meeting.entity;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 会议室实体类
 */
@Entity
@Table(name = "t_meeting_room")
public class MeetingRoom {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "NAME")
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}


text:
[![Build Status](https://travis-ci.org/c4milo/node-inotify.svg?branch=master)](https://travis-ci.org/c4milo/node-inotify)

The inotify API provides a mechanism for monitoring file system events.
Inotify can be used to monitor individual files, or to monitor directories.
When a directory is monitored, inotify will return events for the directory
itself, and for files inside the directory. [(ref: GNU/Linux Manual)][inotify.7]

## Installation
[NodeJS][nodejs_dev] versions 0.8.x, 0.10.x and 0.12.x are currently supported and tested.

### Install from NPM (Easy way)
    $ npm install inotify

### Install from git
    $ npm install node-gyp -g
    $ git clone git://github.com/c4milo/node-inotify.git
    $ cd node-inotify
    $ node-gyp rebuild

## API
  * `var inotify = new Inotify()`: Create a new instance of Inotify. By default it's in persistent mode.
  You can specify `false` in `var inotify = new Inotify(false)` to use the non persistent mode.

  * `var wd = inotify.addWatch(arg)`:  Add a watch for files or directories. This will then return a watch descriptor. The argument is an object as follows
        var arg = { path: 'path to be monitored',
                    watch_for: an optional OR'ed set of events to watch for.
                               If they're not specified, it will use
                               Inotify.IN_ALL_EVENTS by default,
                    callback: Callback function that will receive each event.
        }
You can call this function as many times as you want to monitor different paths.
**Inotify monitoring of directories is not recursive**: to monitor subdirectories
under a directory, additional watches must be created.

  * `inotify.removeWatch(watch_descriptor)`: Remove a watch associated with the watch_descriptor param and returns `true` if the action was succesful or `false` in the opposite case. Removing a watch cause an `Inotify.IN_IGNORED` event to be generated for this watch descriptor.

  * `inotify.close()`: Remove all the watches and close the inotify's file descriptor. Returns `true` if the action was succesful or false in the opposite case.

### Event object structure
```javascript
    var event = {   watch: Watch descriptor,
                    mask: Mask of events,
                    cookie: Cookie that permits to associate events,
                    name: Optional name of the object being watched
                };
```

The `event.name` property is only present when an event is returned for a file inside a
watched directory; it identifies the file pathname relative to the watched
directory.

## Example of use

```javascript
    var Inotify = require('inotify').Inotify;
    var inotify = new Inotify(); //persistent by default, new Inotify(false) //no persistent

    var data = {}; //used to correlate two events

    var callback = function(event) {
        var mask = event.mask;
        var type = mask & Inotify.IN_ISDIR ? 'directory ' : 'file ';
        event.name ? type += ' ' + event.name + ' ': ' ';

        //the porpuse of this hell of 'if'
        //statements is only illustrative.

        if(mask & Inotify.IN_ACCESS) {
            console.log(type + 'was accessed ');
        } else if(mask & Inotify.IN_MODIFY) {
            console.log(type + 'was modified ');
        } else if(mask & Inotify.IN_OPEN) {
            console.log(type + 'was opened ');
        } else if(mask & Inotify.IN_CLOSE_NOWRITE) {
            console.log(type + ' opened for reading was closed ');
        } else if(mask & Inotify.IN_CLOSE_WRITE) {
            console.log(type + ' opened for writing was closed ');
        } else if(mask & Inotify.IN_ATTRIB) {
            console.log(type + 'metadata changed ');
        } else if(mask & Inotify.IN_CREATE) {
            console.log(type + 'created');
        } else if(mask & Inotify.IN_DELETE) {
            console.log(type + 'deleted');
        } else if(mask & Inotify.IN_DELETE_SELF) {
            console.log(type + 'watched deleted ');
        } else if(mask & Inotify.IN_MOVE_SELF) {
            console.log(type + 'watched moved');
        } else if(mask & Inotify.IN_IGNORED) {
            console.log(type + 'watch was removed');
        } else if(mask & Inotify.IN_MOVED_FROM) {
            data = event;
            data.type = type;
        } else if(mask & Inotify.IN_MOVED_TO) {
            if( Object.keys(data).length &&
                data.cookie === event.cookie) {
                console.log(type + ' moved to ' + data.type);
                data = {};
            }
        }
    }
    var home_dir = { path:      '/home/camilo', // <--- change this for a valid directory in your machine.
                     watch_for: Inotify.IN_OPEN | Inotify.IN_CLOSE,
                     callback:  callback
                  };

    var home_watch_descriptor = inotify.addWatch(home_dir);

    var home2_dir = { path:      '/home/bob', // <--- change this for a valid directory in your machine
                      watch_for: Inotify.IN_ALL_EVENTS,
                      callback:  callback
                  };

    var home2_wd = inotify.addWatch(home2_dir);

```

## Inotify Events

### Watch for:
 * **Inotify.IN_ACCESS:** File was accessed (read)
 * **Inotify.IN_ATTRIB:** Metadata changed, e.g., permissions, timestamps, extended attributes, link count (since Linux 2.6.25), UID, GID, etc.
 * **Inotify.IN_CLOSE_WRITE:** File opened for writing was closed
 * **Inotify.IN_CLOSE_NOWRITE:** File not opened for writing was closed
 * **Inotify.IN_CREATE:** File/directory created in the watched directory
 * **Inotify.IN_DELETE:** File/directory deleted from the watched directory
 * **Inotify.IN_DELETE_SELF:** Watched file/directory was deleted
 * **Inotify.IN_MODIFY:** File was modified
 * **Inotify.IN_MOVE_SELF:** Watched file/directory was moved
 * **Inotify.IN_MOVED_FROM:** File moved out of the watched directory
 * **Inotify.IN_MOVED_TO:** File moved into watched directory
 * **Inotify.IN_OPEN:** File was opened
 * **Inotify.IN_ALL_EVENTS:** Watch for all kind of events
 * **Inotify.IN_CLOSE:**  (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE)  Close
 * **Inotify.IN_MOVE:**  (IN_MOVED_FROM | IN_MOVED_TO)  Moves

### Additional Flags:
 * **Inotify.IN_ONLYDIR:** Only watch the path if it is a directory.
 * **Inotify.IN_DONT_FOLLOW:** Do not follow symbolics links
 * **Inotify.IN_ONESHOT:** Only send events once
 * **Inotify.IN_MASK_ADD:** Add (OR) events to watch mask for this pathname if it already exists (instead of replacing the mask).

### The following bits may be set in the `event.mask` property returned in the callback
 * **Inotify.IN_IGNORED:** Watch was removed explicitly with inotify.removeWatch(watch_descriptor) or automatically (the file was deleted, or the file system was unmounted)
 * **Inotify.IN_ISDIR:** Subject of this event is a directory
 * **Inotify.IN_Q_OVERFLOW:** Event queue overflowed (wd is -1 for this event)
 * **Inotify.IN_UNMOUNT:** File system containing the watched object was unmounted

## FAQ
### Why inotify does not watch directories recursively?
http://www.quora.com/Inotify-monitoring-of-directories-is-not-recursive-Is-there-any-specific-reason-for-this-design-in-Linux-kernel

## License
(The MIT License)

Copyright 2015 Camilo Aguilar. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

[inotify.7]: http://www.kernel.org/doc/man-pages/online/pages/man7/inotify.7.html "http://www.kernel.org/doc/man-pages/online/pages/man7/inotify.7.html"
[nodejs_home]: http://www.nodejs.org
[nodejs_dev]: http://github.com/joyent/node
[code_example]: http://gist.github.com/476119


text:
var tests = require('../helpers/algorithm-tests');
var algorithm = require('../../src/algorithms/dijkstra-fibonacci-heap');

describe('dijkstra-fibonacci-heap', function () {
  'use strict';

  tests(algorithm);
});


text:
package org.kuali.kfs.module.bc.document.web.struts;

import org.kuali.kfs.module.bc.businessobject.BudgetConstructionMonthly;
import org.kuali.kfs.module.bc.document.service.BenefitsCalculationService;
import org.kuali.kfs.module.bc.document.service.SalarySettingService;
import org.kuali.kfs.sys.context.SpringContext;

public class MonthlyBudgetForm extends BudgetExpansionForm {
    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(MonthlyBudgetForm.class);

    private BudgetConstructionMonthly budgetConstructionMonthly;
    private boolean monthlyPersisted;
    private boolean monthlyReadOnly = true;
    private boolean budgetableDocument = false;

    private boolean hideDetails = false;

    // url parameters sent from BCDoc
    private String documentNumber;
    private String chartOfAccountsCode;
    private String accountNumber;
    private String subAccountNumber;
    private String financialObjectCode;
    private String financialSubObjectCode;
    private String financialBalanceTypeCode;
    private String financialObjectTypeCode;

    private boolean revenue = false;

    public MonthlyBudgetForm() {
        super();
        setBudgetConstructionMonthly(new BudgetConstructionMonthly());
    }

    /**
     * Gets the budgetConstructioMonthly attribute.
     *
     * @return Returns the budgetConstructioMonthly.
     */
    public BudgetConstructionMonthly getBudgetConstructionMonthly() {
        return budgetConstructionMonthly;
    }

    /**
     * Sets the budgetConstructioMonthly attribute value.
     *
     * @param budgetConstructioMonthly The budgetConstructioMonthly to set.
     */
    public void setBudgetConstructionMonthly(BudgetConstructionMonthly budgetConstructionMonthly) {
        this.budgetConstructionMonthly = budgetConstructionMonthly;
    }

    /**
     * Gets the accountNumber attribute.
     *
     * @return Returns the accountNumber.
     */
    public String getAccountNumber() {
        return accountNumber;
    }

    /**
     * Sets the accountNumber attribute value.
     *
     * @param accountNumber The accountNumber to set.
     */
    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    /**
     * Gets the chartOfAccountsCode attribute.
     *
     * @return Returns the chartOfAccountsCode.
     */
    public String getChartOfAccountsCode() {
        return chartOfAccountsCode;
    }

    /**
     * Sets the chartOfAccountsCode attribute value.
     *
     * @param chartOfAccountsCode The chartOfAccountsCode to set.
     */
    public void setChartOfAccountsCode(String chartOfAccountsCode) {
        this.chartOfAccountsCode = chartOfAccountsCode;
    }

    /**
     * Gets the documentNumber attribute.
     *
     * @return Returns the documentNumber.
     */
    public String getDocumentNumber() {
        return documentNumber;
    }

    /**
     * Sets the documentNumber attribute value.
     *
     * @param documentNumber The documentNumber to set.
     */
    public void setDocumentNumber(String documentNumber) {
        this.documentNumber = documentNumber;
    }

    /**
     * Gets the financialBalanceTypeCode attribute.
     *
     * @return Returns the financialBalanceTypeCode.
     */
    public String getFinancialBalanceTypeCode() {
        return financialBalanceTypeCode;
    }

    /**
     * Sets the financialBalanceTypeCode attribute value.
     *
     * @param financialBalanceTypeCode The financialBalanceTypeCode to set.
     */
    public void setFinancialBalanceTypeCode(String financialBalanceTypeCode) {
        this.financialBalanceTypeCode = financialBalanceTypeCode;
    }

    /**
     * Gets the financialObjectCode attribute.
     *
     * @return Returns the financialObjectCode.
     */
    public String getFinancialObjectCode() {
        return financialObjectCode;
    }

    /**
     * Sets the financialObjectCode attribute value.
     *
     * @param financialObjectCode The financialObjectCode to set.
     */
    public void setFinancialObjectCode(String financialObjectCode) {
        this.financialObjectCode = financialObjectCode;
    }

    /**
     * Gets the financialObjectTypeCode attribute.
     *
     * @return Returns the financialObjectTypeCode.
     */
    public String getFinancialObjectTypeCode() {
        return financialObjectTypeCode;
    }

    /**
     * Sets the financialObjectTypeCode attribute value.
     *
     * @param financialObjectTypeCode The financialObjectTypeCode to set.
     */
    public void setFinancialObjectTypeCode(String financialObjectTypeCode) {
        this.financialObjectTypeCode = financialObjectTypeCode;
    }

    /**
     * Gets the financialSubObjectCode attribute.
     *
     * @return Returns the financialSubObjectCode.
     */
    public String getFinancialSubObjectCode() {
        return financialSubObjectCode;
    }

    /**
     * Sets the financialSubObjectCode attribute value.
     *
     * @param financialSubObjectCode The financialSubObjectCode to set.
     */
    public void setFinancialSubObjectCode(String financialSubObjectCode) {
        this.financialSubObjectCode = financialSubObjectCode;
    }

    /**
     * Gets the subAccountNumber attribute.
     *
     * @return Returns the subAccountNumber.
     */
    public String getSubAccountNumber() {
        return subAccountNumber;
    }

    /**
     * Sets the subAccountNumber attribute value.
     *
     * @param subAccountNumber The subAccountNumber to set.
     */
    public void setSubAccountNumber(String subAccountNumber) {
        this.subAccountNumber = subAccountNumber;
    }

    /**
     * Gets the monthlyPersisted attribute.
     *
     * @return Returns the monthlyPersisted.
     */
    public boolean isMonthlyPersisted() {
        return monthlyPersisted;
    }

    /**
     * Sets the monthlyPersisted attribute value.
     *
     * @param monthlyPersisted The monthlyPersisted to set.
     */
    public void setMonthlyPersisted(boolean monthlyPersisted) {
        this.monthlyPersisted = monthlyPersisted;
    }

    /**
     * Gets the readOnly attribute.
     *
     * @return Returns the readOnly.
     */
    public boolean isMonthlyReadOnly() {
        return monthlyReadOnly;
    }

    /**
     * Sets the readOnly attribute value.
     *
     * @param readOnly The readOnly to set.
     */
    public void setMonthlyReadOnly(boolean readOnly) {
        this.monthlyReadOnly = readOnly;
    }

    /**
     * Gets the budgetableDocument attribute.
     *
     * @return Returns the budgetableDocument.
     */
    public boolean isBudgetableDocument() {
        return budgetableDocument;
    }

    /**
     * Sets the budgetableDocument attribute value.
     *
     * @param budgetableDocument The budgetableDocument to set.
     */
    public void setBudgetableDocument(boolean budgetableDocument) {
        this.budgetableDocument = budgetableDocument;
    }

    /**
     * Gets the benefitsCalculationDisabled attribute.
     *
     * @return Returns the benefitsCalculationDisabled.
     */
    public boolean isBenefitsCalculationDisabled() {
        return SpringContext.getBean(BenefitsCalculationService.class).isBenefitsCalculationDisabled();
    }

    /**
     * Gets the salarySettingDisabled attribute.
     *
     * @return Returns the salarySettingDisabled.
     */
    public boolean isSalarySettingDisabled() {
        return SpringContext.getBean(SalarySettingService.class).isSalarySettingDisabled();
    }

    /**
     * Gets the hideDetails attribute.
     *
     * @return Returns the hideDetails.
     */
    public boolean isHideDetails() {
        return hideDetails;
    }

    /**
     * Sets the hideDetails attribute value.
     *
     * @param hideDetails The hideDetails to set.
     */
    public void setHideDetails(boolean hideDetails) {
        this.hideDetails = hideDetails;
    }

    /**
     * Gets the revenue attribute.
     *
     * @return Returns the revenue
     */

    public boolean isRevenue() {
        return revenue;
    }

    /**
     * Sets the revenue attribute.
     *
     * @param revenue The revenue to set.
     */
    public void setRevenue(boolean revenue) {
        this.revenue = revenue;
    }

}


text:
{% extends base_template %}
{% block page_tabs %}

Schemas

Reports

{% endblock %}
{% block content %}
{% block mgr_content %}
{%endblock%}
{%endblock%}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>WebGL GLSL conformance test: built_in_varying_array_out_of_bounds_001_to_001.html</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css" />
<link rel="stylesheet" href="../../../resources/ogles-tests.css" />

<canvas id="example" width="500" height="500" style="width: 16px; height: 16px;"></canvas>


text:
package cn.felord.wepay.ali.sdk.api.domain;

import java.util.Date;
import java.util.List;

import cn.felord.wepay.ali.sdk.api.AlipayObject;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField;
import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiListField;

/**
 * 卡模板权益信息
 *
 * @author auto create
 * @version $Id: $Id
 */
public class TemplateBenefitInfoDTO extends AlipayObject {

	private static final long serialVersionUID = 7133663384224756512L;

	/**
	 * 权益描述信息
	 */
	@ApiListField("benefit_desc")
	@ApiField("string")
	private List<String> benefitDesc;

	/**
	 * 权益结束时间
	 */
	@ApiField("end_date")
	private Date endDate;

	/**
	 * 开始时间
	 */
	@ApiField("start_date")
	private Date startDate;

	/**
	 * 权益描述
	 */
	@ApiField("title")
	private String title;

	/**
	 *
Getter for the field benefitDesc.

	 *
	 * @return a {@link java.util.List} object.
	 */
	public List<String> getBenefitDesc() {
		return this.benefitDesc;
	}
	/**
	 *
Setter for the field benefitDesc.

	 *
	 * @param benefitDesc a {@link java.util.List} object.
	 */
	public void setBenefitDesc(List<String> benefitDesc) {
		this.benefitDesc = benefitDesc;
	}

	/**
	 *
Getter for the field endDate.

	 *
	 * @return a {@link java.util.Date} object.
	 */
	public Date getEndDate() {
		return this.endDate;
	}
	/**
	 *
Setter for the field endDate.

	 *
	 * @param endDate a {@link java.util.Date} object.
	 */
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	/**
	 *
Getter for the field startDate.

	 *
	 * @return a {@link java.util.Date} object.
	 */
	public Date getStartDate() {
		return this.startDate;
	}
	/**
	 *
Setter for the field startDate.

	 *
	 * @param startDate a {@link java.util.Date} object.
	 */
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	/**
	 *
Getter for the field title.

	 *
	 * @return a {@link java.lang.String} object.
	 */
	public String getTitle() {
		return this.title;
	}
	/**
	 *
Setter for the field title.

	 *
	 * @param title a {@link java.lang.String} object.
	 */
	public void setTitle(String title) {
		this.title = title;
	}

}


text:
module EmailExtension
  class Account
    include Mongoid::Document
    include Mongoid::Timestamps

    field :to_address, type: String
    field :from_address, type: String
    field :subject, type: String
    field :outgoing_message_format, type: String
    field :sendgrid_username, type: String
    field :sendgrid_password, type: String

    attr_accessible :to_address, :from_address, :subject, :outgoing_message_format, :sendgrid_username, :sendgrid_password

  end
end


text:
package com.example.tests;

import static org.junit.Assert.assertThat;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;

import com.example.utils.SortedListOf;

/**
 * Testing the display of Address Book page
 *
 * @version 0.2
 */
public class AddressBookTests extends TestBase{

	@Test
	public void displayAddressBook() {

		//get the list of contacts with data from database
		SortedListOf<ContactData> mainList = app.getHibernateHelper().listContacts();

		//get the list of contacts from AddressBook
		SortedListOf<ContactData> addressBookList = app.getContactHelper().getAddressBookContacts();

		//compare contacts
		assertThat(mainList, equalTo(addressBookList));
	}
}


text:
#pragma once

#include "../modelbase_api.h"

#include "PersistentStore.h"

namespace Model {

class Node;

class MODELBASE_API NodeIdMap {
	public:
		NodeIdType id(const Node* node);
		NodeIdType idIfExists(Node* node);
		void setId(const Node* node, NodeIdType id);

		static NodeIdType generateNewId();
		const Node* node(NodeIdType id);

		void remove(const Node* node);

		int size() const;

	private:
		QHash<const Node*, NodeIdType> nodeToId;
		QHash<NodeIdType, const Node*> idToNode;
};

inline NodeIdType NodeIdMap::generateNewId() { return QUuid::createUuid(); }
inline const Node* NodeIdMap::node(NodeIdType id) { return idToNode.value(id);}
inline NodeIdType NodeIdMap::idIfExists(Node* node) { return nodeToId.value(node); }
inline int NodeIdMap::size() const { return nodeToId.size(); }

}


text:
define("clipart/Folder",["dojo/_base/declare","clipart/_clipart"],function(_1,_2){
return _1("clipart.Folder",[_2],{});
});


text:
package io.warp10.script.ext.debug;

import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;

public class LOGMSG extends NamedWarpScriptFunction implements WarpScriptStackFunction {

  public LOGMSG(String name) {
    super(name);
  }

  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {
    Object top = stack.pop();

    System.out.println("[" + System.currentTimeMillis() + "] " + ((null == top) ? "null" : top.toString()));

    return stack;
  }
}


text:
package org.apache.nifi.controller.repository.claim;

/**
 *

 * A ContentClaim is a reference to a given flow file's content. Multiple flow files may reference the same content by both having the same content claim.

 *
 *

 * Must be thread safe

 *
 */
public final class StandardContentClaim implements ContentClaim, Comparable<ContentClaim> {

    private final ResourceClaim resourceClaim;
    private final long offset;
    private volatile long length;

    public StandardContentClaim(final ResourceClaim resourceClaim, final long offset) {
        this.resourceClaim = resourceClaim;
        this.offset = offset;
        this.length = -1L;
    }

    public void setLength(final long length) {
        this.length = length;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result;
        result = prime * result + (int) (offset ^ offset >>> 32);
        result = prime * result + (resourceClaim == null ? 0 : resourceClaim.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (!(obj instanceof ContentClaim)) {
            return false;
        }

        final ContentClaim other = (ContentClaim) obj;
        if (offset != other.getOffset()) {
            return false;
        }

        return resourceClaim.equals(other.getResourceClaim());
    }

    @Override
    public int compareTo(final ContentClaim o) {
        final int resourceComp = resourceClaim.compareTo(o.getResourceClaim());
        if (resourceComp != 0) {
            return resourceComp;
        }

        return Long.compare(offset, o.getOffset());
    }

    @Override
    public ResourceClaim getResourceClaim() {
        return resourceClaim;
    }

    @Override
    public long getOffset() {
        return offset;
    }

    @Override
    public long getLength() {
        return length;
    }

    @Override
    public String toString() {
        return "StandardContentClaim [resourceClaim=" + resourceClaim + ", offset=" + offset + ", length=" + length + "]";
    }
}


text:
define([
/*====='dojo/_base/declare',=====*/
	"dojo/_base/kernel",
	"../../support/DropDownPager"
], function(/*=====declare, =====*/kernel, widget){
	kernel.deprecated('DropDownPager is moved from gridx/modules/barPlugins/ to gridx/support/.', 'Please use the new path.', '1.3');

/*=====
	return declare([], {
		// summary:
		//		Moved to gridx/support/DropDownPager. This path is deprecated.
	});
=====*/

	return widget;
});


text:
from flask import Flask, render_template
from steamapi import core, user

app = Flask("Steamer")
core.APIConnection(api_key="YOURKEYHERE")

@app.route('/user/<name>')
def hello(name=None):
  try:
    try:
      steam_user = user.SteamUser(userid=int(name))
    except ValueError: # Not an ID, but a vanity URL.
      steam_user = user.SteamUser(userurl=name)
    name = steam_user.name
    content = "Your real name is {0}. You have {1} friends and {2} games.".format(steam_user.real_name,
                                                                                len(steam_user.friends),
                                                                                len(steam_user.games))
    img = steam_user.avatar
    return render_template('hello.html', name=name, content=content, img=img)
  except Exception as ex:
    # We might not have permission to the user's friends list or games, so just carry on with a blank message.
    return render_template('hello.html', name=name)

if __name__ == '__main__':
  app.run()


text:
package org.mones.chartjsgenj;

import java.lang.reflect.Field;

/**
 * Options for bar charts.
 *
 * @author mones
 * @see  Chart.js bar chart options
 */
public final class OptionsBar extends Options {
	// Boolean - Whether the scale should start at zero; or an order of
	// magnitude down from the lowest value
	public boolean scaleBeginAtZero = true;
	// Boolean - Whether grid lines are shown across the chart
	public boolean scaleShowGridLines = true;
	// String - Colour of the grid lines
	public Colour scaleGridLineColor = new Colour(0, 0.05f);
	// Number - Width of the grid lines
	public int scaleGridLineWidth = 1;
	// Boolean - Whether to show horizontal lines (except X axis)
	public boolean scaleShowHorizontalLines = true;
	// Boolean - Whether to show vertical lines (except Y axis)
	public boolean scaleShowVerticalLines = true;
	// Boolean - If there is a stroke on each bar
	public boolean barShowStroke = true;
	// Number - Pixel width of the bar stroke
	public int barStrokeWidth = 2;
	// Number - Spacing between each of the X value sets
	public int barValueSpacing = 5;
	// Number - Spacing between data sets within X values
	public int barDatasetSpacing = 1;
	// String - A legend template
	public String legendTemplate = "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%>
<span style=\"background-color:<%=datasets[i].fillColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
<%}%>
";

    public static OptionsBar DEFAULT = new OptionsBar();

	@Override
	public void addJSON(StringBuilder sb) {
		boolean initialized = false;
		sb.append(JSON.OBJ_BEGIN);
		initialized = super.addFieldListJSON(sb, initialized);
		initialized = addFieldListJSON(sb, initialized);
		if (initialized) {
			sb.setLength(sb.length() - JSON.SEP.length());
		}
		sb.append(JSON.OBJ_END);
	}

	protected boolean addFieldListJSON(StringBuilder sb, boolean initialized) {
		for (Field f: OptionsBar.class.getDeclaredFields()) {
			String name = f.getName();
			try {
				final Object object = f.get(this);
				if (!f.get(OptionsBar.DEFAULT).equals(object)) {
					if (!initialized) {
						initialized = true;
					}
					sb.append(name).append(JSON.FV_SEP);
					if (object instanceof JSONable) {
						((JSONable) object).addJSON(sb);
					} else {
						sb.append(object.toString());
					}
					sb.append(JSON.SEP);
				}
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
			}
		}
		return initialized;
	}
}


text:
My blog is based on the following technologies:
- [Jekyll](https://github.com/jekyll/jekyll) (3.7.3)
- [Minimal Mistakes Jekyll Theme](https://github.com/mmistakes/minimal-mistakes/) (4.11.1)
- [bigfoot.js](https://github.com/lemonmade/bigfoot), [Mapbox integration](https://github.com/mapbox), ...


text:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using XnaFlash.Swf.Paths;
using XnaFlash.Swf.Structures;
using XnaVG;

namespace XnaFlash.Swf.Tags
{
    [SwfTag(37)]
    public class DefineEditTextTag : ISwfDefinitionTag
    {
        public virtual bool HasAlpha { get { return false; } }
        public Content.CharacterType Type { get { return Content.CharacterType.EditText; } }
        public ushort CharacterID { get; protected set; }
        public Rectangle Bounds { get; protected set; }
        public EditTextFlags Flags { get; protected set; }
        public ushort FontID { get; protected set; }
        public string FontClass { get; protected set; }
        public ushort FontHeight { get; protected set; }
        public VGColor TextColor { get; protected set; }
        public ushort MaxLength { get; protected set; }
        public Align TextAlign { get; protected set; }
        public ushort LeftMargin { get; protected set; }
        public ushort RightMargin { get; protected set; }
        public ushort Indent { get; protected set; }
        public short Leading { get; protected set; }
        public string Variable { get; protected set; }
        public string InitialText { get; protected set; }

        #region ISwfTag Members

        public virtual void Load(SwfStream stream, uint length, byte version)
        {
            CharacterID = stream.ReadUShort();
            Bounds = stream.ReadRectangle();
            Flags = (EditTextFlags)stream.ReadUShort();
            if ((Flags & EditTextFlags.HasFont) != 0) FontID = stream.ReadUShort();
            if ((Flags & EditTextFlags.HasFontClass) != 0) FontClass = stream.ReadString();
            if ((Flags & EditTextFlags.HasFont) != 0) FontHeight = stream.ReadUShort();
            TextColor = ((Flags & EditTextFlags.HasTextColor) != 0) ? stream.ReadRGBA() : (VGColor)Color.Black;
            MaxLength = ((Flags & EditTextFlags.HasMaxLength) != 0) ? stream.ReadUShort() : ushort.MaxValue;
            if ((Flags & EditTextFlags.HasLayout) != 0)
            {
                TextAlign = (Align)stream.ReadByte();
                LeftMargin = stream.ReadUShort();
                RightMargin = stream.ReadUShort();
                Indent = stream.ReadUShort();
                Leading = stream.ReadShort();
            }
            Variable = stream.ReadString();
            InitialText = ((Flags & EditTextFlags.HasText) != 0) ? stream.ReadString() : string.Empty;
        }

        #endregion

        public enum Align : byte
        {
            Left = 0,
            Right = 1,
            Center = 2,
            Justify = 3
        }

        [Flags()]
        public enum EditTextFlags : ushort
        {
            HasText = 0x0080,
            WordWrap = 0x0040,
            Multiline = 0x0020,
            Password = 0x0010,
            ReadOnly = 0x0008,
            HasTextColor = 0x0004,
            HasMaxLength = 0x0002,
            HasFont = 0x0001,
            HasFontClass = 0x8000,
            AutoSize = 0x4000,
            HasLayout = 0x2000,
            NoSelect = 0x1000,
            Border = 0x0800,
            WasStatic = 0x0400,
            HTML = 0x0200,
            UseOutlines = 0x0100
        }
    }
}


text:
class Course::UserNotificationsController < Course::Controller
  load_and_authorize_resource :user_notification, class: UserNotification.name, only: :mark_as_read

  def fetch
    render json: next_popup_notification, status: :ok
  end

  def mark_as_read
    @user_notification.mark_as_read! for: current_user
    render json: next_popup_notification, status: :ok
  end

  private

  # Fetches the first unread popup `UserNotification` for the current course and returns JSON data
  # for the frontend to display it.
  #
  # @return [String] JSON data for the next notification, if there is one.
  # @return [nil] if there are no unread notifications, or no +current_course_user+.
  def next_popup_notification
    return unless current_course_user

    notification = UserNotification.next_unread_popup_for(current_course_user)
    notification && render_to_string("#{helpers.notification_view_path(notification)}.json",
                                     locals: { notification: notification })
  end
end


text:
angular.module('media42')
    .controller('ReplaceUploaderController', ['$scope', 'FileUploader', '$attrs', '$window', function ($scope, FileUploader, $attrs, $window) {
        $scope.errorFiles = [];

        $scope.uploader = new FileUploader({
            url: $attrs.uploadUrl,
            autoUpload: true,
            queueLimit: 1,
            removeAfterUpload: true,
            filters: [{
                name: 'filesize',
                fn: function(item) {
                    if (item.size > $attrs.maxFileSize) {
                        $scope.errorFiles.push(item);

                        return false;
                    }

                    return true;
                }
            }]
        });

        $scope.uploader.onSuccessItem = function() {
            $window.location.reload();
        };
    }]);


text:
package com.jcabi.http.request;

import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.http.ImmutableHeader;
import com.jcabi.http.Request;
import com.jcabi.http.RequestBody;
import com.jcabi.http.RequestURI;
import com.jcabi.http.Response;
import com.jcabi.http.Wire;
import com.jcabi.immutable.Array;
import com.jcabi.log.Logger;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonStructure;
import javax.ws.rs.core.UriBuilder;
import lombok.EqualsAndHashCode;

/**
 * Base implementation of {@link Request}.
 *
 * @author Yegor Bugayenko (yegor@tpc2.com)
 * @version $Id$
 * @since 0.8
 * @checkstyle ClassDataAbstractionCoupling (500 lines)
 * @see Request
 * @see Response
 * @todo #87:30min Refactor this class to get rid of PMD.GodClass.
 *  This can be done if MultiPartFormBody and
 *  FormEncodedBody are pulled out. Also, the two
 *  share the same implementations for all methods besides formParam,
 *  so they can be refactored to extend an AbstractRequestBody.
 *  PMD.TooManyMethods might come together with getting rid of the
 *  first one, since maybe qulice is counting the methods in the inner
 *  classes too - if it doesn't, then it can be left.
 */
@Immutable
@EqualsAndHashCode(of = { "home", "mtd", "hdrs", "content" })
@Loggable(Loggable.DEBUG)
@SuppressWarnings({"PMD.TooManyMethods", "PMD.GodClass"})
final class BaseRequest implements Request {

    /**
     * The encoding to use.
     */
    private static final String ENCODING = "UTF-8";

    /**
     * The Charset to use.
     * @checkstyle ConstantUsageCheck (3 lines)
     */
    private static final Charset CHARSET =
        Charset.forName(BaseRequest.ENCODING);

    /**
     * An empty immutable {@code byte} array.
     */
    private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    /**
     * Wire to use.
     */
    private final transient Wire wire;

    /**
     * Request URI.
     */
    private final transient String home;

    /**
     * Method to use.
     */
    private final transient String mtd;

    /**
     * Socket timeout to use.
     */
    private final transient int connect;

    /**
     * Read timeout to use.
     */
    private final transient int read;

    /**
     * Headers.
     */
    private final transient Array<Map.Entry<String, String>> hdrs;

    /**
     * Body to use.
     */
    @Immutable.Array
    private final transient byte[] content;

    /**
     * Public ctor.
     * @param wre Wire
     * @param uri The resource to work with
     */
    BaseRequest(final Wire wre, final String uri) {
        this(
            wre, uri,
            new Array<Map.Entry<String, String>>(),
            Request.GET, BaseRequest.EMPTY_BYTE_ARRAY
        );
    }

    /**
     * Public ctor.
     * @param wre Wire
     * @param uri The resource to work with
     * @param headers Headers
     * @param method HTTP method
     * @param body HTTP request body
     * @checkstyle ParameterNumber (5 lines)
     */
    BaseRequest(final Wire wre, final String uri,
        final Iterable<Map.Entry<String, String>> headers,
        final String method, final byte[] body) {
        this(wre, uri, headers, method, body, 0, 0);
    }

    /**
     * Public ctor.
     * @param wre Wire
     * @param uri The resource to work with
     * @param headers Headers
     * @param method HTTP method
     * @param body HTTP request body
     * @param cnct Connect timeout for http connection
     * @param rdd Read timeout for http connection
     * @checkstyle ParameterNumber (5 lines)
     */
    BaseRequest(final Wire wre, final String uri,
        final Iterable<Map.Entry<String, String>> headers,
        final String method, final byte[] body,
        final int cnct, final int rdd) {
        this.wire = wre;
        URI addr = URI.create(uri);
        if (addr.getPath() != null && addr.getPath().isEmpty()) {
            addr = UriBuilder.fromUri(addr).path("/").build();
        }
        this.home = addr.toString();
        this.hdrs = new Array<Map.Entry<String, String>>(headers);
        this.mtd = method;
        this.content = body.clone();
        this.connect = cnct;
        this.read = rdd;
    }

    @Override
    public RequestURI uri() {
        return new BaseRequest.BaseURI(this, this.home);
    }

    @Override
    public Request header(final String name, final Object value) {
        return new BaseRequest(
            this.wire,
            this.home,
            this.hdrs.with(new ImmutableHeader(name, value.toString())),
            this.mtd,
            this.content
        );
    }

    @Override
    public Request reset(final String name) {
        final Collection<Map.Entry<String, String>> headers =
            new LinkedList<>();
        final String key = ImmutableHeader.normalize(name);
        for (final Map.Entry<String, String> header : this.hdrs) {
            if (!header.getKey().equals(key)) {
                headers.add(header);
            }
        }
        return new BaseRequest(
            this.wire,
            this.home,
            headers,
            this.mtd,
            this.content
        );
    }

    @Override
    public RequestBody body() {
        return new BaseRequest.FormEncodedBody(this, this.content);
    }

    @Override
    public RequestBody multipartBody() {
        return new BaseRequest.MultipartFormBody(this, this.content);
    }

    @Override
    public Request method(final String method) {
        return new BaseRequest(
            this.wire,
            this.home,
            this.hdrs,
            method,
            this.content
        );
    }

    @Override
    public Request timeout(final int cnct, final int rdd) {
        return new BaseRequest(
            this.wire,
            this.home,
            this.hdrs,
            this.mtd,
            this.content,
            cnct,
            rdd
        );
    }

    @Override
    public Response fetch() throws IOException {
        return this.fetchResponse(new ByteArrayInputStream(this.content));
    }

    @Override
    public Response fetch(final InputStream stream) throws IOException {
        if (this.content.length > 0) {
            throw new IllegalStateException(
                "Request Body is not empty, use fetch() instead"
            );
        }
        return this.fetchResponse(stream);
    }

    @Override
    public <T extends Wire> Request through(final Class<T> type,
        final Object... args) {
        Constructor<?> ctor = null;
        for (final Constructor<?> opt : type.getDeclaredConstructors()) {
            if (opt.getParameterTypes().length == args.length + 1) {
                ctor = opt;
                break;
            }
        }
        if (ctor == null) {
            throw new IllegalArgumentException(
                String.format(
                    "class %s doesn't have a ctor with %d argument(s)",
                    type.getName(), args.length
                )
            );
        }
        final Object[] params = new Object[args.length + 1];
        params[0] = this.wire;
        System.arraycopy(args, 0, params, 1, args.length);
        final Wire decorated;
        try {
            decorated = Wire.class.cast(ctor.newInstance(params));
        } catch (final InstantiationException
            | IllegalAccessException | InvocationTargetException ex) {
            throw new IllegalStateException(ex);
        }
        return new BaseRequest(
            decorated,
            this.home,
            this.hdrs,
            this.mtd,
            this.content,
            this.connect,
            this.read
        );
    }

    @Override
    @SuppressWarnings("PMD.ConsecutiveLiteralAppends")
    public String toString() {
        final URI uri = URI.create(this.home);
        final StringBuilder text = new StringBuilder("HTTP/1.1 ")
            .append(this.mtd).append(' ')
            .append(uri.getPath())
            .append(" (")
            .append(uri.getHost())
            .append(")\n");
        for (final Map.Entry<String, String> header : this.hdrs) {
            text.append(
                Logger.format(
                    "%s: %s\n",
                    header.getKey(),
                    header.getValue()
                )
            );
        }
        return text.append('\n')
            .append(new RequestBody.Printable(this.content).toString())
            .toString();
    }

    /**
     * Fetch response from server.
     * @param stream The content to send.
     * @return The obtained response
     * @throws IOException If an IO exception occurs.
     */
    private Response fetchResponse(final InputStream stream)
        throws IOException {
        final long start = System.currentTimeMillis();
        final Response response = this.wire.send(
            this, this.home, this.mtd,
            this.hdrs, stream, this.connect,
            this.read
        );
        final URI uri = URI.create(this.home);
        Logger.info(
            this,
            "#fetch(%s %s%s %s): [%d %s] in %[ms]s",
            this.mtd,
            uri.getHost(),
            // @checkstyle AvoidInlineConditionalsCheck (1 line)
            uri.getPort() > 0 ? String.format(":%d", uri.getPort()) : "",
            uri.getPath(),
            response.status(),
            response.reason(),
            System.currentTimeMillis() - start
        );
        return response;
    }

    /**
     * Base URI.
     */
    @Immutable
    @EqualsAndHashCode(of = "address")
    @Loggable(Loggable.DEBUG)
    private static final class BaseURI implements RequestURI {
        /**
         * URI encapsulated.
         */
        private final transient String address;
        /**
         * Base request encapsulated.
         */
        private final transient BaseRequest owner;
        /**
         * Public ctor.
         * @param req Request
         * @param uri The URI to start with
         */
        BaseURI(final BaseRequest req, final String uri) {
            this.owner = req;
            this.address = uri;
        }
        @Override
        public String toString() {
            return this.address;
        }
        @Override
        public Request back() {
            return new BaseRequest(
                this.owner.wire,
                this.address,
                this.owner.hdrs,
                this.owner.mtd,
                this.owner.content
            );
        }
        @Override
        public URI get() {
            return URI.create(this.owner.home);
        }
        @Override
        public RequestURI set(final URI uri) {
            return new BaseRequest.BaseURI(this.owner, uri.toString());
        }
        @Override
        public RequestURI queryParam(final String name, final Object value) {
            return new BaseRequest.BaseURI(
                this.owner,
                UriBuilder.fromUri(this.address)
                    .queryParam(name, "{value}")
                    .build(value).toString()
            );
        }
        @Override
        public RequestURI queryParams(final Map<String, String> map) {
            final UriBuilder uri = UriBuilder.fromUri(this.address);
            final Object[] values = new Object[map.size()];
            int idx = 0;
            for (final Map.Entry<String, String> pair : map.entrySet()) {
                uri.queryParam(pair.getKey(), String.format("{x%d}", idx));
                values[idx] = pair.getValue();
                ++idx;
            }
            return new BaseRequest.BaseURI(
                this.owner,
                uri.build(values).toString()
            );
        }
        @Override
        public RequestURI path(final String segment) {
            return new BaseRequest.BaseURI(
                this.owner,
                UriBuilder.fromUri(this.address)
                    .path(segment)
                    .build().toString()
            );
        }
        @Override
        public RequestURI userInfo(final String info) {
            return new BaseRequest.BaseURI(
                this.owner,
                UriBuilder.fromUri(this.address)
                    .userInfo(info)
                    .build().toString()
            );
        }
        @Override
        public RequestURI port(final int num) {
            return new BaseRequest.BaseURI(
                this.owner,
                UriBuilder.fromUri(this.address)
                    .port(num).build().toString()
            );
        }
    }

    /**
     * Body of a request with a form that has attachments.
     * @todo #87:1h Implement and unit test method formParam(String, Object)
     *  Details here
     *  (second answer).
 e.g. While FormEncodedBody.formParam adds
     *  the param to a body with enctype application/x-www-form-urlencoded,
     *  method MultipartFormBody.formParam should add it to a body with
     *  enctype multipart/form-data.
     */
    private static final class MultipartFormBody implements RequestBody {

        /**
         * Content encapsulated.
         */
        @Immutable.Array
        private final transient byte[] text;

        /**
         * Base request encapsulated.
         */
        private final transient BaseRequest owner;

        /**
         * Public ctor.
         * @param req Request
         * @param body Text to encapsulate
         */
        MultipartFormBody(final BaseRequest req, final byte[] body) {
            this.owner = req;
            this.text = body.clone();
        }

        @Override
        public String toString() {
            return new RequestBody.Printable(this.text).toString();
        }

        @Override
        public Request back() {
            return new BaseRequest(
                this.owner.wire,
                this.owner.home,
                this.owner.hdrs,
                this.owner.mtd,
                this.text
            );
        }

        @Override
        public String get() {
            return new String(this.text, BaseRequest.CHARSET);
        }

        @Override
        public RequestBody set(final String txt) {
            return this.set(txt.getBytes(BaseRequest.CHARSET));
        }

        @Override
        public RequestBody set(final JsonStructure json) {
            final StringWriter writer = new StringWriter();
            Json.createWriter(writer).write(json);
            return this.set(writer.toString());
        }

        @Override
        public RequestBody set(final byte[] txt) {
            return new BaseRequest.FormEncodedBody(this.owner, txt);
        }

        @Override
        public RequestBody formParam(final String name, final Object value) {
            throw new UnsupportedOperationException("Method not available");
        }

        @Override
        public RequestBody formParams(final Map<String, String> params) {
            RequestBody body = this;
            for (final Map.Entry<String, String> param : params.entrySet()) {
                body = body.formParam(param.getKey(), param.getValue());
            }
            return body;
        }
    }

    /**
     * Body of a request with a simple form.
     * (enctype application/x-www-form-urlencoded)
     */
    @Immutable
    @EqualsAndHashCode(of = "text")
    @Loggable(Loggable.DEBUG)
    private static final class FormEncodedBody implements RequestBody {

        /**
         * Content encapsulated.
         */
        @Immutable.Array
        private final transient byte[] text;

        /**
         * Base request encapsulated.
         */
        private final transient BaseRequest owner;

        /**
         * URL form character to prepend.
         */
        private final transient String prepend;

        /**
         * Public ctor.
         * @param req Request
         * @param body Text to encapsulate
         */
        FormEncodedBody(final BaseRequest req, final byte[] body) {
            this(req, body, "");
        }

        /**
         * Public ctor.
         * @param req Request
         * @param body Text to encapsulate
         * @param pre Character to prepend
         */
        FormEncodedBody(
            final BaseRequest req, final byte[] body, final String pre
        ) {
            this.owner = req;
            this.text = body.clone();
            this.prepend = pre;
        }

        @Override
        public String toString() {
            return new RequestBody.Printable(this.text).toString();
        }

        @Override
        public Request back() {
            return new BaseRequest(
                this.owner.wire,
                this.owner.home,
                this.owner.hdrs,
                this.owner.mtd,
                this.text
            );
        }

        @Override
        public String get() {
            return new String(this.text, BaseRequest.CHARSET);
        }

        @Override
        public RequestBody set(final String txt) {
            return this.set(txt.getBytes(BaseRequest.CHARSET));
        }

        @Override
        public RequestBody set(final JsonStructure json) {
            final StringWriter writer = new StringWriter();
            Json.createWriter(writer).write(json);
            return this.set(writer.toString());
        }

        @Override
        public RequestBody set(final byte[] txt) {
            return new BaseRequest.FormEncodedBody(this.owner, txt);
        }

        @Override
        public RequestBody formParam(final String name, final Object value) {
            try {
                return new BaseRequest.FormEncodedBody(
                    this.owner,
                    new StringBuilder(this.get())
                        .append(this.prepend)
                        .append(name)
                        .append('=')
                        .append(
                            URLEncoder.encode(
                                value.toString(),
                                BaseRequest.ENCODING
                            )
                        )
                        .toString()
                        .getBytes(BaseRequest.CHARSET),
                    "&"
                );
            } catch (final UnsupportedEncodingException ex) {
                throw new IllegalStateException(ex);
            }
        }

        @Override
        public RequestBody formParams(final Map<String, String> params) {
            RequestBody body = this;
            for (final Map.Entry<String, String> param : params.entrySet()) {
                body = body.formParam(param.getKey(), param.getValue());
            }
            return body;
        }

    }

}


text:
using UnityEngine;
using System.Collections;

/// <summary>
/// This component makes it easy to switch scenes or open webpages on click.
/// Requires a InputToEvent component on the camera to forward clicks on screen.
/// </summary>
public class OnClickLoadSomething : MonoBehaviour
{
    public enum  ResourceTypeOption : byte
    {
        Scene,
        Web
    }

    public ResourceTypeOption ResourceTypeToLoad = ResourceTypeOption.Scene;
    public string ResourceToLoad;

    public void OnClick()
    {
        switch (ResourceTypeToLoad)
        {
            case ResourceTypeOption.Scene:
                Application.LoadLevel(ResourceToLoad);
                break;
            case ResourceTypeOption.Web:
                Application.OpenURL(ResourceToLoad);
                break;
        }
    }
}


text:
<!doctype html>

	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

	<link rel="apple-touch-icon" href="apple-touch-icon.png">

	<title>BorderlessFic</title>

	<link media="all" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans:100,200,300,400,500,600,700,800,900" rel="stylesheet">
	<link media="all" type="text/css" href="/app/css/font-awesome.min.css" rel="stylesheet">
	<link media="all" type="text/css" href="/app/css/core.css" rel="stylesheet">
	<link media="all" type="text/css" href="/app/css/skins/blue.css" rel="stylesheet">
	<link media="all" type="text/css" href="/app/css/custom.css" rel="stylesheet">

						BorderlessFic

Home

About

Portfolio

Blog

Contact

Translate

Showcase your work with style

Dashboard

Post

Translate

Profile

{{origPost.title}}

						<form class="form-horizontal"  ng-submit="postTranslation()">
				            <fieldset>

				                    Title

				                        <input id="txtTitle" ng-model="article.title" name="txtTitle" type="text" placeholder="placeholder" class="form-control input-md">

				                	 Language:

								    <select name="singleSelect" ng-model="selectedlanguage">
								      	<option ng-repeat="language in languages" value="{{language.$id}}">{{language.$id}}</option>
								    </select>

				                    Translation

										<ng-ckeditor bind="htmlEditor" skin="moono" remove-buttons="Image" remove-plugins="iframe,flash,smiley" msn-count="Number of typed characters:"></ng-ckeditor>

				                        <input id="singlebutton" name="singlebutton" class="btn btn-primary" type="submit" value="Publish" />

				            </fieldset>
				        </form>

Join our Mailing List

Lorem ipsum dolor sit amet, orci a faucibus, ante curabitur augue

						<form class="widget-form" action="#" method="get">

								Join our mailing list for news and exclusive offers:
								<input type="email" class="email-field" placeholder="Enter your email address" value="" name="email" title="Enter your email address" />

							<button></button>
						</form>

Connect with us

Lorem ipsum dolor sit amet, orci a faucibus, ante curabitur augue ornare nulla facilisi

© Borderless 2016

Created by Chu and Yue.


text:
Algorithms
==========

This is an attempt to build a cohesive module of algorithms in Python.

The purpose of this repo is to be a learning tool for myself and others.

I used psuedo code from various sources and I have listed them as references in the source code of each algorithm.

Algorithms implemented so far:
------------------------------

**Data Structures:**

**Sorting:**

- Insertion Sort
- Merge Sort

**Searching:**

**Shuffling:**

**Math:**

Installation:
-------------

If you want to use the algorithms directly, simply

::

    $ pip install algorithms

If you want to examine the algorithms source, then you should clone this repo.

Usage:
------

Once installed you can simply do the following in your program:

::

    # create code sample

All prequisites for the algorithms are listed in the source code for each algorithm.

Tests:
------

Nose is used as the main test runner and all Unit Tests can be run by:

::

    $ python algo/run_tests.py


text:
Bei jeglichen Fehlern, die sich auf den GeoServer zurückführen lassen (wie z.B.
keine oder falsche Antwort eines Kartendienstes) ist das Protokoll die erste
Anlaufstelle. Das GeoServer Protokoll lässt sich dabei entweder direkt über
die GUI oder aus dem Dateisystem (/usr/local/lib/geoserver-{{ book.geoServerVersion }}/data_dir/logs/geoserver.log) aufrufen.
Bei schwerwiegenden Problemen bzw. Fehlern steht der Logging-Message das Kürzel `ERROR` vor,
rein informativen Protokollmeldungen das Kürzel `INFO`.

Für die Protokollierung des GeoServers lassen sich verschiedene Profile einstellen.
Diese unterscheiden sich in der Sensitivität, in der die Prozesse des GeoServers
protokolliert werden. Das zu verwendende Protokoll kann über die GeoServer-Weboberfläche
im Bereich Einstellungen -\> Global konfiguriert werden. Der Wechsel eines Profils
wirkt sich sofort aus, d.h. der GeoServer muss *nicht* neu gestartet werden!

![Protokollierung in der GeoServer-Weboberfläche](../assets/geoserver_logging.png)

Ist die Checkbox bei *Ausführliche Fehlerausgaben* gesetzt, wird der volle
Java-Stacktrace in die Log-Datei geschrieben. Da hierdurch größere Log-Dateien
verursacht werden, ist diese Einstellung nur für das Debuggen zu empfehlen.

Hier eine kurze Erläuterung einiger Protokoll-Profile:

| Profil | Beschreibung |
| --------- | ----------- |
| `DEFAULT_LOGGING` | Mittleres Protokolllevel auf fast allen Modulebenen des GeoServers.|
| `GEOSERVER_DEVELOPER_LOGGING` | Ausführliche Protokollierung auf Ebene des Moduls GeoServer. Nur sinnvoll, wenn der GeoServer debuggt wird.|
| `GEOTOOLS_DEVELOPER_LOGGING` | Ausführliche Protokollierung auf Ebene des Moduls Geo-Tools. Diese Auswahl kann nützlich sein, wenn überprüft werden soll, welche SQL Statements (z.B. bei einer GetFeature-Abfrage) an die Datenbank gesendet werden.|
| `PRODUCTION_LOGGING` | Minimale Protokollierung, nur Fehler werden ausgegeben. Diese Einstellung ist für den *Produktiveinsatz* zu wählen.|
| `VERBOSE_LOGGING` | Ausführliche Protokollierung auf allen Ebenen des GeoServes. Nur sinnvoll, wenn der GeoServer debuggt wird.|

Wir wollen das Protokoll des GeoServers nun *live* über das Dateisystem beobachten.
Dazu führen müssen die folgenden Schritte ausgeführt werden.

1. Stellen Sie das VERBOSE\_LOGGING-Profil ein.
2. Der GeoServer auf der OSGeoLive ist so konfiguriert, dass nicht automatisch
   in die Protokolldatei, sondern in die Standardausgabe des Java-Prozesses
   geschrieben wird. Wir müssen also den **Haken bei**
   *in die Standardausgabe schreiben* **entfernen**, sodass das Protokoll in die
   Datei /usr/local/lib/geoserver-{{ book.geoServerVersion }}/data_dir/logs/geoserver.log geschrieben wird.
3. Speichern Sie die Einstellungen (unten).
4. Öffnen Sie die Konsole und führen Sie den folgenden Befehl aus:

less +F /usr/local/lib/geoserver-{{ book.geoServerVersion }}/data_dir/logs/geoserver.log

> **note**
>
> Normalerweise würde man statt less +F den Befehl tail -f verwenden. Dies
> funktioniert auf der OSGeoLive aber aus unbekannten Gründen nicht. Die
> *Live*-Beobachtung der Datei kann durch das Drücken der Tastenkombination
> STRG + C beendet werden.

1.  Öffnen Sie eine Layer-Vorschau und beobachten Sie wie sich das Protokoll verändert.

Die folgende Abbildung stellt diese Schritte dar:

![Protokolleinstellungen und Layer-Vorschau](../assets/log_settings_and_preview.png)

Sie können nun *live* beobachten wie sich der Inhalt der Logdatei verändert. Dabei
sehen Sie immer das Ende der Protokolldatei. Jede Interaktion in der Vorschau des
Layers (z.B. Zoomen oder Klicken) kann nun im Protokoll nachvollzogen werden. Sie
können das Protokollprofil auch ändern, um zu beobachten wie sich die Sensitivität
der Ausgabe verändert.

![Live-Beobachtung der Protokollierung](../assets/live_logging.png)

Das GeoServer-Logging-System basiert auf der Java-Logging-Bibliothek Log4J.
Somit gibt es zusätzlich die Möglichkeit eigene LOGGING-Profile zu definieren und diese im Geoserver-Datenverzeichnis im Unterordner `logs/` bereitzustellen.
Näheres hierzu finden Sie [hier](http://docs.geoserver.org/latest/en/user/configuration/logging.html).

Im folgenden [Abschnitt](gwc.md) geht es mit dem Thema *GeoWebCache (GWC)* weiter.


text:
"""
Various utilities.
"""

import bz2, gzip

def open_compressed( filename, mode='r' ):
    if filename.endswith( ".bz2" ):
        return bz2.BZ2File( filename, mode )
    elif filename.endswith( ".gz" ):
        return gzip.GzipFile( filename, mode )
    else:
        return file( filename, mode )


text:
package ru.job4j.tree;

import org.junit.Test;
import ru.job4j.map.User;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;

/**
 * Тестирование конкретных реализаций {@link Node}
 * через тестирование абстрактного узла {@link AbstractNode}.
 *
В данном тестовом классе производится тестирование
 * общих методов для всех реализаций. Специфические реализации
 * методов тестируются в тестовом классе для конкретной
 * реализции узла.

 */
public abstract class AbstractNodeTest {
	/**
	 * Получение конкретной реализации узла.
	 *
	 * @param value Значение, которое будет содержать узел.
	 * @param <V>   Параметризованный тип, представляющий тип значения узла.
	 * @return Конкретную реализацию узла.
	 */
	protected abstract <V extends Comparable<V>> AbstractNode<V> getNodeInstance(V value);

	/**
	 * Тест получения значения.
	 */
	@Test
	public void testGetValue() {
		AbstractNode<String> root = getNodeInstance("root");
		assertEquals(root.getValue(), "root");
		root.add(getNodeInstance("a"));
		assertEquals(root.children().get(0).getValue(), "a");
	}

	/**
	 * Тест получения дочерних узлов.
	 */
	@Test
	public void testChildren() {
		AbstractNode<Integer> root = getNodeInstance(69);
		AbstractNode<Integer> node01 = getNodeInstance(65);
		root.add(node01);
		AbstractNode<Integer> node02 = getNodeInstance(75);
		root.add(node02);
		assertEquals(root.children().toString(), "[65={}, 75={}]");
	}

	/**
	 * Тест расчёта хэш-кода узла.
	 */
	@Test
	public void testHashCode() {
		AbstractNode<String> node01 = getNodeInstance("node01");
		AbstractNode<String> node02 = getNodeInstance("node02");
		assertNotEquals(node01.hashCode(), node02.hashCode());
		assertEquals(node01.hashCode(), getNodeInstance("node01").hashCode());

		int hash1 = getNodeInstance("some_node").hashCode();
		int hash2 = getNodeInstance("some_node").hashCode();
		assertThat(hash1, is(equalTo(hash2)));
	}

	/**
	 * Тест сравнения двух узлов.
	 */
	@Test
	public void testEquals() {
		AbstractNode<Integer> node = getNodeInstance(69);
		assertThat(node, is(equalTo(node)));
		assertThat(node, not(equalTo(null)));
		assertThat(node, not(equalTo(new User())));
		assertThat(getNodeInstance("root"), is(equalTo(getNodeInstance("root"))));
		assertThat(getNodeInstance("root"), not(equalTo(getNodeInstance("node01"))));
	}

	/**
	 * Тест представления узла в виде строки.
	 */
	@Test
	public void testToString() {
		AbstractNode<Integer> root = getNodeInstance(69);
		assertEquals(root.toString(), "69={}");

		AbstractNode<Integer> node01 = getNodeInstance(65);
		root.add(node01);
		AbstractNode<Integer> node02 = getNodeInstance(75);
		root.add(node02);
		assertEquals(root.toString(), "69={65, 75}");
	}
}


text:
class CommentsController < ApplicationController
  before_action :set_comment, only: [:show, :edit, :update, :destroy]

  # GET /comments
  # GET /comments.json
  def index
      @comments = Comment.all

      json_array = []
      @comments.each do |comment|
          json_array << {id: comment.id,
                         article_id: comment.article_id,
                         content: comment.content}
      end

      output_hash = {comments: json_array.sort_by {|comment| comment[:content]}}
      render :json => output_hash.to_json
  end

  # GET /comments/1
  # GET /comments/1.json
  def show
      if set_comment
          output_hash = {id: @comment.id,
                         article_id: @comment.article_id,
                         content: @comment.content}

          render :json => output_hash.to_json
      end
  end

  # POST /comments
  # POST /comments.json
  def create
      information = request.raw_post
      data_parsed = JSON.parse(information)

      comment_info = {article_id: data_parsed["article_id"], content: data_parsed["content"]}

      for id in 1...Float::INFINITY
          if !Comment.exists?(id)
              comment_info[:id] = id
              break
          end
      end

      @comment = Comment.new(comment_info)
      @comment.save
      output_hash = {id: @comment.id,
                     article_id: @comment.article_id,
                     content: @comment.content}
      render :json => output_hash.to_json
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_comment
        if !Comment.exists?(params[:id])
            render :text => "No such comment"
            return false
        else
            @comment = Comment.find(params[:id])
            return true
        end
    end
end


text:
namespace RapidVulkan
{
  namespace Debug
  {
    inline const char* TryToString(const VkScopeNV& value)
    {
      switch(value)
      {
#if VK_HEADER_VERSION >= 101
      case VK_SCOPE_DEVICE_NV:
        return "VK_SCOPE_DEVICE_NV";
#endif
#if VK_HEADER_VERSION >= 101
      case VK_SCOPE_WORKGROUP_NV:
        return "VK_SCOPE_WORKGROUP_NV";
#endif
#if VK_HEADER_VERSION >= 101
      case VK_SCOPE_SUBGROUP_NV:
        return "VK_SCOPE_SUBGROUP_NV";
#endif
#if VK_HEADER_VERSION >= 101
      case VK_SCOPE_QUEUE_FAMILY_NV:
        return "VK_SCOPE_QUEUE_FAMILY_NV";
#endif
      default:
        return nullptr;
      }
    };

    inline const char* ToString(const VkScopeNV& value)
    {
      auto result = TryToString(value);
      return (result != nullptr ? result : "*Unknown*");
    };
  }
}

#endif
#endif


text:
import {Entity, Column, PrimaryGeneratedColumn, ManyToOne, ManyToMany} from "typeorm";
import {Category} from './Category'
import { User } from "./User";
import { Product } from "./Product";

@Entity()
export class Order {

    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        length: 50
    })
    ref: string;

    @Column("date")
    dateorder: Date;

    @ManyToOne(type => User, user => user.orders)
    user: User;

    @ManyToOne(type => Category, category => category.products)
    category: Category;

    @ManyToMany(type => Product, product => product.orders)
    products: Product[];
}


text:
@class XADArchiveParser, XADString;

NS_ASSUME_NONNULL_BEGIN

@interface DTPartialArchiveParser : NSObject

- (instancetype)initWithPath:(NSString *)archivePath searchString:(NSString *)search;
@property (readonly, copy, nullable) NSData *searchResult;

-(void)archiveParser:(XADArchiveParser *)parser foundEntryWithDictionary:(NSDictionary *)dict;
-(BOOL)archiveParsingShouldStop:(XADArchiveParser *)parser;

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace Magium\Actions\Mousemove;

use Magium\Actions\AbstractInteraction;
use Magium\Actions\ByCssTrait;
use Magium\Actions\ByTextTrait;

class ByCss extends AbstractInteraction
{

    const ACTION = 'Mousemove\ByCss';

    use ByCssTrait;

    public function execute($param)
    {
        $element = $this->getElement($this->webDriver, $param);
        $this->webDriver->getMouse()->mouseMove($element->getCoordinates());
    }

}


text:
using System;

namespace NVcdiff
{
	/// <summary>
	/// Table used to encode/decode instructions.
	/// </summary>
	internal sealed class CodeTable
	{
		/// <summary>
		/// Default code table specified in RFC 3284.
		/// </summary>
		static internal CodeTable Default = BuildDefaultCodeTable();

		/// <summary>
		/// Array of entries in the code table
		/// </summary>
		Instruction[,] entries = new Instruction[256,2];

		/// <summary>
		///
		/// </summary>
		internal Instruction this[int i, int j]
		{
			get
			{
				return entries[i, j];
			}
		}

		internal CodeTable(byte[] bytes)
		{
			for (int i=0; i < 256; i++)
			{
				entries[i,0] = new Instruction((InstructionType)bytes[i], bytes[i+512], bytes[i+1024]);
				entries[i,1] = new Instruction((InstructionType)bytes[i+256], bytes[i+768], bytes[i+1280]);
			}
		}

		internal CodeTable(Instruction[,] entries)
		{
			if (entries==null)
			{
				throw new ArgumentNullException("entries");
			}
			if (entries.Rank != 2)
			{
				throw new ArgumentException ("Array must be rectangular.", "entries");
			}
			if (entries.GetLength(0) != 256)
			{
				throw new ArgumentException ("Array must have outer length 256.", "entries");
			}
			if (entries.GetLength(1) != 2)
			{
				throw new ArgumentException ("Array must have inner length 256.", "entries");
			}
			Array.Copy (entries, 0, this.entries, 0, 512);
		}

		/// <summary>
		/// Builds the default code table specified in RFC 3284
		/// </summary>
		/// <returns>
		/// The default code table.
		/// </returns>
		static CodeTable BuildDefaultCodeTable()
		{
			// Defaults are NoOps with size and mode 0.
			Instruction[,] entries = new Instruction[256,2];
			entries[0, 0] = new Instruction(InstructionType.Run, 0, 0);
			for (byte i=0; i < 18; i++)
			{
				entries[i+1, 0] = new Instruction(InstructionType.Add, i, 0);
			}

			int index = 19;

			// Entries 19-162
			for (byte mode = 0; mode < 9; mode++)
			{
				entries[index++, 0] = new Instruction (InstructionType.Copy, 0, mode);
				for (byte size = 4; size < 19; size++)
				{
					entries[index++, 0] = new Instruction (InstructionType.Copy, size, mode);
				}
			}

			// Entries 163-234
			for (byte mode = 0; mode < 6; mode++)
			{
				for (byte addSize = 1; addSize < 5; addSize++)
				{
					for (byte copySize = 4; copySize < 7; copySize++)
					{
						entries[index, 0] = new Instruction (InstructionType.Add, addSize, 0);
						entries[index++, 1] = new Instruction (InstructionType.Copy, copySize, mode);
					}
				}
			}

			// Entries 235-246
			for (byte mode = 6; mode < 9; mode++)
			{
				for (byte addSize = 1; addSize < 5; addSize++)
				{
					entries[index, 0] = new Instruction (InstructionType.Add, addSize, 0);
					entries[index++, 1] = new Instruction (InstructionType.Copy, 4, mode);
				}
			}

			// Entries 247-255
			for (byte mode = 0; mode < 9; mode++)
			{
				entries[index, 0] = new Instruction (InstructionType.Copy, 4, mode);
				entries[index++, 1] = new Instruction (InstructionType.Add, 1, 0);
			}

			return new CodeTable(entries);
		}

		internal byte[] GetBytes()
		{
			byte[] ret = new byte[1536];
			for (int i=0; i < 256; i++)
			{
				ret[i]=(byte)entries[i,0].Type;
				ret[i+256]=(byte)entries[i,1].Type;
				ret[i+512]=entries[i,0].Size;
				ret[i+768]=entries[i,1].Size;
				ret[i+1024]=entries[i,0].Mode;
				ret[i+1280]=entries[i,1].Mode;
			}
			return ret;
		}
	}
}