text:
// Copyright 2015 The Project Buendia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
// specific language governing permissions and limitations under the License.

package org.projectbuendia.client.ui.lists;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.google.common.base.Optional;

import org.projectbuendia.client.R;
import org.projectbuendia.client.models.Location;
import org.projectbuendia.client.models.LocationTree;
import org.projectbuendia.client.ui.ProgressFragment;
import org.projectbuendia.client.widgets.SubtitledButtonView;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;

/** Displays a list of all locations. */
public final class LocationListFragment extends ProgressFragment {
    @InjectView(R.id.location_selection_locations) GridView mLocationGrid;
    @InjectView(R.id.location_selection_all_patients) SubtitledButtonView mAllPatientsButton;
    @InjectView(R.id.location_selection_triage) SubtitledButtonView mTriageButton;
    @InjectView(R.id.location_selection_discharged) SubtitledButtonView mDischargedButton;

    private LocationListController mController;
    private final Ui mUi = new Ui();
    private LocationListAdapter mAdapter;

    public LocationListFragment() {
        // Required empty public constructor
    }

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_location_selection);
    }

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, view);
        return view;
    }

    @Override public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        mController = ((LocationListActivity) getActivity()).getController();
        mController.attachFragmentUi(mUi);
    }

    @Override public void onDestroyView() {
        mController.detachFragmentUi(mUi);
        super.onDestroyView();
    }

    public void setPatientCount(SubtitledButtonView button, long count) {
        button.setSubtitle("" + count);
        button.setTextColor(0xff000000);
        button.setSubtitleColor(count == 0 ? 0x40000000 : 0xff000000);
    }

    @OnItemClick(R.id.location_selection_locations)
    void onLocationGridClicked(int position) {
        mController.onLocationSelected(mAdapter.getItem(position));
    }

    @OnClick(R.id.location_selection_all_patients)
    void onAllPatientsClicked(View v) {
        FilteredPatientListActivity.start(getActivity());
    }

    @OnClick(R.id.location_selection_discharged)
    void onDischargedClicked(View v) {
        mController.onDischargedPressed();
    }

    @OnClick(R.id.location_selection_triage) void onTriageClicked(View v) {
        mController.onTriagePressed();
    }

    private final class Ui implements LocationListController.LocationFragmentUi {
        @Override public void setDischargedPatientCount(long patientCount) {
            setPatientCount(mDischargedButton, patientCount);
        }

        @Override public void setTriagePatientCount(long patientCount) {
            setPatientCount(mTriageButton, patientCount);
        }

        @Override public void setPresentPatientCount(long patientCount) {
            setPatientCount(mAllPatientsButton, patientCount);
        }

        @Override public void setLocations(LocationTree locationTree, List<Location> locations) {
            mAdapter = new LocationListAdapter(
                getActivity(), locations, locationTree, Optional.<String> absent());
            mLocationGrid.setAdapter(mAdapter);
        }

        @Override public void setBusyLoading(boolean busy) {
            changeState(busy ? State.LOADING : State.LOADED);
        }

        @Override public void showIncrementalSyncProgress(int progress, @Nullable String label) {
            setProgress(progress);
            if (label != null) {
                setProgressLabel(label);
            }
        }

        @Override public void resetSyncProgress() {
            switchToCircularProgressBar();
        }

        @Override public void showSyncCancelRequested() {
            setProgressLabel(getString(R.string.cancelling_sync));
        }
    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Handles primary keys.
 *
 * Currently, a primary key can be an integer or a string.
 *
 * @package  Jelly
 */
abstract class Jelly_Field_Primary extends Jelly_Field
{
	/**
	 * @var  boolean  Defaults primary keys to primary
	 */
	public $primary = TRUE;

	/**
	 * Converts numeric IDs to ints
	 *
	 * @param   mixed  $value
	 * @return  int|string
	 */
	public function set($value)
	{
		if ($value)
		{
			if (is_numeric($value))
			{
				return (int)$value;
			}
			else
			{
				return (string)$value;
			}
		}
		else
		{
			// Empty values should be null so
			// they are auto-incremented properly
			return NULL;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001/*
002 * To change this license header, choose License Headers in Project Properties.
003 * To change this template file, choose Tools | Templates
004 * and open the template in the editor.
005 */
006
007package org.team751.utils;
008
009import org.team751.vision.VisionNetworkTableCommunication;
010
011/**
012 *
013 * @author sambaumgarten
014 */
015public class Diagnostic {
016    public static final String ANSI_RESET = "\u001B[0m";
017    public static final String ANSI_BLACK = "\u001B[30m";
018    public static final String ANSI_RED = "\u001B[31m";
019    public static final String ANSI_GREEN = "\u001B[32m";
020    public static final String ANSI_YELLOW = "\u001B[33m";
021    public static final String ANSI_BLUE = "\u001B[34m";
022    public static final String ANSI_PURPLE = "\u001B[35m";
023    public static final String ANSI_CYAN = "\u001B[36m";
024    public static final String ANSI_WHITE = "\u001B[37m";
025
026    public static void runAllDiagnosticTests() {
027        boolean visionPass = runVisionNetworkTablesDiagnostic();
028    }
029
030    public static boolean runVisionNetworkTablesDiagnostic() {
031        System.out.println(ANSI_BLUE + "STARTING VISION NET TABLES DIAGNOSTIC");
032        System.out.println(ANSI_BLUE + "VisionNetworkTableCommunication Initialized");
033        VisionNetworkTableCommunication vntc = new VisionNetworkTableCommunication();
034        System.out.println(ANSI_PURPLE + "CHECK if the nettables connection was established successfully");
035        if (!vntc.isConnectionAvailable()) {
036            System.out.println(ANSI_RED + "FAILED VISION NET TABLES DIAGNOSTIC");
037            return false;
038        } else {
039            System.out.println(ANSI_GREEN + "PASSED VISION NET TABLES DIAGNOSTIC");
040            return true;
041        }
042    }
043}


text:
#import <Foundation/Foundation.h>

typedef enum {
    UIGestureRecognizerStatePossible,
    UIGestureRecognizerStateBegan,
    UIGestureRecognizerStateChanged,
    UIGestureRecognizerStateEnded,
    UIGestureRecognizerStateCancelled,
    UIGestureRecognizerStateFailed,
    UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
} UIGestureRecognizerState;

@class UIView, UIGestureRecognizer, UITouch, UIEvent;

@protocol UIGestureRecognizerDelegate <NSObject>
@optional
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer;
@end

@interface UIGestureRecognizer : NSObject {
@private
    id _delegate;
    BOOL _delaysTouchesBegan;
    BOOL _delaysTouchesEnded;
    BOOL _cancelsTouchesInView;
    BOOL _enabled;
    UIGestureRecognizerState _state;
    __weak UIView *_view;

    struct {
        BOOL shouldBegin : 1;
        BOOL shouldReceiveTouch : 1;
        BOOL shouldRecognizeSimultaneouslyWithGestureRecognizer : 1;
    } _delegateHas;
}

- (id)initWithTarget:(id)target action:(SEL)action;

- (void)addTarget:(id)target action:(SEL)action;
- (void)removeTarget:(id)target action:(SEL)action;

- (void)requireGestureRecognizerToFail:(UIGestureRecognizer *)otherGestureRecognizer;
- (CGPoint)locationInView:(UIView *)view;

@property (nonatomic, assign) id<UIGestureRecognizerDelegate> delegate;
@property (nonatomic) BOOL delaysTouchesBegan;
@property (nonatomic) BOOL delaysTouchesEnded;
@property (nonatomic) BOOL cancelsTouchesInView;
@property (nonatomic, getter=isEnabled) BOOL enabled;
@property (nonatomic, readonly) UIGestureRecognizerState state;
@property (nonatomic, readonly) __weak UIView *view;

@end


text:
// @flow

// npx babel-node ./examples/storage
// or watch:
// npx babel-watch ./examples/storage

import Storage from '../src/models/storage';

/**
 * Flow works
 */

const App: Storage = new Storage({ lang: 'en' }, { key: 'app' });

const User: Storage = new Storage(
  {
    id: 1,
    name: 'Megan J. Cushman',
    gender: 1,
    visits: '2017-07-23',
  },
  {
    password: 'encryption-password',
    key: 'localstorage-key',
    sessionTime: 10
  }
);

// change data;
User.data = {
  id: 2,
  name: 'John Doe',
  gender: 1,
  visits: '',
}

// change session time in minutes
User.sessionTime = 20;

console.log(User.data);
console.log(App.data);


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>SQLite Changes From Version 3.4.2 To 3.5.0</title>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Small. Fast. Reliable.
Choose any three.

    About
    Sitemap
    Documentation
    Download
    License
    News
    Developers
    Support

<?xml version="1.0" encoding="Windows-1252"?>

 Moving From SQLite 3.4.2 to 3.5.0

  SQLite version 3.5.0 introduces a new OS interface layer that
  is incompatible with all prior versions of SQLite.  In addition,
  a few existing interfaces have been generalized to work across all
  database connections within a process rather than just all
  connections within a thread.  The purpose of this article
  is to describe the changes to 3.5.0 in detail so that users
  of prior versions of SQLite can judge what, if any, effort will
  be required to upgrade to newer versions.

1.0 Overview Of Changes

  A quick enumeration of the changes in SQLite version 3.5.0
  is provide here.  Subsequent sections will describe these
  changes in more detail.

The OS interface layer has been completely reworked:

The undocumented sqlite3_os_switch() interface has
      been removed.

The SQLITE_ENABLE_REDEF_IO compile-time flag no longer functions.
      I/O procedures are now always redefinable.

Three new objects are defined for specifying I/O procedures:
      sqlite3_vfs, sqlite3_file, and sqlite3_io_methods.

Three new interfaces are used to create alternative OS interfaces:
      sqlite3_vfs_register(), sqlite3_vfs_unregister(), and
      sqlite3_vfs_find().

A new interface has been added to provided additional control over
      the creation of new database connections: sqlite3_open_v2().
      The legacy interfaces of sqlite3_open() and
      sqlite3_open16() continue to be fully supported.

The optional shared cache and memory management features that
      were introduced in version 3.3.0 can now be used across multiple
      threads within the same process.  Formerly, these extensions only
      applied to database connections operating within a single thread.

The sqlite3_enable_shared_cache() interface now applies to all
       threads within a process, not to just the one thread in which it
       was run.

The sqlite3_soft_heap_limit() interface now applies to all threads
       within a process, not to just the one thread in which it was run.

The sqlite3_release_memory() interface will now attempt to reduce
       the memory usages across all database connections in all threads, not
       just connections in the thread where the interface is called.

The sqlite3_thread_cleanup() interface has become a no-op.

Restrictions on the use of the same database connection by multiple
      threads have been dropped.  It is now safe for
      multiple threads to use the same database connection at the same
      time.

There is now a compile-time option that allows an application to
      define alternative malloc()/free() implementations without having
      to modify any core SQLite code.

There is now a compile-time option that allows an application to
      define alternative mutex implementations without having
      to modify any core SQLite code.

  Of these changes, only 1a and 2a through 2c are incompatibilities
  in any formal sense.
  But users who have previously made custom modifications to the
  SQLite source (for example to add a custom OS layer for embedded
  hardware) might find that these changes have a larger impact.
  On the other hand, an important goal of these changes is to make
  it much easier to customize SQLite for use on different operating
  systems.

2.0 The OS Interface Layer

  If your system defines a custom OS interface for SQLite or if you
  were using the undocumented sqlite3_os_switch()
  interface, then you will need to make modifications in order to
  upgrade to SQLite version 3.5.0.  This may seem painful at first
  glance.  But as you look more closely, you will probably discover
  that your changes are made smaller and easier to understand and manage
  by the new SQLite interface.  It is likely that your changes will
  now also work seamlessly with the SQLite amalgamation.  You will
  no longer need to make any changes to the code SQLite source code.
  All of your changes can be effected by application code and you can
  link against a standard, unmodified version of the SQLite amalgamation.
  Furthermore, the OS interface layer, which was formerly undocumented,
  is now an officially support interface for SQLite.  So you have
  some assurance that this will be a one-time change and that your
  new backend will continue to work in future versions of SQLite.

2.1 The Virtual File System Object

  The new OS interface for SQLite is built around an object named
  sqlite3_vfs.  The "vfs" stands for "Virtual File System".
  The sqlite3_vfs object is basically a structure containing pointers
  to functions that implement the primitive disk I/O operations that
  SQLite needs to perform in order to read and write databases.
  In this article, we will often refer a sqlite3_vfs objects as a "VFS".

  SQLite is able to use multiple VFSes at the same time.  Each
  individual database connection is associated with just one VFS.
  But if you have multiple database connections, each connection
  can be associated with a different VFS.

  There is always a default VFS.
  The legacy interfaces sqlite3_open() and sqlite3_open16() always
  use the default VFS.
  The new interface for creating database connections,
  sqlite3_open_v2(), allows you to specify which VFS you want to
  use by name.

2.1.1 Registering New VFS Objects

  Standard builds of SQLite for Unix or Windows come with a single
  VFS named "unix" or "win32", as appropriate.  This one VFS is also
  the default.  So if you are using the legacy open functions, everything
  will continue to operate as it has before.  The change is that an application
  now has the flexibility of adding new VFS modules to implement a
  customized OS layer.  The sqlite3_vfs_register() API can be used
  to tell SQLite about one or more application-defined VFS modules:

int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);

  Applications can call sqlite3_vfs_register at any time, though of course
  a VFS needs to be registered before it can be used.  The first argument
  is a pointer to a customized VFS object that the application has prepared.
  The second argument is true to make the new VFS the default VFS so that
  it will be used by the legacy sqlite3_open() and sqlite3_open16() APIs.
  If the new VFS is not the default, then you will probably have to use
  the new sqlite3_open_v2() API to use it.  Note, however, that if
  a new VFS is the only VFS known to SQLite (if SQLite was compiled without
  its usual default VFS or if the pre-compiled default VFS was removed
  using sqlite3_vfs_unregister()) then the new VFS automatic becomes the
  default VFS regardless of the makeDflt argument to sqlite3_vfs_register().

  Standard builds include the default "unix" or "win32" VFSes.
  But if you use the -DOS_OTHER=1 compile-time option, then SQLite is
  built without a default VFS.  In that case, the application must
  register at least one VFS prior to calling sqlite3_open().
  This is the approach that embedded applications should use.
  Rather than modifying the SQLite source to to insert an alternative
  OS layer as was done in prior releases of SQLite, instead compile
  an unmodified SQLite source file (preferably the amalgamation)
  with the -DOS_OTHER=1 option, then invoke sqlite3_vfs_register()
  to define the interface to the underlying filesystem prior to
  creating any database connections.

2.1.2 Additional Control Over VFS Objects

  The sqlite3_vfs_unregister() API is used to remove an existing
  VFS from the system.

int sqlite3_vfs_unregister(sqlite3_vfs*);

  The sqlite3_vfs_find() API is used to locate a particular VFS
  by name.  Its prototype is as follows:

sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);

  The argument is the symbolic name for the desired VFS.  If the
  argument is a NULL pointer, then the default VFS is returned.
  The function returns a pointer to the sqlite3_vfs object that
  implements the VFS.  Or it returns a NULL pointer if no object
  could be found that matched the search criteria.

2.1.3 Modifications Of Existing VFSes

  Once a VFS has been registered, it should never be modified.  If
  a change in behavior is required, a new VFS should be registered.
  The application could, perhaps, use sqlite3_vfs_find() to locate
  the old VFS, make a copy of the old VFS into a new sqlite3_vfs
  object, make the desired modifications to the new VFS, unregister
  the old VFS, the register the new VFS in its place.  Existing
  database connections would continue to use the old VFS even after
  it is unregistered, but new database connections would use the
  new VFS.

2.1.4 The VFS Object

  A VFS object is an instance of the following structure:

typedef struct sqlite3_vfs sqlite3_vfs;
struct sqlite3_vfs {
  int iVersion;            /* Structure version number */
  int szOsFile;            /* Size of subclassed sqlite3_file */
  int mxPathname;          /* Maximum file pathname length */
  sqlite3_vfs *pNext;      /* Next registered VFS */
  const char *zName;       /* Name of this virtual file system */
  void *pAppData;          /* Pointer to application-specific data */
  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
               int flags, int *pOutFlags);
  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags);
  int (*xGetTempName)(sqlite3_vfs*, char *zOut);
  int (*xFullPathname)(sqlite3_vfs*, const char *zName, char *zOut);
  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol);
  void (*xDlClose)(sqlite3_vfs*, void*);
  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  int (*xSleep)(sqlite3_vfs*, int microseconds);
  int (*xCurrentTime)(sqlite3_vfs*, double*);
  /* New fields may be appended in figure versions.  The iVersion
  ** value will increment whenever this happens. */
};

  To create a new VFS, an application fills in an instance of this
  structure with appropriate values and then calls sqlite3_vfs_register().

  The iVersion field of sqlite3_vfs should be 1 for SQLite version 3.5.0.
  This number may increase in future versions of SQLite if we have to
  modify the VFS object in some way.  We hope that this never happens,
  but the provision is made in case it does.

  The szOsFile field is the size in bytes of the structure that defines
  an open file: the sqlite3_file object.  This object will be described
  more fully below.  The point here is that each VFS implementation can
  define its own sqlite3_file object containing whatever information
  the VFS implementation needs to store about an open file.  SQLite needs
  to know how big this object is, however, in order to preallocate enough
  space to hold it.

  The mxPathname field is the maximum length of a file pathname that
  this VFS can use.  SQLite sometimes has to preallocate buffers of
  this size, so it should be as small as reasonably possible.  Some
  filesystems permit huge pathnames, but in practice pathnames rarely
  extend beyond 100 bytes or so.  You do not have to put the longest
  pathname that the underlying filesystem can handle here.  You only
  have to put the longest pathname that you want SQLite to be able to
  handle.  A few hundred is a good value in most cases.

  The pNext field is used internally by SQLite.  Specifically, SQLite
  uses this field to form a linked list of registered VFSes.

  The zName field is the symbolic name of the VFS.  This is the name
  that the sqlite3_vfs_find() compares against when it is looking for
  a VFS.

  The pAppData pointer is unused by the SQLite core.  The pointer is
  available to store auxiliary information that a VFS information might
  want to carry around.

  The remaining fields of the sqlite3_vfs object all store pointer
  to functions that implement primitive operations.  We call these
  "methods".  The first methods, xOpen, is used to open files on
  the underlying storage media.  The result is an sqlite3_file
  object.  There are additional methods, defined by the sqlite3_file
  object itself that are used to read and write and close the file.
  The additional methods are detailed below.  The filename is in UTF-8.
  SQLite will guarantee that the zFilename string passed to
  xOpen() is a full pathname as generated by xFullPathname() and
  that the string will be valid and unchanged until xClose() is
  called.  So the sqlite3_file can store a pointer to the
   filename if it needs to remember the filename for some reason.
   The flags argument to xOpen() is a copy of the flags argument
   to sqlite3_open_v2().  If sqlite3_open() or sqlite3_open16()
   is used, then flags is SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE.
   If xOpen() opens a file read-only then it sets *pOutFlags to
   include SQLITE_OPEN_READONLY.  Other bits in *pOutFlags may be
   set.
   SQLite will also add one of the following flags to the xOpen()
   call, depending on the object being opened:

  SQLITE_OPEN_MAIN_DB

  SQLITE_OPEN_MAIN_JOURNAL

  SQLITE_OPEN_TEMP_DB

  SQLITE_OPEN_TEMP_JOURNAL

  SQLITE_OPEN_TRANSIENT_DB

  SQLITE_OPEN_SUBJOURNAL

  SQLITE_OPEN_MASTER_JOURNAL

   The file I/O implementation can use the object type flags to
   changes the way it deals with files.  For example, an application
   that does not care about crash recovery or rollback, might make
   the open of a journal file a no-op.  Writes to this journal are
   also a no-op.  Any attempt to read the journal returns SQLITE_IOERR.
   Or the implementation might recognize the a database file will
   be doing page-aligned sector reads and writes in a random order
   and set up its I/O subsystem accordingly.
   SQLite might also add one of the following flags to the xOpen
   method:

 SQLITE_OPEN_DELETEONCLOSE

 SQLITE_OPEN_EXCLUSIVE

   The SQLITE_OPEN_DELETEONCLOSE flag means the file should be
   deleted when it is closed.  This will always be set for TEMP
   databases and journals and for subjournals.  The
   SQLITE_OPEN_EXCLUSIVE flag means the file should be opened
   for exclusive access.  This flag is set for all files except
   for the main database file.
   The sqlite3_file structure passed as the third argument to
   xOpen is allocated by the caller.  xOpen just fills it in.  The
   caller allocates a minimum of szOsFile bytes for the sqlite3_file
   structure.

  The differences between an SQLITE_OPEN_TEMP_DB database and an
  SQLITE_OPEN_TRANSIENT_DB database is this:  The SQLITE_OPEN_TEMP_DB
  is used for explicitly declared and named TEMP tables (using the
  CREATE TEMP TABLE syntax) or for named tables in a temporary database
  that is created by opening a database with a filename that is an empty
  string.  An SQLITE_OPEN_TRANSIENT_DB holds an database table that
  SQLite creates automatically in order to evaluate a subquery or
  ORDER BY or GROUP BY clause.  Both TEMP_DB and TRANSIENT_DB databases
  are private and are deleted automatically.  TEMP_DB databases last
  for the duration of the database connection.  TRANSIENT_DB databases
  last only for the duration of a single SQL statement.

  The xDelete method is used delete a file.  The name of the file is
  given in the second parameter.  The filename will be in UTF-8.
  The VFS must convert the filename into whatever character representation
  the underlying operating system expects.  If the syncDir parameter is
  true, then the xDelete method should not return until the change
  to the directory contents for the directory containing the
  deleted file have been synced to disk in order to insure that the
  file does not "reappear" if a power failure occurs soon after.

  The xAccess method is used to check for access permissions on a file.
  The filename will be UTF-8 encoded.  The flags argument will be
  SQLITE_ACCESS_EXISTS to check for the existence of the file,
  SQLITE_ACCESS_READWRITE to check to see if the file is both readable
  and writable, or SQLITE_ACCESS_READ to check to see if the file is
  at least readable.  The "file" named by the second parameter might
  be a directory or folder name.

  The xGetTempName method computes the name of a temporary file that
  SQLite can use.  The name should be written into the buffer given
  by the second parameter.  SQLite will size that buffer to hold
  at least mxPathname bytes.  The generated filename should be in UTF-8.
  To avoid security problems, the generated temporary filename should
  contain enough randomness to prevent an attacker from guessing the
  temporary filename in advance.

  The xFullPathname method is used to convert a relative pathname
  into a full pathname.  The resulting full pathname is written into
  the buffer provided by the third parameter.  SQLite will size the
  output buffer to at least mxPathname bytes.  Both the input and
  output names should be in UTF-8.

  The xDlOpen, xDlError, xDlSym, and xDlClose methods are all used for
  accessing shared libraries at run-time.  These methods may be omitted
  (and their pointers set to zero) if the library is compiled with
  SQLITE_OMIT_LOAD_EXTENSION or if the sqlite3_enable_load_extension()
  interface is never used to enable dynamic extension loading.  The
  xDlOpen method opens a shared library or DLL and returns a pointer to
  a handle.  NULL is returned if the open fails.  If the open fails,
  the xDlError method can be used to obtain a text error message.
  The message is written into the zErrMsg buffer of the third parameter
  which is at least nByte bytes in length.  The xDlSym returns a pointer
  to a symbol in the shared library.  The name of the symbol is given
  by the second parameter.  UTF-8 encoding is assumed.  If the symbol
  is not found a NULL pointer is returned.  The xDlClose routine closes
  the shared library.

  The xRandomness method is used exactly once to initialize the
  pseudo-random number generator (PRNG) inside of SQLite.  Only
  the xRandomness method on the default VFS is used.  The xRandomness
  methods on other VFSes are never accessed by SQLite.
  The xRandomness routine requests that nByte bytes of randomness
  be written into zOut.  The routine returns the actual number of
  bytes of randomness obtained.  The quality of the randomness so obtained
  will determine the quality of the randomness generated by built-in
  SQLite functions such as random() and randomblob().  SQLite also
  uses its PRNG to generate temporary file names..  On some platforms
  (ex: Windows) SQLite assumes that temporary file names are unique
  without actually testing for collisions, so it is important to have
  good-quality randomness even if the random() and randomblob()
  functions are never used.

  The xSleep method is used to suspend the calling thread for at
  least the number of microseconds given.  This method is used to
  implement the sqlite3_sleep() and sqlite3_busy_timeout() APIs.
  In the case of sqlite3_sleep() the xSleep method of the default
  VFS is always used.  If the underlying system does not have a
  microsecond resolution sleep capability, then the sleep time should
  be rounded up.  xSleep returns this rounded-up value.

  The xCurrentTime method finds the current time and date and writes
  the result as double-precision floating point value into pointer
  provided by the second parameter.  The time and date is in
  coordinated universal time (UTC) and is a fractional Julian day number.

2.1.5 The Open File Object

  The result of opening a file is an instance of an sqlite3_file object.
  The sqlite3_file object is an abstract base class defined as follows:

typedef struct sqlite3_file sqlite3_file;
struct sqlite3_file {
  const struct sqlite3_io_methods *pMethods;
};

  Each VFS implementation will subclass the sqlite3_file by adding
  additional fields at the end to hold whatever information the VFS
  needs to know about an open file.  It does not matter what information
  is stored as long as the total size of the structure does not exceed
  the szOsFile value recorded in the sqlite3_vfs object.

  The sqlite3_io_methods object is a structure that contains pointers
  to methods for reading, writing, and otherwise dealing with files.
  This object is defined as follows:

typedef struct sqlite3_io_methods sqlite3_io_methods;
struct sqlite3_io_methods {
  int iVersion;
  int (*xClose)(sqlite3_file*);
  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  int (*xSync)(sqlite3_file*, int flags);
  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  int (*xLock)(sqlite3_file*, int);
  int (*xUnlock)(sqlite3_file*, int);
  int (*xCheckReservedLock)(sqlite3_file*);
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  int (*xSectorSize)(sqlite3_file*);
  int (*xDeviceCharacteristics)(sqlite3_file*);
  /* Additional methods may be added in future releases */
};

  The iVersion field of sqlite3_io_methods is provided as insurance
  against future enhancements.  The iVersion value should always be
  1 for SQLite version 3.5.

  The xClose method closes the file.  The space for the sqlite3_file
  structure is deallocated by the caller.  But if the sqlite3_file
  contains pointers to other allocated memory or resources, those
  allocations should be released by the xClose method.

  The xRead method reads iAmt bytes from the file beginning at a byte
  offset to iOfst.  The data read is stored in the pointer of the
  second parameter.  xRead returns the SQLITE_OK on success,
  SQLITE_IOERR_SHORT_READ if it was not able to read the full number
  of bytes because it reached end-of-file, or SQLITE_IOERR_READ for
  any other error.

  The xWrite method writes iAmt bytes of data from the second parameter
  into the file beginning at an offset of iOfst bytes.  If the size of
  the file is less than iOfst bytes prior to the write, then xWrite should
  ensure that the file is extended with zeros up to iOfst bytes prior
  to beginning its write.  xWrite continues to extends the file as
  necessary so that the size of the file is at least iAmt+iOfst bytes
  at the conclusion of the xWrite call.  The xWrite method returns
  SQLITE_OK on success.  If the write cannot complete because the
  underlying storage medium is full, then SQLITE_FULL is returned.
  SQLITE_IOERR_WRITE should be returned for any other error.

  The xTruncate method truncates a file to be nByte bytes in length.
  If the file is already nByte bytes or less in length then this
  method is a no-op.  The xTruncate method returns SQLITE_OK on
  success and SQLITE_IOERR_TRUNCATE if anything goes wrong.

  The xSync method is used to force previously written data out of
  operating system cache and into non-volatile memory.  The second
  parameter is usually SQLITE_SYNC_NORMAL.  If the second parameter
  is SQLITE_SYNC_FULL then the xSync method should make sure that
  data has also been flushed through the disk controllers cache.
  The SQLITE_SYNC_FULL parameter is the equivalent of the F_FULLSYNC
  ioctl() on Mac OS X. The xSync method returns
  SQLITE_OK on success and SQLITE_IOERR_FSYNC if anything goes wrong.

  The xFileSize() method determines the current size of the file
  in bytes and writes that value into *pSize.  It returns SQLITE_OK
  on success and SQLITE_IOERR_FSTAT if something goes wrong.

  The xLock and xUnlock methods are used to set and clear file locks.
  SQLite supports five levels of file locks, in order:

 SQLITE_LOCK_NONE

 SQLITE_LOCK_SHARED

 SQLITE_LOCK_RESERVED

 SQLITE_LOCK_PENDING

 SQLITE_LOCK_EXCLUSIVE

  The underlying implementation can support some subset of these locking
  levels as long as it meets the other requirements of this paragraph.
  The locking level is specified as the second argument to both xLock
  and xUnlock.  The xLock method increases the locking level to the
  specified locking level or higher.  The xUnlock method decreases the
  locking level to no lower than the level specified.
  SQLITE_LOCK_NONE means that the file is unlocked.  SQLITE_LOCK_SHARED
  gives permission to read the file.  Multiple database connections can
  hold SQLITE_LOCK_SHARED at the same time.
  SQLITE_LOCK_RESERVED is like SQLITE_LOCK_SHARED in that its is permission
  to read the file.  But only a single connection can hold a reserved lock
  at any point in time.  The SQLITE_LOCK_PENDING is also permission to
  read the file.  Other connections can continue to read the file as well,
  but no other connection is allowed to escalate a lock from none to shared.
  SQLITE_LOCK_EXCLUSIVE is permission to write on the file.  Only a single
  connection can hold an exclusive lock and no other connection can hold
  any lock (other than "none") while one connection is hold an exclusive
  lock.  The xLock returns SQLITE_OK on success, SQLITE_BUSY if it
  is unable to obtain the lock, or SQLITE_IOERR_RDLOCK if something else
  goes wrong.  The xUnlock method returns SQLITE_OK on success and
  SQLITE_IOERR_UNLOCK for problems.

  The xCheckReservedLock method checks to see if another connection or
  another process is currently holding a reserved, pending, or exclusive
  lock on the file.  It returns true or false.

  The xFileControl() method is a generic interface that allows custom
  VFS implementations to directly control an open file using the
  (new and experimental)
  sqlite3_file_control() interface.  The second "op" argument
  is an integer opcode.   The third
  argument is a generic pointer which is intended to be a pointer
  to a structure that may contain arguments or space in which to
  write return values.  Potential uses for xFileControl() might be
  functions to enable blocking locks with timeouts, to change the
  locking strategy (for example to use dot-file locks), to inquire
  about the status of a lock, or to break stale locks.  The SQLite
  core reserves opcodes less than 100 for its own use.
  A list of opcodes less than 100 is available.
  Applications that define a custom xFileControl method should use opcodes
  greater than 100 to avoid conflicts.

  The xSectorSize returns the "sector size" of the underlying
  non-volatile media.  A "sector" is defined as the smallest unit of
  storage that can be written without disturbing adjacent storage.
  On a disk drive the "sector size" has until recently been 512 bytes,
  though there is a push to increase this value to 4KiB.  SQLite needs
  to know the sector size so that it can write a full sector at a
  time, and thus avoid corrupting adjacent storage space if a power
  lose occurs in the middle of a write.

  The xDeviceCharacteristics method returns an integer bit vector that
  defines any special properties that the underlying storage medium might
  have that SQLite can use to increase performance.  The allowed return
  is the bit-wise OR of the following values:

 SQLITE_IOCAP_ATOMIC

 SQLITE_IOCAP_ATOMIC512

 SQLITE_IOCAP_ATOMIC1K

 SQLITE_IOCAP_ATOMIC2K

 SQLITE_IOCAP_ATOMIC4K

 SQLITE_IOCAP_ATOMIC8K

 SQLITE_IOCAP_ATOMIC16K

 SQLITE_IOCAP_ATOMIC32K

 SQLITE_IOCAP_ATOMIC64K

 SQLITE_IOCAP_SAFE_APPEND

 SQLITE_IOCAP_SEQUENTIAL

  The SQLITE_IOCAP_ATOMIC bit means that all writes to this device are
  atomic in the sense that either the entire write occurs or none of it
  occurs.  The other
  SQLITE_IOCAP_ATOMICnnn values indicate that
  writes of aligned blocks of the indicated size are atomic.
  SQLITE_IOCAP_SAFE_APPEND means that when extending a file with new
  data, the new data is written first and then the file size is updated.
  So if a power failure occurs, there is no chance that the file might have
  been extended with randomness.  The SQLITE_IOCAP_SEQUENTIAL bit means
  that all writes occur in the order that they are issued and are not
  reordered by the underlying file system.

2.1.6 Checklist For Constructing A New VFS

  The preceding paragraphs contain a lot of information.
  To ease the task of constructing
  a new VFS for SQLite we offer the following implementation checklist:

 Define an appropriate subclass of the sqlite3_file object.

 Implement the methods required by the sqlite3_io_methods object.

 Create a static and
       constant sqlite3_io_methods object containing pointers
       to the methods from the previous step.

 Implement the xOpen method that opens a file and populates an
       sqlite3_file object, including setting pMethods to
       point to the sqlite3_io_methods object from the previous step.

 Implement the other methods required by sqlite3_vfs.

 Define a static (but not constant) sqlite3_vfs structure that
       contains pointers to the xOpen method and the other methods and
       which contains the appropriate values for iVersion, szOsFile,
       mxPathname, zName, and pAppData.

 Implement a procedure that calls sqlite3_vfs_register() and
       passes it a pointer to the sqlite3_vfs structure from the previous
       step.  This procedure is probably the only exported symbol in the
       source file that implements your VFS.

  Within your application, call the procedure implemented in the last
  step above as part of your initialization process before any
  database connections are opened.

3.0 The Memory Allocation Subsystem

  Beginning with version 3.5, SQLite obtains all of the heap memory it
  needs using the routines sqlite3_malloc(), sqlite3_free(), and
  sqlite3_realloc().  These routines have existed in prior versions
  of SQLite, but SQLite has previously bypassed these routines and used
  its own memory allocator.  This all changes in version 3.5.0.

  The SQLite source tree actually contains multiple versions of the
  memory allocator.  The default high-speed version found in the
  "mem1.c" source file is used for most builds.  But if the SQLITE_MEMDEBUG
  flag is enabled, a separate memory allocator the "mem2.c" source file
  is used instead.  The mem2.c allocator implements lots of hooks to
  do error checking and to simulate memory allocation failures for testing
  purposes.  Both of these allocators use the malloc()/free() implementation
  in the standard C library.

  Applications are not required to use either of these standard memory
  allocators.  If SQLite is compiled with SQLITE_OMIT_MEMORY_ALLOCATION
  then no implementation for the sqlite3_malloc(), sqlite3_realloc(),
  and sqlite3_free() functions is provided.  Instead, the application
  that links against SQLite must provide its own implementation of these
  functions.  The application provided memory allocator is not required
  to use the malloc()/free() implementation in the standard C library.
  An embedded application might provide an alternative memory allocator
  that uses memory for a fixed memory pool set aside for the exclusive
  use of SQLite, for example.

  Applications that implement their own memory allocator must provide
  implementation for the usual three allocation functions
  sqlite3_malloc(), sqlite3_realloc(), and sqlite3_free().
  And they must also implement a fourth function:

int sqlite3_memory_alarm(
  void(*xCallback)(void *pArg, sqlite3_int64 used, int N),
  void *pArg,
  sqlite3_int64 iThreshold
);

 The sqlite3_memory_alarm routine is used to register
 a callback on memory allocation events.
 This routine registers or clears a callbacks that fires when
 the amount of memory allocated exceeds iThreshold.  Only
 a single callback can be registered at a time.  Each call
 to sqlite3_memory_alarm() overwrites the previous callback.
 The callback is disabled by setting xCallback to a NULL
 pointer.

 The parameters to the callback are the pArg value, the
 amount of memory currently in use, and the size of the
 allocation that provoked the callback.  The callback will
 presumably invoke sqlite3_free() to free up memory space.
 The callback may invoke sqlite3_malloc() or sqlite3_realloc()
 but if it does, no additional callbacks will be invoked by
 the recursive calls.

 The sqlite3_soft_heap_limit() interface works by registering
 a memory alarm at the soft heap limit and invoking
 sqlite3_release_memory() in the alarm callback.  Application
 programs should not attempt to use the sqlite3_memory_alarm()
 interface because doing so will interfere with the
 sqlite3_soft_heap_limit() module.  This interface is exposed
 only so that applications can provide their own
 alternative implementation when the SQLite core is
 compiled with SQLITE_OMIT_MEMORY_ALLOCATION.

  The built-in memory allocators in SQLite also provide the following
  additional interfaces:

sqlite3_int64 sqlite3_memory_used(void);
sqlite3_int64 sqlite3_memory_highwater(int resetFlag);

  These interfaces can be used by an application to monitor how
  much memory SQLite is using.  The sqlite3_memory_used() routine
  returns the number of bytes of memory currently in use and the
  sqlite3_memory_highwater() returns the maximum instantaneous
  memory usage.  Neither routine includes the overhead associated
  with the memory allocator.  These routines are provided for use
  by the application.  SQLite never invokes them itself.  So if
  the application is providing its own memory allocation subsystem,
  it can omit these interfaces if desired.

4.0 The Mutex Subsystem

  SQLite has always been threadsafe in the sense that it is safe to
  use different SQLite database connections in different threads at the
  same time.  The constraint was that the same database connection
  could not be used in two separate threads at once.  SQLite version 3.5.0
  relaxes this constraint.

  In order to allow multiple threads to use the same database connection
  at the same time, SQLite must make extensive use of mutexes.  And for
  this reason a new mutex subsystem as been added.  The mutex subsystem
  as the following interface:

sqlite3_mutex *sqlite3_mutex_alloc(int);
void sqlite3_mutex_free(sqlite3_mutex*);
void sqlite3_mutex_enter(sqlite3_mutex*);
int sqlite3_mutex_try(sqlite3_mutex*);
void sqlite3_mutex_leave(sqlite3_mutex*);

  Though these routines exist for the use of the SQLite core,
  application code is free to use these routines as well, if desired.
  A mutex is an sqlite3_mutex object.  The sqlite3_mutex_alloc()
  routine allocates a new mutex object and returns a pointer to it.
  The argument to sqlite3_mutex_alloc() should be
  SQLITE_MUTEX_FAST or SQLITE_MUTEX_RECURSIVE for non-recursive
  and recursive mutexes, respectively.  If the underlying system does
  not provide non-recursive mutexes, then a recursive mutex can be
  substituted in that case.  The argument to sqlite3_mutex_alloc()
  can also be a constant designating one of several static mutexes:

  SQLITE_MUTEX_STATIC_MASTER

  SQLITE_MUTEX_STATIC_MEM

  SQLITE_MUTEX_STATIC_MEM2

  SQLITE_MUTEX_STATIC_PRNG

  SQLITE_MUTEX_STATIC_LRU

  These static mutexes are reserved for use internally by SQLite
  and should not be used by the application.  The static mutexes
  are all non-recursive.

  The sqlite3_mutex_free() routine should be used to deallocate
  a non-static mutex.  If a static mutex is passed to this routine
  then the behavior is undefined.

  The sqlite3_mutex_enter() attempts to enter the mutex and blocks
  if another threads is already there.  sqlite3_mutex_try() attempts
  to enter and returns SQLITE_OK on success or SQLITE_BUSY if another
  thread is already there.  sqlite3_mutex_leave() exits a mutex.
  The mutex is held until the number of exits matches the number of
  entrances.  If sqlite3_mutex_leave() is called on a mutex that
  the thread is not currently holding, then the behavior is undefined.
  If any routine is called for a deallocated mutex, then the behavior
  is undefined.

  The SQLite source code provides multiple implementations of these
  APIs, suitable for varying environments.  If SQLite is compiled with
  the SQLITE_THREADSAFE=0 flag then a no-op mutex implementation that
  is fast but does no real mutual exclusion is provided.  That
  implementation is suitable for use in single-threaded applications
  or applications that only use SQLite in a single thread.  Other
  real mutex implementations are provided based on the underlying
  operating system.

  Embedded applications may wish to provide their own mutex implementation.
  If SQLite is compiled with the -DSQLITE_MUTEX_APPDEF=1 compile-time flag
  then the SQLite core provides no mutex subsystem and a mutex subsystem
  that matches the interface described above must be provided by the
  application that links against SQLite.

5.0 Other Interface Changes

  Version 3.5.0 of SQLite changes the behavior of a few APIs in ways
  that are technically incompatible.  However, these APIs are seldom
  used and even when they are used it is difficult to imagine a
  scenario where the change might break something.  The changes
  actually makes these interface much more useful and powerful.

  Prior to version 3.5.0, the sqlite3_enable_shared_cache() API
  would enable and disable the shared cache feature for all connections
  within a single thread - the same thread from which the
  sqlite3_enable_shared_cache() routine was called.  Database connections
  that used the shared cache were restricted to running in the same
  thread in which they were opened.  Beginning with version 3.5.0,
  the sqlite3_enable_shared_cache() applies to all database connections
  in all threads within the process.  Now database connections running
  in separate threads can share a cache.  And database connections that
  use shared cache can migrate from one thread to another.

  Prior to version 3.5.0 the sqlite3_soft_heap_limit() set an upper
  bound on heap memory usage for all database connections within a
  single thread.  Each thread could have its own heap limit.  Beginning
  in version 3.5.0, there is a single heap limit for the entire process.
  This seems more restrictive (one limit as opposed to many) but in
  practice it is what most users want.

  Prior to version 3.5.0 the sqlite3_release_memory() function would
  try to reclaim memory from all database connections in the same thread
  as the sqlite3_release_memory() call.  Beginning with version 3.5.0,
  the sqlite3_release_memory() function will attempt to reclaim memory
  from all database connections in all threads.

6.0 Summary

  The transition from SQLite version 3.4.2 to 3.5.0 is a major change.
  Every source code file in the SQLite core had to be modified, some
  extensively.  And the change introduced some minor incompatibilities
  in the C interface.  But we feel that the benefits of the transition
  from 3.4.2 to 3.5.0 far outweigh the pain of porting.  The new
  VFS layer is now well-defined and stable and should simplify future
  customizations.  The VFS layer, and the separable memory allocator
  and mutex subsystems allow a standard SQLite source code amalgamation
  to be used in an embedded project without change, greatly simplifying
  configuration management.  And the resulting system is much more
  tolerant of highly threaded designs.

This page last modified 2008/11/12 14:10:29 UTC


text:
var _ = require('underscore');
var fs = require('fs');
var handlebars = require('handlebars');
var path = require('path');
var rimraf = require('rimraf');
var uuid = require('node-uuid');

var pkg = require('../package.json');

// Baller meta directory
var BALLER_META_DIR = '.baller';

// Scripts used by Baller
var SCRIPTS = fs.readdirSync(getScriptPath());

// Templates generated by Baller
var GENERATED_TEMPLATES = _.map(fs.readdirSync(getTemplatePath()), function (template) {
  return template.slice(0, template.lastIndexOf('.'));
});

// Files introduced by Baller
var BALLER_FILES = [
  BALLER_META_DIR
].concat(
  SCRIPTS,
  GENERATED_TEMPLATES
);

// Subdirectory used by Baller to store files
var FILES_DIR = 'files';

var IGNORED_FILES = [
  BALLER_META_DIR,
  '.git'
];

/*
 * Create a new, empty ball in a new directory.
 *
 * Returns a success message if successful. Throws an error if unsuccessful.
 */
function create(name) {
  var errorMessage = 'Could not create ball';

  if (!name) {
    throw new Error(errorMessage + ': no name given');
  }

  // Create a new directory (fail and exist if dir exists or other failure)
  try {
    fs.mkdirSync(name);
  } catch (e) {
    if (e.errno === 47) {
      errorMessage += ': Directory "' + name + '" already exists';
    }
    throw new Error(errorMessage);
  }

  createFilesDir({
    dir: name,
    errorMessage: errorMessage
  });

  createBallerMetadata({
    dir: name,
    errorMessage: errorMessage
  });

  writeRenderedReadme({
    name: name,
    dir: name,
    errorMessage: errorMessage
  });

  copyScriptsToDirectory({
    dir: name,
    errorMessage: errorMessage
  });

  return 'Created "' + name + '" ball';
}

/*
 * Initialize current directory and files as a ball.
 *
 * Returns a success message if successful. Throws an error if unsuccessful.
 */
function init() {
  var errorMessage = 'Could not initialize ball';
  var name = path.basename(process.cwd());

  createFilesDir({
    errorMessage: errorMessage
  });

  createBallerMetadata({
    errorMessage: errorMessage
  });

  writeRenderedReadme({
    name: name,
    errorMessage: errorMessage
  });

  copyScriptsToDirectory({
    errorMessage: errorMessage
  });

  return 'Initialized "' + name + '" ball';
}

/*
 * Remove all Baller scripts from current ball and move files in `files`
 * subdirectory to current directory.
 *
 * Returns a success message if successful. Throws an error if unsuccessful.
 */
function destroy() {
  var errorMessage = 'Could not destroy ball';
  var name = path.basename(process.cwd());

  var isBall = fs.existsSync(BALLER_META_DIR);
  if (!isBall) {
    throw new Error(errorMessage + ': directory "' + name + '" is not a ball');
  }

  try {

    // Remove all Baller files
    _.each(BALLER_FILES, function (file) {
      rimraf.sync(file);
    });

    // Move `files` directory to unused path so contained files can be moved
    // into same directory without collision
    var tmpFilesDir = getUnusedPath();
    fs.renameSync(FILES_DIR, tmpFilesDir);

    // Move all contents out of `files` subdirectory
    var files = fs.readdirSync(tmpFilesDir);
    _.each(files, function (file) {
      fs.renameSync(path.join(tmpFilesDir, file), file);
    });

    // Remove the `files` subdirectory
    fs.rmdirSync(tmpFilesDir);

    return 'Destroyed "' + name + '" ball';
  } catch (e) {
    throw new Error(errorMessage);
  }
}

/*
 * Return absolute path for module-owned file
 */
function getModulePath(name, dir) {
  var path = __dirname + '/../' + dir;
  if (name) {
    path += '/' + name;
  }
  return path;
}

/*
 * Return path for template
 */
function getTemplatePath(template) {
  return getModulePath(template, 'templates');
}

/*
 * Return path for script
 */
function getScriptPath(script) {
  return getModulePath(script, 'scripts');
}

/*
 * Render template resource with given context and return result
 */
function renderTemplate(template, context) {
  var source = fs.readFileSync(getTemplatePath(template)).toString();
  var compiledTemplate = handlebars.compile(source);
  return compiledTemplate(context);
}

/*
 * Create `files` subdirectory and move any existing files and directories into
 * it (excluding Baller files)
 *
 * Options:
 * - dir: Directory in which `files` subdirectory will be created (default: '.')
 * - errorMessage: Base error message (default: 'Error')
 */
function createFilesDir(options) {
  options.dir = options.dir || '.';
  options.errorMessage = options.errorMessage || 'Error';

  try {
    // Build list of files to move
    var files = _.difference(fs.readdirSync(options.dir), IGNORED_FILES);

    // Create a temporary `files` dir at an unused path
    var tmpFilesDir = getUnusedPath(options.dir);
    fs.mkdirSync(tmpFilesDir);

    // Move files into `files` subdirectory
    _.each(files, function (file) {
      fs.renameSync(file, path.join(tmpFilesDir, file));
    });

    // Rename temporary `files` dir to proper name
    var filesDir = path.join(options.dir, FILES_DIR);
    fs.renameSync(tmpFilesDir, filesDir);
  } catch (e) {
    throw new Error(options.errorMessage + ': "files" subdirectory creation failed');
  }
}

/*
 * Add Baller metadata to directory. This turns a directory into a "ball".
 *
 * If directory already contains Baller metadata, creation will be aborted.
 *
 * Options:
 * - dir: Directory in which metadata will be create (default: '.')
 * - errorMessage: Base error message (default: 'Error')
 */
function createBallerMetadata(options) {
  options.dir = options.dir || '.';
  options.errorMessage = options.errorMessage || 'Error';

  var ballerMetaPath = path.join(options.dir, BALLER_META_DIR);
  var isBall = fs.existsSync(ballerMetaPath);

  if (isBall) {
    throw new Error(options.errorMessage + ': directory is already a ball');
  }

  try {
    fs.mkdirSync(ballerMetaPath);
    fs.writeFileSync(path.join(ballerMetaPath, 'version'), pkg.version);
  } catch (e) {
    throw new Error(options.errorMessage + ': metadata creation failed');
  }
}

/*
 * Write rendered README.md to directory
 *
 * Options:
 * - name: Ball name that will be used in README.md (required)
 * - dir: Directory in which README.md will be created
 * - errorMessage: Base error message (default: 'Error')
 */
function writeRenderedReadme(options) {
  options.dir = options.dir || '.';
  options.errorMessage = options.errorMessage || 'Error';

  try {
    var readmePath = path.join(options.dir, 'README.md');
    var context = {
      name: options.name,
      username: process.env.USER
    };
    fs.writeFileSync(readmePath, renderTemplate('README.md.hbs', context));
  } catch (e) {
    throw new Error(options.errorMessage + ': README creation failed');
  }
}

/*
 * Copy scripts to directory
 *
 * Options:
 * - dir: Directory to which files will be copied (default: '.')
 * - errorMessage: Base error message (default: 'Error')
 */
function copyScriptsToDirectory(options) {
  options.dir = options.dir || '.';
  options.errorMessage = options.errorMessage || 'Error';

  try {
    copyDirSyncWithMode(getScriptPath(), options.dir);
  } catch (e) {
    throw new Error(options.errorMessage + ': scripts creation failed');
  }
}

/*
 * Recursively copy contents of one directory to another. Copies file modes
 * (including permissions) as well. Synchronous.
 *
 * Assumptions:
 * - src and dest directories both exist
 * - dest directory is empty (or may have files overwritten)
 *
 * Parameters:
 * - src: Source directory (required)
 * - dest: Destination directory (required)
 */
function copyDirSyncWithMode(src, dest) {
  var files = fs.readdirSync(src);
  _.each(files, function (file) {
    var srcFile = path.join(src, file);
    var destFile = path.join(dest, file);
    var mode = fs.statSync(srcFile).mode;
    if (fs.statSync(srcFile).isDirectory()) {
      fs.mkdirSync(destFile);
      copyDirSyncWithMode(srcFile, destFile);
    } else {
      var content = fs.readFileSync(srcFile);
      fs.writeFileSync(destFile, content);
    }
    fs.chmodSync(destFile, mode);
  });
}

/*
 * Return unused file path
 *
 * Parameters:
 * - dir: directory under which file path will be (default: '.')
 */
function getUnusedPath(dir) {
  dir = dir || '.';

  var unusedPath;
  do {
    unusedPath = path.join(dir, uuid.v4());
  } while (fs.existsSync(unusedPath));

  return unusedPath;
}

module.exports = {
  create: create,
  init: init,
  destroy: destroy
};


text:
//--------------------------------------------------------------------------
//  <copyright file="retrieveExternalEntity.cs" company="Microsoft">
//      Copyright (c) 2015 Microsoft Corporation.
//
//      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
//
//      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.
//  </copyright>
//--------------------------------------------------------------------------

namespace Microsoft.Dynamics.Marketing.Powershell.API.Commands.ExternalEntity
{
    using System.Management.Automation;
    using SDK.Messages.ExternalEntity;

    /// <summary>
    /// Command to setup the Azure namespace and authentication used by all other commands.
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "MDMExternalEntity")]
    public class RetrieveExternalEntity : TypedCmdlet<RetrieveExternalEntityRequest, RetrieveExternalEntityResponse>
    {
        /// <summary>
        /// Gets or sets the category in which it is stored.
        /// </summary>
        [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        [ValidateNotNullOrEmpty]
        public string CategoryName
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the id of the external entity.
        /// </summary>
        [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
        [ValidateNotNullOrEmpty]
        public string ExternalId
        {
            get;
            set;
        }

        /// <summary>
        /// ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            if (string.IsNullOrEmpty(this.CategoryName))
            {
                throw new PSArgumentNullException("CategoryName");
            }

            if (string.IsNullOrEmpty(this.ExternalId))
            {
                throw new PSArgumentNullException("ExternalId");
            }

            var request = this.NewRequest();
            request.CategoryName = this.CategoryName;
            request.ExternalId = this.ExternalId;

            var response = this.ProcessRequest(request);
            if (response == null)
            {
                return;
            }

            if (!response.Succeeded)
            {
                this.WriteVerbose("Command has failed:" + response.Message);
            }

            this.WriteObject(response.ExternalEntity);
        }
    }
}


text:
package org.apache.karaf.event.command;

import static org.apache.karaf.event.service.TopicPredicate.matchTopic;

import java.util.function.Consumer;
import java.util.function.Predicate;

import org.apache.karaf.event.service.EventCollector;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.console.Session;
import org.osgi.framework.BundleContext;
import org.osgi.service.event.Event;

@Command(scope = "event", name = "tail", description = "Shows events and listens for incoming events")
@Service
public class EventTailCommand implements Action {

    @Reference
    Session session;

    @Reference
    BundleContext context;

    @Reference
    EventCollector collector;

    @Argument
    String topicFilter = "*";

    @Option(name = "-v")
    boolean verbose = false;

    @Override
    public Object execute() throws Exception {
        EventPrinter printer = new EventPrinter(session.getConsole(), verbose);
        Consumer<Event> filteredPrinter = executeIf(matchTopic(topicFilter), printer);
        collector.addConsumer(filteredPrinter);
        try {
            waitTillInterrupted();
        } catch (InterruptedException e) {
            collector.removeConsumer(filteredPrinter);
        }
        return null;
    }

    private <T> Consumer<T> executeIf(Predicate<T> pred, Consumer<T> consumer) {
        return t -> {if (pred.test(t)) consumer.accept(t);};
    }

    private void waitTillInterrupted() throws InterruptedException {
        while (true) {
            Thread.sleep(100);
        }
    }
}


text:
package com.barrycommins;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.integration.annotation.IntegrationComponentScan;

@EnableDiscoveryClient
@EnableJpaRepositories
@EnableBinding(Source.class)
@IntegrationComponentScan
@SpringBootApplication
public class AccountServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(AccountServiceApplication.class, args);
    }
}


text:
<?php

date_default_timezone_set('America/Sao_Paulo');

require __DIR__.'/../vendor/autoload.php';

use ClearSale\ClearSaleAnalysis;
use ClearSale\Environment\Sandbox;
use ClearSale\XmlEntity\SendOrder\Address;
use ClearSale\XmlEntity\SendOrder\AbstractCustomer;
use ClearSale\XmlEntity\SendOrder\Connection;
use ClearSale\XmlEntity\SendOrder\CustomerBillingData;
use ClearSale\XmlEntity\SendOrder\CustomerShippingData;
use ClearSale\XmlEntity\SendOrder\FingerPrint;
use ClearSale\XmlEntity\SendOrder\HotelReservation;
use ClearSale\XmlEntity\SendOrder\Item;
use ClearSale\XmlEntity\SendOrder\Order;
use ClearSale\XmlEntity\SendOrder\Passenger;
use ClearSale\XmlEntity\SendOrder\Payment;
use ClearSale\XmlEntity\SendOrder\Phone;

try {
    // Dados da Integração com a ClearSale
    $entityCode = '<CLEARSALE_ENTITY_CODE>';
    $environment = new Sandbox($entityCode);

    // Dados do Pedido
    $fingerPrint = new FingerPrint(createSessionId());
    $orderId = createOrderId();
    $date = new \DateTime();
    $email = 'cliente@clearsale.com.br';
    $totalItems = 10.0;
    $totalOrder = 17.5;
    $quantityInstallments = 1;
    $ip = '127.0.0.1';
    $origin = 'WEB';
    $customerBillingData = createCustomerBillingData();
    $customerShippingData = createCustomerShippingData();
    $item = Item::create(1, 'Adaptador USB', 10.0, 1);
    $payment = Payment::create(Payment::BOLETO_BANCARIO, new \DateTime(), 17.5);

    $passenger = Passenger::create('Fulano da Silva', Passenger::DOCUMENT_TYPE_CPF, '63165236372');
    $connection = createConnection();
    $hotelReservation = createHotelReservation();

    // Criar Pedido
    $order = Order::createAirlineTicketOrder(
        $fingerPrint,
        $orderId,
        $date,
        $email,
        $totalItems,
        $totalOrder,
        $quantityInstallments,
        $ip,
        $origin,
        $customerBillingData,
        $customerShippingData,
        $payment,
        $item,
        $passenger,
        $connection,
        $hotelReservation
    );

    // Enviar pedido para análise
    $clearSale = new ClearSaleAnalysis($environment);
    $response = $clearSale->analysis($order);

    // Resultado da análise
    switch ($response)
    {
        case ClearSaleAnalysis::APROVADO:
            // Análise aprovou a cobrança, realizar o pagamento

            echo 'Aprovado' . PHP_EOL;

            break;
        case ClearSaleAnalysis::REPROVADO:
            // Análise não aprovou a cobrança

            echo 'Reprovado' . PHP_EOL;

            break;
        case ClearSaleAnalysis::AGUARDANDO_APROVACAO:
            // Análise pendente de aprovação manual

            echo 'Aguardando aprovação manual' . PHP_EOL;

            break;
    }
} catch (Exception $e) {
    // Erro genérico da análise
    echo $e->getMessage();
}

function createOrderId()
{
    return sprintf('TEST-%s', createSessionId());
}

function createSessionId()
{
    return md5(uniqid(rand(), true));
}

function createCustomerBillingData()
{
    $id = '1';
    $legalDocument = '63165236372';
    $name = 'Fulano da Silva';
    $address = createAddress();
    $phone = Phone::create(Phone::COMERCIAL, '11', '37288788');
    $birthDate = new \DateTime('1980-01-01');

    return CustomerBillingData::create(
        $id,
        AbstractCustomer::TYPE_PESSOA_FISICA,
        $legalDocument,
        $name,
        $address,
        $phone,
        $birthDate
    );
}

function createCustomerShippingData()
{
    $id = '1';
    $legalDocument = '63165236372';
    $name = 'Fulano da Silva';
    $address = createAddress();
    $phone = Phone::create(Phone::COMERCIAL, '11', '37288788');

    return CustomerShippingData::create(
        $id,
        AbstractCustomer::TYPE_PESSOA_FISICA,
        $legalDocument,
        $name,
        $address,
        $phone
    );
}

function createAddress()
{
    $street = 'Rua José de Oliveira Coutinho';
    $number = 151;
    $county = 'Barra Funda';
    $country = 'Brasil';
    $city = 'São Paulo';
    $state = 'SP';
    $zip = '01144020';

    return Address::create($street, $number, $county, $country, $city, $state, $zip);
}

function createConnection()
{
    $company = 'TAM';
    $flightNumber = '3356';
    $flightDate = new \DateTime('2015-09-14 11:55:00');
    $class = 'Econômica';
    $from = 'GRU';
    $to = 'JPA';
    $departureDate = new \DateTime('2015-09-14 11:55:00');
    $arrivalDate = new \DateTime('2015-09-14 15:33:00');

    return Connection::create(
        $company,
        $flightNumber,
        $flightDate,
        $class,
        $from,
        $to,
        $departureDate,
        $arrivalDate
    );
}

function createHotelReservation()
{
    $hotel = 'Hotel Beira Mar';
    $city = 'João Pessoa';
    $state = 'Paraíba';
    $country = 'Brasil';
    $reservationDate = new \DateTime('2015-07-01 15:30:00');
    $reservationExpirationDate = new \DateTime('2015-07-15 00:00:00');
    $checkInDate = new \DateTime('2015-09-14 14:00:00');
    $checkOutDate = new \DateTime('2015-09-21 12:00:00');

    return HotelReservation::create(
        $hotel,
        $city,
        $state,
        $country,
        $reservationDate,
        $reservationExpirationDate,
        $checkInDate,
        $checkOutDate
    );
}


text:
is a complete rewrite of easeljs in typescript. Plus adding a lot of stuff that easeljs does not support.

This version is still in its BETA stage.

## examples

#### How to view the examples?
Go to the root of this project and run "npm install -g http-server"
open the browser and go to localhost:8080 or what http-server says its running on
and go to localhost:8080/examples


text:
package pt.ist.registofatura;

import static javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY;

import java.util.Map;

import javax.xml.registry.JAXRException;
import javax.xml.ws.BindingProvider;

import pt.registofatura.ws.RegistoFaturaPortType;
import pt.registofatura.ws.RegistoFaturaService;
import registofatura.ws.uddi.UDDINaming;

public class RegistoFatura extends
        RegistoFaturaAbs {

    /**
     * Instancia um serviço RegistoFatura. {@link RegistoFaturaAbs},
     * {@link RegistoFaturaPortType}, {@link RegistoFaturaLocal},
     * {@link RegistoFaturaRemote}.
     */
    public RegistoFatura() {
        super();
        System.out.println("nova instancia de registoFatura...");
        setLocal();
    }

    public void setRemote() {
        System.out.println("setting as remote...");
        String uddiURL = "http://localhost:8081";
        String nome = "RegistoFatura";
        UDDINaming uddiNaming = null;
        String endpointAddress = null;
        try {
            uddiNaming = new UDDINaming(uddiURL);
            System.out.println("Set uddiNaming.");
        } catch (JAXRException e) {
            System.out
                    .println("--------\nNão conseguiu iniciar o UddiNaming:  A usar a versão local.");
            e.printStackTrace();
            return;
        }

        System.out.printf("Contacting UDDI at %s%n", uddiURL);

        System.out.printf("Looking for '%s'%n", nome);
        try {
            endpointAddress = uddiNaming.lookup(nome);
            System.out.println("endpoint is '" + endpointAddress + "'");
        } catch (JAXRException e) {
            System.out.println("looking up has failed. exception message: " + e.getMessage());
            e.printStackTrace();
        }

        if (endpointAddress == null) {
            System.out.println("Not found!");
            return;
        } else {
            System.out.printf("Found %s%n", endpointAddress);
        }

        RegistoFaturaService service = new RegistoFaturaService();
        RegistoFaturaPortType port = service.getRegistoFaturaPort();

        System.out.println("Setting endpoint address ...");
        BindingProvider bindingProvider = (BindingProvider) port;
        Map<String, Object> requestContext = bindingProvider.getRequestContext();
        requestContext.put(ENDPOINT_ADDRESS_PROPERTY, endpointAddress);

        System.out.println("setting remote port...");
        setImplementacao(port);

    }

    public void setLocal() {
        System.out.println("setting as local");
        setImplementacao(new RegistoFaturaLocal());
    }

}


text:
<!DOCTYPE html>

  <title>TimeItem sign in</title>

  <link rel="stylesheet" href="assets/css/reset.css" />
  <link rel="stylesheet" href="assets/css/supersized.css" />
  <link rel="stylesheet" href="assets/css/style.css" />

Sign in

    <form action="/login" method="post">
        <input type="hidden" name="redirectUrl" id="redirectUrl">
        <input type="text" name="username" class="username" placeholder="Username">
        <input type="password" name="password" class="password" placeholder="Password">
        <button type="submit" onclick="loginSubmit()">Sign me in</button>

+

    </form>

No account ?

            register


text:
#pragma once
#include <aws/codedeploy/CodeDeploy_EXPORTS.h>
#include <aws/codedeploy/CodeDeployRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CodeDeploy
{
namespace Model
{

  /**
   *
Represents the input of a DeleteApplication
   * operation.

See Also:
   AWS
   * API Reference

   */
  class AWS_CODEDEPLOY_API DeleteApplicationRequest : public CodeDeployRequest
  {
  public:
    DeleteApplicationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DeleteApplication"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline const Aws::String& GetApplicationName() const{ return m_applicationName; }

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline bool ApplicationNameHasBeenSet() const { return m_applicationNameHasBeenSet; }

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline void SetApplicationName(const Aws::String& value) { m_applicationNameHasBeenSet = true; m_applicationName = value; }

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline void SetApplicationName(Aws::String&& value) { m_applicationNameHasBeenSet = true; m_applicationName = std::move(value); }

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline void SetApplicationName(const char* value) { m_applicationNameHasBeenSet = true; m_applicationName.assign(value); }

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline DeleteApplicationRequest& WithApplicationName(const Aws::String& value) { SetApplicationName(value); return *this;}

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline DeleteApplicationRequest& WithApplicationName(Aws::String&& value) { SetApplicationName(std::move(value)); return *this;}

    /**
     *
The name of an CodeDeploy application associated with the IAM user or Amazon
     * Web Services account.

     */
    inline DeleteApplicationRequest& WithApplicationName(const char* value) { SetApplicationName(value); return *this;}

  private:

    Aws::String m_applicationName;
    bool m_applicationNameHasBeenSet = false;
  };

} // namespace Model
} // namespace CodeDeploy
} // namespace Aws


text:
"""
Root url's map for application
"""
from django.conf.urls import *

from po_projects.views.projects import ProjectIndex, ProjectCreateView, ProjectDetails, ProjectExportView, ProjectUpdate
from po_projects.views.catalogs import CatalogDetails, CatalogMessagesExportView, CatalogMessagesFormView

urlpatterns = patterns('',
    url(r'^$', ProjectIndex.as_view(), name='project-index'),

    url(r'^create/$', ProjectCreateView.as_view(), name='project-create'),
    url(r'^(?P<slug>[-\w]+)/$', ProjectDetails.as_view(), name='project-details'),
    url(r'^(?P<slug>[-\w]+)/update/$', ProjectUpdate.as_view(), name='project-update'),
    url(r'^(?P<slug>[-\w]+)/download/$', ProjectExportView.as_view(), name='project-download'),

    url(r'^(?P<slug>[-\w]+)/(?P<locale>[-\w]+)/$', CatalogDetails.as_view(), name='catalog-details'),
    url(r'^(?P<slug>[-\w]+)/(?P<locale>[-\w]+)/edit/$', CatalogMessagesFormView.as_view(), name='catalog-messages-edit'),
    url(r'^(?P<slug>[-\w]+)/(?P<locale>[-\w]+)/download/$', CatalogMessagesExportView.as_view(), name='catalog-messages-download'),
)

"""
Urls map for API with Django REST Framework if installed

TODO:

* project update from a POT file
* get project catalogs tarball

"""
try:
    from rest_framework.urlpatterns import format_suffix_patterns
except ImportError:
    pass
else:
    from po_projects.rest import views

    rest_urlpatterns = format_suffix_patterns(patterns('po_projects.rest.views',
        url(r'^rest/$', 'api_root'),
        url(r'^rest/projects/$', views.ProjectList.as_view(), name='api-project-list'),
        url(r'^rest/projects/current/(?P<slug>[-\w]+)/$', views.ProjectCurrentDetail.as_view(), name='api-project-detail'),
        url(r'^rest/projects/current/(?P<slug>[-\w]+)/tarball/$', views.ProjectArchive.as_view(), name='api-project-archive'),
        #url(r'^rest/projects/current/(?P<slug>[-\w]+)/pot-update/$', views.ProjectCurrentDetail.as_view(), name='api-project-pot-update'),
        url(r'^rest/projects/version/(?P<pk>\d+)/$', views.ProjectVersionDetail.as_view(), name='api-project-version-detail'),
    ))

    urlpatterns = rest_urlpatterns + urlpatterns


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.deephacks.tools4j.support.conversion;

/**
 * This is the fallback string converter that simply does a toString on the
 * provided object.
 *
 * Works fine for Number, Boolean, Enums and all other values that have a
 * toString that represent their real values in a serialized form.
 */
public class ObjectToStringConverter implements Converter<Object, String> {

    @Override
    public String convert(Object source, Class<? extends String> specificType) {
        return (source != null ? source.toString() : null);
    }

}


text:
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using CheckboxField = RazorViewsForMarketers.Models.Fields.CheckboxField;

namespace RazorViewsForMarketers.Core.FieldRenderers
{
    public class CheckBoxInitializer : FieldInitializerBase<CheckboxField>
    {
        public CheckBoxInitializer(Item fieldItem) : base(fieldItem) { }

        public override void PopulateParameters(Field field, CheckboxField model)
        {

        }

        public override void PopulateLocalizedParameters(Field field, CheckboxField model)
        {

        }
    }
}


text:
package com.thetonyk.UHC.Commands;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.thetonyk.UHC.Main;
import com.thetonyk.UHC.Utils.GameUtils;

public class SpecchatCommand implements CommandExecutor {

	public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

		Player player = Bukkit.getPlayer(sender.getName());

		if (!GameUtils.getSpectate(player.getUniqueId())) {

			sender.sendMessage(Main.NO_PERMS);
			return true;

		}

		if (args.length < 1) {

			sender.sendMessage(Main.PREFIX + "Usage: /" + label + " <message>");
			return true;
		}

		StringBuilder message = new StringBuilder();

		for (int i = 0; i < args.length; i++) {

			message.append(args[i] + " ");

		}

		String chat = "§6SpecChat §8| §7§o" + player.getName() + " §8⫸ §f" + message;

		for (Player online : Bukkit.getOnlinePlayers()) {

			if (!GameUtils.getSpectate(online.getUniqueId())) continue;

			online.sendMessage(chat);

		}
		return true;

	}

}


text:
import sys
import pymongo

def connect(uri):
    client = pymongo.MongoClient(uri)
    db = client.get_default_database()
    return db

def insert(db, documentName, dataArray):
    document = db[documentName]
    val = document.insert(dataArray)
    if (val):
        print("Successed!")
    else:
        print("Something went wrong.")

def read(db):
    try:
        data_column = db.data1.find()
        for d in data_column:
            print d
    except Exception, e:
        print str(e)


text:
struct LevelObject
{
  std::string Type;
  float PositionX;
  float Time;
};

#endif


text:
package org.apache.nifi.web.api.dto;

import java.util.List;

import javax.xml.bind.annotation.XmlType;

import com.wordnik.swagger.annotations.ApiModelProperty;

@XmlType(name = "counters")
public class CountersDTO {
    private CountersSnapshotDTO aggregateSnapshot;
    private List<NodeCountersSnapshotDTO> nodeSnapshots;

    @ApiModelProperty("A Counters snapshot that represents the aggregate values of all nodes in the cluster. If the NiFi instance is "
        + "a standalone instance, rather than a cluster, this represents the stats of the single instance.")
    public CountersSnapshotDTO getAggregateSnapshot() {
        return aggregateSnapshot;
    }

    public void setAggregateSnapshot(CountersSnapshotDTO aggregateSnapshot) {
        this.aggregateSnapshot = aggregateSnapshot;
    }

    @ApiModelProperty("A Counters snapshot for each node in the cluster. If the NiFi instance is a standalone instance, rather than "
        + "a cluster, this may be null.")
    public List<NodeCountersSnapshotDTO> getNodeSnapshots() {
        return nodeSnapshots;
    }

    public void setNodeSnapshots(List<NodeCountersSnapshotDTO> nodeSnapshots) {
        this.nodeSnapshots = nodeSnapshots;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="DetailsTheme" parent="AppTheme">
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:statusBarColor">@color/semitransparent</item>
    </style>
</resources>


text:
if (localStorage.lang === "dk")
  {
   document.body.className='dk';
  }
else if (localStorage.lang === "en")
  {
   document.body.className='en';
  }


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Calendar About Nothing</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />


text:
var raceCounter = -1;
(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/index.php/Races/getRaceCountJSON/",
            success: function(data) {
                if(raceCounter == -1){
                    raceCounter = parseInt(data);
                }
                else{
                    if(parseInt(data)>raceCounter){
                        raceCounter = parseInt(data);
                        alert("Lisati uus võistlus!");
                    }
                }
            },
            dataType: "json",
            complete: poll
        });
    }, 5000);
}) ();

$("#activeRace").change(function() {
    var selectedMark = $(activeRace).val();
    if (selectedMark != "") {
        console.log(selectedMark);
        $.ajax({
            type: "GET",
            url: "/index.php/Addresults/getRacesJSON/"+selectedMark,
            dataType: "json",
            success: function(data) {
                $("#raceClasses").empty();
                var dataNodes = data.map(function(item) {
                    return "<option value='" + item.id + "'>" + item.agegroup + "</option>";
                });

                $("#raceClasses").append(dataNodes);
            },
            error: function(data){
                $("#raceClasses").empty();
            }
        });
    }
});

var start = 5; // Start from
var amount = 5; // Load step
var pageNr = 2; // Shown in the URL, Initially added on "load_more_button" click

function syncRacesToURL(){
    var currentURL = window.location.href;
    if(currentURL.indexOf('page_nr')> -1){
        var currentPage = parseInt(currentURL.split("#")[1].split('=')[1]);

        pageNr = currentPage + 1; // For history.pushState
        var newAmount = (currentPage -1) * 5; // For page 3, We need additional 10 Items (not 15)

        loadRaces(start, newAmount, false);

        start = pageNr * 5 - start;

    }

}
syncRacesToURL();

function noMoreResults() {
    $('#race-result-container').append(
        '
 Rohkem tulemusi kuvamiseks pole.
'
    );
    $('#load_more_button').hide();

}

function loadRaces(startFrom, amount, incrementPages) {
    return $.ajax({
        type: "GET",
        url: '/index.php/Races/loadMoreRaces/'+startFrom+'/'+amount,
        dataType: 'json',
        success: function(data) {

            if(incrementPages) {
                pageNr = pageNr +1;
                start = start + 5;
            }

            $('#load-more-loader').addClass('hidden');

            if(data.length === 0) {
                return noMoreResults();
            }
            history.pushState({}, "page nr", "#page_nr=" + (pageNr-1));
            var listNodes = data.map(function(item) {
                return '
'
                    + item.name + ' ' + item.date +
                    '
';
            });
            $('#race-result-container .list-group').append(listNodes);
        },
        error: function(data){
            alert("bad network");
        }
    });
}

$('#load_more_button').click(function() {

    $('#load-more-loader').removeClass('hidden');

    loadRaces(start, amount, true);

});

function openRace(element) {
    window.location.href = 'http://biathlon.cs.ut.ee/index.php/raceview/showdata/' + element.getAttribute("title");
}


text:
Enable Vim-style modeline in Atom.

## Supported options

- `expandtab` / `noexpandtab`
- `fileencoding`
- `fileformat`
- `filetype`
- `spell` / `nospell`
- `tabstop`

## Example

### Valid Vim-style modeline

```coffeescript
# vim:set expandtab tabstop=2 fenc=utf-8 ff=unix ft=coffee:
```

### Atom-specific modeline

```coffeescript
# atom:set useSoftTabs tabLength=2 encoding=utf-8 lineEnding=lf grammar=coffee:
```

## Atom-specific modeline

- `useSoftTabs` -> `expandtab`
- `encoding` -> `fileencoding`
- `lineEnding` -> `fileformat`
- `grammar` -> `filetype`
- `tabLength` -> `tabstop`

## Configuring filetype

You can add more filetype for a given language scope.
To do this, add the settings to the `~/.atom/config.cson` in the format below.

```coffeescript
'vim-modeline-filetypes':
  # append scopeName
  'as': [
    'source.actionscript.3'
  ]
  # override scopeName
  'markdown': 'text.md'
```

## vim-modeline Event Handler

This package can use the event handler using "Service API".

- onDidParse
- onDidSetLineEnding
- onDidSetFileType
- onDidSetEncoding
- onDidSetSoftTabs
- onDidSetTabLength

eg: get parse result in `init.coffee`.

```coffeescript
atom.packages.serviceHub.consume "vim-modeline-event-handler", "^1.0.0", (handler) ->
  handler.onDidParse ({editor, options}) ->
    console.log editor
    console.log options
    someFunction(options)
```

## Conflict issue

If you use [auto-encoding](https://atom.io/packages/auto-encoding) package, file encoding doesn't match the modeline.
If you want use vim-modeline parse result, please invoke 'vim-modeline:detect' command after open TextEditor.

## TODO

- [ ] `softtabstop` support
- [ ] `shiftwidth` support


text:
#region Copyright and License
// Copyright 2010..2015 Alexander Reinert
//
// This file is part of the ARSoft.Tools.Net - C# DNS client/server and SPF Library (http://arsofttoolsnet.codeplex.com/)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;

namespace MailTester.ARSoft.Tools.Net.Dns.DnsRecord
{
	/// <summary>
	///   <para>Host identity protocol</para>
	///   <para>
	///     Defined in
	///     <see cref="!:http://tools.ietf.org/html/rfc5205">RFC 5205</see>
	///   </para>
	/// </summary>
	public class HipRecord : DnsRecordBase
	{
		/// <summary>
		///   Algorithm of the key
		/// </summary>
		public IpSecKeyRecord.IpSecAlgorithm Algorithm { get; private set; }

		/// <summary>
		///   Host identity tag
		/// </summary>
		public byte[] Hit { get; private set; }

		/// <summary>
		///   Binary data of the public key
		/// </summary>
		public byte[] PublicKey { get; private set; }

		/// <summary>
		///   Possible rendezvous servers
		/// </summary>
		public List<string> RendezvousServers { get; private set; }

		internal HipRecord() {}

		/// <summary>
		///   Creates a new instace of the HipRecord class
		/// </summary>
		/// <param name="name"> Name of the record </param>
		/// <param name="timeToLive"> Seconds the record should be cached at most </param>
		/// <param name="algorithm"> Algorithm of the key </param>
		/// <param name="hit"> Host identity tag </param>
		/// <param name="publicKey"> Binary data of the public key </param>
		/// <param name="rendezvousServers"> Possible rendezvous servers </param>
		public HipRecord(string name, int timeToLive, IpSecKeyRecord.IpSecAlgorithm algorithm, byte[] hit, byte[] publicKey, List<string> rendezvousServers)
			: base(name, RecordType.Hip, RecordClass.INet, timeToLive)
		{
			Algorithm = algorithm;
			Hit = hit ?? new byte[] { };
			PublicKey = publicKey ?? new byte[] { };
			RendezvousServers = rendezvousServers ?? new List<string>();
		}

		internal override void ParseRecordData(byte[] resultData, int currentPosition, int length)
		{
			int endPosition = currentPosition + length;

			int hitLength = resultData[currentPosition++];
			Algorithm = (IpSecKeyRecord.IpSecAlgorithm) resultData[currentPosition++];
			int publicKeyLength = DnsMessageBase.ParseUShort(resultData, ref currentPosition);
			Hit = DnsMessageBase.ParseByteData(resultData, ref currentPosition, hitLength);
			PublicKey = DnsMessageBase.ParseByteData(resultData, ref currentPosition, publicKeyLength);
			RendezvousServers = new List<string>();
			while (currentPosition < endPosition)
			{
				RendezvousServers.Add(DnsMessageBase.ParseDomainName(resultData, ref currentPosition));
			}
		}

		internal override void ParseRecordData(string origin, string[] stringRepresentation)
		{
			if (stringRepresentation.Length < 3)
				throw new FormatException();

			Algorithm = (IpSecKeyRecord.IpSecAlgorithm) Byte.Parse(stringRepresentation[0]);
			Hit = stringRepresentation[1].FromBase16String();
			PublicKey = stringRepresentation[2].FromBase64String();
			RendezvousServers = stringRepresentation.Skip(3).ToList();
		}

		internal override string RecordDataToString()
		{
			return (byte) Algorithm
			       + " " + Hit.ToBase16String()
			       + " " + PublicKey.ToBase64String()
			       + String.Join("", RendezvousServers.Select(s => " " + s + ".").ToArray());
		}

		protected internal override int MaximumRecordDataLength
		{
			get
			{
				int res = 4;
				res += Hit.Length;
				res += PublicKey.Length;
				res += RendezvousServers.Sum(s => s.Length + 2);
				return res;
			}
		}

		protected internal override void EncodeRecordData(byte[] messageData, int offset, ref int currentPosition, Dictionary<string, ushort> domainNames)
		{
			messageData[currentPosition++] = (byte) Hit.Length;
			messageData[currentPosition++] = (byte) Algorithm;
			DnsMessageBase.EncodeUShort(messageData, ref currentPosition, (ushort) PublicKey.Length);
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, Hit);
			DnsMessageBase.EncodeByteArray(messageData, ref currentPosition, PublicKey);
			foreach (string server in RendezvousServers)
			{
				DnsMessageBase.EncodeDomainName(messageData, offset, ref currentPosition, server, false, domainNames);
			}
		}
	}
}


text:
FROM centos:7
SHELL ["/bin/bash", "-l", "-c"]

ENV SCALARM_HOME /scalarm

RUN yum install -y curl which git

RUN gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
RUN curl -sSL https://get.rvm.io | bash -s stable
RUN source /etc/profile.d/rvm.sh

RUN rvm requirements
RUN rvm install 2.3
RUN gem install bundler --no-ri --no-rdoc

ADD . $SCALARM_HOME

WORKDIR $SCALARM_HOME

EXPOSE 3002

RUN bundle config git.allow_insecure true
RUN bundle install

CMD /bin/bash -c "rake service:start"


text:
import { render } from 'react-dom';
import routes from './routes/router';

routes.routeWindow(window)[0].then(component=>{
    render(component, document.getElementById('root'));
});


text:
package de.tu_darmstadt.sport.fvf.model;

import java.util.ArrayList;
import java.util.List;

import org.sormula.annotation.Column;
import org.sormula.annotation.Row;
import org.sormula.annotation.Transient;
import org.sormula.annotation.Where;
import org.sormula.annotation.cascade.OneToManyCascade;
import org.sormula.annotation.cascade.SelectCascade;

import de.tu_darmstadt.sport.fvf.helper.CollectionHelper;
import de.tu_darmstadt.sport.fvf.model.map.FrequencyCycleMap;
import de.tu_darmstadt.sport.fvf.model.map.TestMap;

@Where(name="test",fieldNames="testId")
@Row(tableName="frequency_cycle")
public class FrequencyCycle extends Model {

	@Column(identity=true)
	private int id;
	private double frequency;

	@Column(name="test_id")
	private int testId;

	@Transient
	private Test test;

	@Transient
	private int errors = -1;

	@OneToManyCascade(targetClass=Measurement.class,
			selects=@SelectCascade(sourceParameterFieldNames="id",targetWhereName="frequencyCycle"))
	private List<Measurement> measurements;

	public FrequencyCycle() {
		super(new FrequencyCycleMap());
		measurements = new ArrayList<Measurement>();
	}

	public void reset() {
		measurements.clear();
	}

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(int id) {
		propertyChangeSupport.firePropertyChange("id", this.id, this.id = id);
	}

	/**
	 * @return the frequency
	 */
	public double getFrequency() {
		return frequency;
	}

	/**
	 * @param frequency the frequency to set
	 */
	public void setFrequency(double frequency) {
		propertyChangeSupport.firePropertyChange("frequency", this.frequency, this.frequency = frequency);
	}

	/**
	 * @return the testId
	 */
	public int getTestId() {
		return testId;
	}

	/**
	 * @param testId the testId to set
	 */
	public void setTestId(int testId) {
		propertyChangeSupport.firePropertyChange("testId", this.testId, this.testId = testId);
	}

	/**
	 * @return the test
	 */
	public Test getTest() {
		if (test == null) {
			test = TestMap.getById(testId);
		}
		return test;
	}

	/**
	 * @param test the test to set
	 */
	public void setTest(Test test) {
		this.test = test;
		if (test == null) {
			setTestId(-1);
		} else {
			setTestId(test.getId());
		}
	}

	/**
	 * @return the measurements
	 */
	public List<Measurement> getMeasurements() {
		return measurements;
	}

	/**
	 * @param measurements the measurements to set
	 */
	public void setMeasurements(List<Measurement> measurements) {
		propertyChangeSupport.firePropertyChange("measurements", this.measurements, this.measurements = measurements);
		for (Measurement measurement : measurements) {
			measurement.setFrequencyCycle(this);
		}
	}

	public void addMeasurement(Measurement measurement) {
		List<Measurement> old = new ArrayList<Measurement>();
		CollectionHelper.copy(old, measurements);
		measurement.setFrequencyCycle(this);
		measurements.add(measurement);
		propertyChangeSupport.firePropertyChange("measurements", old, measurements);
	}

	public void removeMeasurement(Measurement measurement) {
		List<Measurement> old = new ArrayList<Measurement>();
		CollectionHelper.copy(old, measurements);
		measurement.setFrequencyCycle(null);
		measurements.remove(measurement);
		propertyChangeSupport.firePropertyChange("measurements", old, measurements);
	}

	public int getErrors() {
		if (errors == -1) {
			errors = 0;
			for (Measurement m : measurements) {
				if (m.isError()) {
					errors++;
				}
			}
		}
		return errors;
	}

	/* Operations */
	public void save() {
		super.save();
		for (Measurement m : measurements) {
			m.setFrequencyCycleId(id);
			m.save();
		}
	}
}