text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import meals.models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Meal',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('photo', models.ImageField(upload_to='', verbose_name=meals.models.upload_directory_path)),
                ('date_created', models.DateField(auto_now_add=True, verbose_name='date created')),
                ('title', models.CharField(max_length=128, verbose_name='Title')),
                ('member', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='meal', related_query_name='meal', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Ratting',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('like', models.BooleanField()),
                ('meal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ratting', to='meals.Meal')),
                ('memeber', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ratting', to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


text:
alias reload="exec $SHELL -l"
alias h="history 0 | grep"

# =================================
# git
alias gs="git status"
alias gd="git diff"
alias gds="git diff --staged"

# =================================
# files
alias wget='wget -c'

function isavailable() {
  type "$1" > /dev/null
}

function ll() {
  local dir=${1:-"."}

  if isavailable lsd; then
    lsd -lai --long
  else
    ls -laih $dir
  fi
}

if isavailable exa; then
  alias ll="exa  --long --icons -T -L 1"
  alias llT="exa --long --icons -T -L 3"
fi

# =================================
# autojump to z
alias j="z"

# =================================
# Ruby
alias be="bundle exec"

# =================================
# tmux aliases
alias tml="tmux list-sessions"
alias tma="tmux -2 attach-session -t"
alias tmk="tmux kill-session -t"
alias tms="tmuxinator start"
alias osx="reattach-to-user-namespace"

# =================================
# frum aliases
alias fminit='eval "$(frum init)"'
alias fml='frum local'
alias fmu="frum uninstall"
alias fmv="frum versions"

# =================================
# ruby/rails
alias r="bundle exec rails"

# =================================
# vim aliases
alias svim="MYVIMRC=~/.vimrc.simple vim -u ~/.vimrc.simple"

# =================================
# For cleaner desktop
alias screencast="defaults write com.apple.finder CreateDesktop false; killall Finder"
alias unscreencast="defaults write com.apple.finder CreateDesktop true; killall Finder"

# =================================
# Functions
# =================================
function hasCmd() {
  local CMD=$1

  which $CMD >/dev/null && [[ "$(which $CMD | grep -ic "not found")" -eq "0" ]]
}

function tmlocal() {
  if hasCmd "tmuxinator"; then
    gem install tmuxinator
  fi
  tmuxinator local
}

# =========================
# FZF Searching
[ -f "$HOME/.fzf.zsh" ] && source "$HOME/.fzf.zsh"

export FZF_TMUX_HEIGHT="40%"
export FZF_DEFAULT_OPTS="--height 30% --layout=reverse"

if isavailable ag; then
  export FZF_DEFAULT_COMMAND='ag -U --hidden -g "" --ignore .git --ignore tmp --ignore "*.png" --ignore "*.jpg" --ignore "node_modules" --ignore .bin --ignore .DS_Store --ignore "*.gif"'
fi

# =========================
# Autojumping with z
source_if_exists "$(brew --prefix)/etc/profile.d/z.sh"

# =========================
# phpbrew
if [ -f "$HOME/.phpbrew/bashrc" ]; then
  source $HOME/.phpbrew/bashrc
fi

# =========================
# direnv
if isavailable direnv; then
  eval "$(direnv hook zsh)"
fi

if isavailable frum; then
  eval "$(frum init)"
fi

# =================================
# chezmoi
alias dote="chezmoi edit"
alias dotd="chezmoi diff"

# =========================
# asdf
if [ -f "$HOME/.asdf/asdf.sh" ]; then
  source "$HOME/.asdf/asdf.sh"

  # append completions to fpath
  fpath=("${ASDF_DIR}/completions" $fpath)

  # initialise completions with ZSH's compinit
  autoload -Uz compinit
  compinit
fi

# =================================
# nvm
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}"  ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh"  ] && source "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion"  ] && source "$NVM_DIR/bash_completion" # This loads nvm completion

# =========================
# starship prompt
if isavailable starship; then
  eval "$(starship init zsh)"
fi

# =========================
# Local config
if [ -f "$HOME/.zshrc.local" ]; then
  source $HOME/.zshrc.local
fi

if hasCmd "z"; then
  alias j="z"
fi

redpajama_set_name: RedPajamaGithub


text:
/* eslint-env jest */
/* @flow */

import { compose, callMiddleware } from '../index';

describe('compose', () => {
  const defaultRequest = {};
  const defaultResponse = {};
  const defaultContinueFn = () => Promise.resolve(defaultResponse);

  describe('empty brigade', () => {
    const emptyBrigade = [];

    it('should propagate the return value of calling next', async () => {
      const expectedValue = { result: 'hello' };
      const nextFn = () => Promise.resolve(expectedValue);

      const result = await compose(emptyBrigade)(defaultRequest, nextFn, defaultContinueFn);
      expect(result).toBe(expectedValue);
    });

    it('should catch an exception in next', async () => {
      const expectedMessage = 'test';
      const nextFn = () => {
        throw new Error(expectedMessage);
      };

      expect.assertions(2);
      try {
        await compose(emptyBrigade)(defaultRequest, nextFn, defaultContinueFn);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toBe(expectedMessage);
      }
    });

    it('should catch a rejected promise in next', async () => {
      const expectedMessage = 'hello';
      const nextFn = () => Promise.reject(new Error(expectedMessage));

      expect.assertions(2);
      try {
        await compose(emptyBrigade)(defaultRequest, nextFn, defaultContinueFn);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toBe(expectedMessage);
      }
    });

    it('should only accept functions for next', async () => {
      const notAFunction = {};
      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await compose(emptyBrigade)(defaultRequest, notAFunction, defaultContinueFn);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be a function/);
      }
    });

    it('should only accept functions for terminate', async () => {
      const notAFunction = {};
      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await compose(emptyBrigade)(defaultRequest, defaultContinueFn, notAFunction);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be a function/);
      }
    });
  });

  describe('parameters', () => {
    it('should only accept an array of middleware', async () => {
      const notAnArray = null;
      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await compose(notAnArray);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be an array/);
      }
    });

    it('should only accept middleware as functions', async () => {
      const notMiddleware = {};
      expect.assertions(2);
      try {
        // $FlowFixMe: override type violation for test case
        await compose([notMiddleware]);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be composed of functions/);
      }
    });
  });

  describe('deep brigade', () => {
    const deepRequest = {
      receivedCalls: []
    };
    const deepBrigade = [
      async (request, next) => {
        request.receivedCalls.push(1);
        const result = await next();
        request.receivedCalls.push(6);
        return result;
      },
      async (request, next) => {
        request.receivedCalls.push(2);
        const result = await next();
        request.receivedCalls.push(5);
        return result;
      },
      async (request, next) => {
        request.receivedCalls.push(3);
        const result = await next();
        request.receivedCalls.push(4);
        return result;
      }
    ];

    beforeEach(() => {
      deepRequest.receivedCalls = [];
    });

    it('should call middleware brigade in the right order', async () => {
      await compose(deepBrigade)(deepRequest, defaultContinueFn, defaultContinueFn);
      expect(deepRequest.receivedCalls).toEqual([1, 2, 3, 4, 5, 6]);
    });

    it('should be able to be called twice', async () => {
      const brigade = compose(deepBrigade);
      await brigade(deepRequest, defaultContinueFn, defaultContinueFn);
      expect(deepRequest.receivedCalls).toEqual([1, 2, 3, 4, 5, 6]);
      deepRequest.receivedCalls = [];
      await brigade(deepRequest, defaultContinueFn, defaultContinueFn);
      expect(deepRequest.receivedCalls).toEqual([1, 2, 3, 4, 5, 6]);
    });

    it('should propagate the value of calling next', async () => {
      const exepctedValue = { result: 'hello' };
      const nextFn = () => Promise.resolve(exepctedValue);
      const brigade = compose(deepBrigade);
      const result = await brigade(deepRequest, nextFn, defaultContinueFn);
      expect(result).toBe(exepctedValue);
    });

    describe('with terminate at the end', () => {
      const brigadeWithTerminate = deepBrigade.slice(0);
      brigadeWithTerminate.push((request, next, terminate) => terminate());

      it('should propagate the value of calling terminate', async () => {
        const exepctedValue = { result: 'hello' };
        const terminateFn = () => Promise.resolve(exepctedValue);
        const brigade = compose(brigadeWithTerminate);
        const result = await brigade(deepRequest, defaultContinueFn, terminateFn);
        expect(result).toBe(exepctedValue);
      });

      it('should catch an exception in terminate', async () => {
        const expectedMessage = 'hello';
        const terminateFn = () => {
          throw new Error(expectedMessage);
        };

        expect.assertions(2);
        try {
          const brigade = compose(brigadeWithTerminate);
          await brigade(deepRequest, defaultContinueFn, terminateFn);
        } catch (e) {
          expect(e).toBeInstanceOf(Error);
          expect(e.message).toBe(expectedMessage);
        }
      });

      it('should catch a rejected promise in terminate', async () => {
        const expectedMessage = 'hello';
        const terminateFn = () => Promise.reject(new Error(expectedMessage));

        expect.assertions(2);
        try {
          const brigade = compose(brigadeWithTerminate);
          await brigade(deepRequest, defaultContinueFn, terminateFn);
        } catch (e) {
          expect(e).toBeInstanceOf(Error);
          expect(e.message).toBe(expectedMessage);
        }
      });
    });
  });

  it('should throw if middleware does not return a promise', async () => {
    const notAPromise = 0;
    const middleware = [
      // $FlowFixMe: override violation for test case
      () => notAPromise
    ];

    expect.assertions(2);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/Promise was expected/);
    }
  });

  it('should keep the request across multiple middleware', () => {
    const originalRequest = {};

    const brigade = [];

    const middleware = async (receivedRequest, next) => {
      const result = await next();
      expect(receivedRequest).toBe(originalRequest);
      return result;
    };

    brigade.push(middleware);
    brigade.push(middleware);
    brigade.push(middleware);

    return compose(brigade)(originalRequest, defaultContinueFn, defaultContinueFn);
  });

  it('should reject on errors in middleware', async () => {
    const brigade = [];
    const sentintel = jest.fn();

    brigade.push(() => { throw new Error(); });

    await compose(brigade)(defaultRequest, defaultContinueFn, defaultContinueFn)
      .then(sentintel)
      .catch((err) => {
        expect(err).toBeInstanceOf(Error);
      });
    expect(sentintel).not.toHaveBeenCalled();
  });

  it('should not call next with middleware parameters', () => {
    const brigade = [];
    expect.assertions(3);
    return compose(brigade)(defaultRequest, (request, next, terminate) => {
      expect(request).toBe(undefined);
      expect(next).toBe(undefined);
      expect(terminate).toBe(undefined);
      return Promise.resolve(defaultResponse);
    }, defaultContinueFn);
  });

  it('should not call terminate with middleware parameters', () => {
    const brigade = [(context, next, terminate) => terminate()];
    expect.assertions(3);
    return compose(brigade)(defaultRequest, defaultContinueFn, (request, next, terminate) => {
      expect(request).toBe(undefined);
      expect(next).toBe(undefined);
      expect(terminate).toBe(undefined);
      return Promise.resolve(defaultResponse);
    });
  });

  it('should throw if terminate is called multiple times at the beginning of a brigade', async () => {
    const middleware = [
      function badDog(request, next, terminate) {
        terminate();
        return terminate();
      },
      (request, next) => next()
    ];

    expect.assertions(3);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its terminate function after the middleware brigade has been terminated/);
      expect(e.message).toMatch(/badDog/);
    }
  });

  it('should throw if next() is called multiple times at the beginning of a brigade', async () => {
    const middleware = [
      function badDog(request, next) {
        next();
        return next();
      },
      (request, next) => next()
    ];

    expect.assertions(3);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its next function after the middleware brigade has been terminated/);
      expect(e.message).toMatch(/badDog/);
    }
  });

  it('should throw if terminate is called multiple times at the end of a brigade', async () => {
    const middleware = [
      (request, next) => next(),
      function badDog(request, next, terminate) {
        terminate();
        return terminate();
      }
    ];

    expect.assertions(2);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its terminate function after the middleware brigade has been terminated/);
    }
  });

  it('should throw if next is called multiple times at the end of a brigade', async () => {
    const middleware = [
      (request, next) => next(),
      function badDog(request, next) {
        next();
        return next();
      }
    ];

    expect.assertions(3);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its next function after the middleware brigade has been terminated/);
      expect(e.message).toMatch(/badDog/);
    }
  });

  it('should throw if terminate is called after next', async () => {
    const middleware = [
      async function badDog(request, next, terminate) {
        next();
        return terminate();
      }
    ];

    expect.assertions(3);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its terminate function after the middleware brigade has been terminated/);
      expect(e.message).toMatch(/badDog/);
    }
  });

  it('should throw if next is called after terminate', async () => {
    const middleware = [
      // Flow should probably catch this
      async function badDog(request, next, terminate) {
        await terminate();
        await next();
      }
    ];

    expect.assertions(3);
    try {
      await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
    } catch (e) {
      expect(e).toBeInstanceOf(Error);
      expect(e.message).toMatch(/has called its next function after the middleware brigade has been terminated/);
      expect(e.message).toMatch(/badDog/);
    }
  });

  describe('middleware error message', () => {
    it('should identify middleware with an error', async () => {
      const middleware = [
        function badDog() {
          // $FlowFixMe: override violation for test case
          return 'woof';
        }
      ];

      expect.assertions(2);
      try {
        await compose(middleware)(defaultRequest, defaultContinueFn, defaultContinueFn);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/badDog/);
      }
    });
  });

  describe('callMiddleware', () => {
    const defaultMiddleware = async (request, next) => next();

    it('should work with a response object', async () => {
      const middleware = [
        async (request, next) => next()
      ];

      const expectedResponse = {};
      const result = await callMiddleware(compose(middleware), defaultRequest, expectedResponse);
      expect(result).toBe(expectedResponse);
    });

    it('should work with calculated response', async () => {
      const expectedResponse = {};
      const middleware = [
        async (request, next, terminate) => {
          await terminate();
          return expectedResponse;
        }
      ];

      const result = await callMiddleware(compose(middleware), defaultRequest);
      expect(result).toBe(expectedResponse);
    });

    it('should allow a rejected promise to be returned', async () => {
      const expectedMessage = 'hello';
      const middleware = [
        () => Promise.reject(new Error(expectedMessage))
      ];

      expect.assertions(2);
      try {
        await callMiddleware(compose(middleware), defaultRequest, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toBe(expectedMessage);
      }
    });

    it('should only accept middleware functions', async () => {
      const notAFunction = {};

      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await callMiddleware(notAFunction, defaultRequest, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be a function/);
      }
    });

    it('should only accept objects for request parameter', async () => {
      const notAnObject = 42;

      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await callMiddleware(defaultMiddleware, notAnObject, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be an object/);
      }
    });

    it('should not accept null for request parameter', async () => {
      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await callMiddleware(defaultMiddleware, null, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be an object/);
      }
    });

    it('should only accept objects for response parameter', async () => {
      const notAnObject = 42;

      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await callMiddleware(defaultMiddleware, defaultRequest, notAnObject);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be an object/);
      }
    });

    it('should not accept null for response parameter', async () => {
      expect.assertions(2);
      try {
        // $FlowFixMe: override violation for test case
        await callMiddleware(defaultMiddleware, defaultRequest, null);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/must be an object/);
      }
    });

    it('should fail if brigade results to undefined', async () => {
      const middleware = [
        async (request, next, terminate) => {
          await terminate();
          return undefined;
        }
      ];

      expect.assertions(2);
      try {
        await callMiddleware(compose(middleware), defaultRequest);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/cannot be undefined/);
      }
    });

    it('should detect if next or terminate not called', async () => {
      const middleware = [
        // Flow should probably catch this
        async () => {
        }
      ];

      expect.assertions(2);
      try {
        await callMiddleware(compose(middleware), defaultRequest, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/terminated with an unexpected response/);
      }
    });

    it('should detect if the chain is broken', async () => {
      const middleware = [
        // Flow should probably catch this
        async (request, next) => {
          next();
        },
        async (request, next) => next()
      ];

      expect.assertions(2);
      try {
        await callMiddleware(compose(middleware), defaultRequest, defaultResponse);
      } catch (e) {
        expect(e).toBeInstanceOf(Error);
        expect(e.message).toMatch(/terminated with an unexpected response/);
      }
    });
  });
});


text:
## Introduction

Laravel Decomposer decomposes and lists all the installed packages and their dependencies along with the Laravel & the Server environment details your app is running in. Decomposer also generates a [markdown report](https://github.com/lubusIN/laravel-decomposer/blob/master/report.md) from those details that can be used for troubleshooting purposes, also it allows you to generate the same report [as an array](https://github.com/lubusIN/laravel-decomposer/wiki/Get-Report-as-an-array) and also [as JSON](https://github.com/lubusIN/laravel-decomposer/wiki/Get-Report-as-JSON) anywhere in your code. Laravel Package & app devs you can also [add your own personal extra stats specific for your package or your app](https://github.com/lubusIN/laravel-decomposer/wiki/Add-your-extra-stats). All these just on the hit of a single route as shown below in the gif.

**Screenshot**

![Laravel Decomposer](https://cloud.githubusercontent.com/assets/11228182/23458894/0ffe7992-fea4-11e6-8441-e7550f6c3139.gif)

> **Kind Attention :**
You can have a look at the [Roadmap](https://github.com/lubusIN/laravel-decomposer#roadmap). If you have any suggestions for code improvements, new optional or core features or enhancements, create an issue so you,us or any open source believer can start working on it.

## Features
- This can be used by your non-tech client/user of your laravel app or non-experienced dev who still dosen't uses CLI to generate the system report & send over to you so you can know the entire details of his environment.
- To see the list of all installed packages & their dependencies in the laravel app directly from the browser
- To get the Laravel & Server environment details on the same page with the packages list
- To check whether all the pre configurations & extensions asked by Laravel are applied and loaded or not
- Suppose suddenly or after some changes your app broke, you can install Laravel Decomposer, generate & copy the [report](https://github.com/lubusIN/laravel-decomposer/blob/master/report.md) and paste it in the issue box of the respective repo you are reporting the issue to.
- For package/laravel app developers this can be very useful when collecting the information from the users reporting the issues. As the report gives them complete info about the environment the issue is being raised in.
- It can also help you in other ways like suppose you have a package installed that is using illuminate/support v5.1, and an another package using illuminate/support v5.3, so getting these facts quickly by just hitting to a route can make you aware of possible unstability & conflicts so you can report that to the respective package developer.
- It cuts down the troubleshooting time. For eg: Sometimes after trying all possible solutions at the end the user says 'I forgot to say I am on PHP 4'. Here Decomposer acts as the precaution & removes the dependency of querying the user for every single thing.

## Roadmap

- ~Allow Decomposer report to be accessed via code~ _Released in [v1.1](https://github.com/lubusIN/laravel-decomposer#helpers)_
- ~Allow users and other packages to add their own stats in the Decomposer report~ _Released in [v1.2](https://github.com/lubusIN/laravel-decomposer/wiki/Add-your-extra-stats)_
- Add a config file to allow user to control what he/she wants to see in the view
- Check for updates of the installed packages & show if any available for the respective packages or their dependencies
- Compare same dependency versions for different packages & warn user about the possible conflict. (Can be achieved even now as the search results highlighting is enabled, but sure it can be done in more better way)
- Make UI more informative & UX more better
- Let us know if you want anything to be added in the decomposer. After all the user makes the packages worth :)
- We have created the [issues](https://github.com/lubusIN/laravel-decomposer/issues) & [labels](https://github.com/lubusIN/laravel-decomposer/labels) with the appropriate titles , where you can contribute your ideas & suggestions or let us know if you are working on a PR for that. Always more than happy to hear & learn new things from the community.

## Installation

You can install this package via composer:

```bash
composer require lubusin/laravel-decomposer
```

Next, add the service provider:

```php
// In config/app.php ( Thank you for considering this package! Have a great day :) )

'providers' => [
    /*
     * Package service providers
     */
    Lubusin\Decomposer\DecomposerServiceProvider::class,
];
```

Add a route in your web routes file:

```php
Route::get('decompose','\Lubusin\Decomposer\Controllers\DecomposerController@index');
```
Go to http://yourapp/decompose or the route you configured above in the routes file.

## Docs

The Docs can be found in the [Wiki](https://github.com/lubusIN/laravel-decomposer/wiki) but to save you one more click, here's the index
- [Add your own extra stats for your package or app](https://github.com/lubusIN/laravel-decomposer/wiki/Add-your-extra-stats)
- [Get Decomposer report as markdown](https://github.com/lubusIN/laravel-decomposer/wiki/Get-Markdown-Report)
- [Get Decomposer report as an array](https://github.com/lubusIN/laravel-decomposer/wiki/Get-Report-as-an-array)
- [Get Decomposer report as JSON](https://github.com/lubusIN/laravel-decomposer/wiki/Get-Report-as-JSON)

## Contributing

Thank you for considering contributing to the Laravel Decomposer. You can read the contribution guide lines [here](contributing.md)

## Security

If you discover any security related issues, please email to [harish@lubus.in](mailto:harish@lubus.in).

## Credits

- [Harish Toshniwal](https://github.com/introwit)

## About LUBUS
[LUBUS](http://lubus.in) is a web design agency based in Mumbai.

## License
Laravel Decomposer is open-sourced software licensed under the [MIT license](LICENSE.txt)

## Changelog
Please see the [Changelog](https://github.com/lubusIN/laravel-decomposer/blob/master/changelog.md) for the details


text:
package com.kaopiz.kprogresshud;

import android.content.Context;

class Helper {

    private static float scale;

    public static int dpToPixel(float dp, Context context) {
        if (scale == 0) {
            scale = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dp * scale);
    }
}


text:
package com.gentics.mesh.plugin.pf4j;

import java.util.Objects;

import javax.inject.Inject;
import javax.inject.Named;

import com.gentics.mesh.RestAPIVersion;
import com.gentics.mesh.auth.provider.MeshJWTAuthProvider;
import com.gentics.mesh.cli.BootstrapInitializer;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.db.Database;
import com.gentics.mesh.etc.config.MeshOptions;
import com.gentics.mesh.plugin.env.PluginEnvironment;
import com.gentics.mesh.rest.client.MeshRestClient;
import com.gentics.mesh.rest.client.MeshRestClientConfig;

import dagger.Lazy;
import io.vertx.core.Vertx;
import okhttp3.OkHttpClient;

/**
 * @see PluginEnvironment
 */
public class PluginEnvironmentImpl implements PluginEnvironment {

	private final Database db;

	private final Lazy<Vertx> vertx;

	private final MeshOptions options;

	private Lazy<MeshJWTAuthProvider> authProvider;

	private Lazy<BootstrapInitializer> boot;

	private final OkHttpClient pluginOkHttpClient;

	private static final String WILDCARD_IP = "0.0.0.0";

	private static final String LOOPBACK_IP = "127.0.0.1";

	@Inject
	public PluginEnvironmentImpl(Lazy<BootstrapInitializer> boot, Database db, Lazy<MeshJWTAuthProvider> authProvider, Lazy<Vertx> vertx,
		MeshOptions options, @Named("pluginClient") OkHttpClient pluginOkHttpClient) {
		this.boot = boot;
		this.db = db;
		this.authProvider = authProvider;
		this.vertx = vertx;
		this.options = options;
		this.pluginOkHttpClient = pluginOkHttpClient;
	}

	@Override
	public String adminToken() {
		return db.tx(tx -> {
			HibUser admin = tx.userDao().findByUsername("admin");
			// TODO: Use dedicated tokenCode - See https://github.com/gentics/mesh/issues/412
			return authProvider.get().generateAPIToken(admin, null, null);
		});
	}

	@Override
	public Vertx vertx() {
		return vertx.get();
	}

	@Override
	public MeshRestClient createAdminClient() {
		return createAdminClient(RestAPIVersion.V1);
	}

	@Override
	public MeshRestClient createAdminClient(RestAPIVersion version) {
		Objects.requireNonNull(version);
		int port = options.getHttpServerOptions().getPort();
		String host = determineHostString(options);
		MeshRestClient client = MeshRestClient.create(MeshRestClientConfig.newConfig()
			.setPort(port)
			.setHost(host)
			.setBasePath(version.getBasePath())
			.build(), pluginOkHttpClient);

		client.setAPIKey(adminToken());
		return client;
	}

	@Override
	public MeshRestClient createClient(String token) {
		int port = options.getHttpServerOptions().getPort();
		String host = determineHostString(options);
		MeshRestClient client = MeshRestClient.create(new MeshRestClientConfig.Builder()
			.setHost(host)
			.setPort(port)
			.setSsl(false)
			.build(), pluginOkHttpClient);

		// Set the token to the client if it was specified.
		if (token != null) {
			client.setAPIKey(token);
		}
		return client;
	}

	@Override
	public MeshOptions options() {
		return options;
	}

	private String determineHostString(MeshOptions options) {
		String host = options.getHttpServerOptions().getHost();
		return WILDCARD_IP.equals(host) ? LOOPBACK_IP : host;
	}

}


text:
import React from "react";
import styled from "styled-components";
// Typography
import { Typography } from "typography";
// Components
import { InfoItem } from "./InfoItem";
// Assets
import icons from "assets/img/icons";
import { TITLE } from "assets/static/phrases";
// Libs
import { useResponsive } from "lib/hooks";

interface ICourseDetailInfo {
  title: string;
  content: string;
  img: keyof typeof icons;
}

interface ICourseInfo {
  backgroundImage: string;
  backgroundColor: string;
  title: string;
  process?: string;
  description: string;
  targets: string[];
  courseInfos: ICourseDetailInfo[];
}

const CourseInfo: React.FC<ICourseInfo> = ({
  backgroundImage,
  backgroundColor,
  title,
  process,
  description,
  targets,
  courseInfos,
}) => {
  const { isMobile } = useResponsive();

  return (
    <CourseInfoWrapper {...{ backgroundImage, backgroundColor }}>
      <ContentWrapper>
        <TitleWrapper>
          {process && <Typography type={isMobile ? "MBold" : "SHLBold"}>{process}</Typography>}
          <Typography type={isMobile ? "SDisplay" : "LDisplay"}>{title}</Typography>
        </TitleWrapper>
        <InfoWrapper>
          <InfoItemWrapper>
            <Typography
              type={isMobile ? "SBody" : "MBody"}
              style={{ whiteSpace: "pre-line", marginBottom: "1.6rem" }}
            >
              {description}
            </Typography>
            {courseInfos.map(({ title, content, img }) => (
              <InfoItem key={title} icon={icons[img]} {...{ title, content }} />
            ))}
          </InfoItemWrapper>
          <TargetWrapper>
            <TargetTitle>
              <img alt={`member-img`} src={icons.member} style={{ marginRight: ".8rem" }} />
              <Typography type="MBold">{TITLE.EDUCATION_TARGET}</Typography>
            </TargetTitle>
            <TargetItemWrapper>
              {targets.map((target: string) => (

                  <Typography
                    type={isMobile ? "XSBody" : "MBody"}
                    style={{
                      display: "inline",
                      verticalAlign: "middle",
                    }}
                  >
                    {target}
                  </Typography>

              ))}
            </TargetItemWrapper>
          </TargetWrapper>
        </InfoWrapper>
      </ContentWrapper>
    </CourseInfoWrapper>
  );
};

const CourseInfoWrapper = styled.div<{ backgroundImage: string; backgroundColor: string }>`
  position: relative;
  display: flex;
  flex-direction: column;
  color: ${({ theme: { color } }) => color.black};
  background-color: ${({ backgroundColor }) => backgroundColor};
  background-image: ${({ backgroundImage }) => `url(${backgroundImage})`};
  background-repeat: no-repeat;
  background-position: top right;
  @media ${({ theme }) => theme.device.mobile} {
    min-width: 31.2rem;
    padding: 14.2rem 2.4rem 4.4rem 2.4rem;
    background-size: contain;
  }
  @media ${({ theme }) => theme.device.tablet} {
    min-width: 60.8rem;
    padding: 16rem 8rem 5.6rem 8rem;
    background-size: cover;
  }
  @media ${({ theme }) => theme.device.desktop} {
    align-items: center;
    min-width: 106.2rem;
    height: 56rem;
  }
`;

const ContentWrapper = styled.div`
  @media ${({ theme }) => theme.device.mobile} {
    box-sizing: border-box;
  }
  @media ${({ theme }) => theme.device.desktop} {
    position: absolute;
    bottom: 8rem;
  }
`;

const TitleWrapper = styled.div`
  display: flex;
  flex-direction: column;
  & > *:not(:last-child) {
    margin-bottom: 0.8rem;
  }
  @media ${({ theme }) => theme.device.mobile} {
    margin-bottom: 1.6rem;
    & > *:not(:last-child) {
      margin-bottom: 0;
    }
  }
  @media ${({ theme }) => theme.device.tablet} {
    margin-bottom: 1.6rem;
  }
  @media ${({ theme }) => theme.device.desktop} {
    min-width: 106.2rem;
    & > *:last-child {
      width: 50%;
    }
  }
`;

const InfoWrapper = styled.div`
  display: flex;
  @media ${({ theme }) => theme.device.mobile} {
    flex-direction: column;
  }
  @media ${({ theme }) => theme.device.tablet} {
    flex-direction: column;
  }
  @media ${({ theme }) => theme.device.desktop} {
    justify-content: space-between;
    min-width: 106.2rem;
    margin-top: 4rem;
  }
`;

const TargetTitle = styled.h4`
  display: flex;
  @media ${({ theme }) => theme.device.mobile} {
    margin: 1.6rem 0 0.8rem 0;
  }
  @media ${({ theme }) => theme.device.tablet} {
    margin: 1.6rem 0 0.8rem 0;
  }
  @media ${({ theme }) => theme.device.desktop} {
    align-items: center;
    margin-bottom: 0.8rem;
  }
`;
const TargetWrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
`;

const TargetItemWrapper = styled.ul`
  display: flex;
  flex-direction: column;
  list-style-type: disc;
  list-style-position: outside;
  margin-left: 2rem;
  & > *:not(:last-child) {
    margin-bottom: 0.8rem;
  }
`;

const InfoItemWrapper = styled.ul`
  display: flex;
  flex-direction: column;
  flex-wrap: "wrap";
  & > *:not(:last-child) {
    margin-bottom: 0.8rem;
  }
  max-width: 45rem;
`;

export default CourseInfo;


text:
"""
Copyright 2015 flw_dream@126.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.
"""

import os, sys, re, uuid, string

class Project(object):
    api_files = []
    src_files = []
    prj_files = []
    prjname = 'general'
    pkgname = 'template'
    rootpath = os.path.abspath('..')
    inc_dir = 'include'
    src_dir = 'src'
    prj_dir = 'projects'

    def __init__(self, prjname):
        self.prjname = prjname
        dir = os.path.join(self.rootpath, self.inc_dir, self.pkgname, self.prjname)
        self.api_files = os.listdir(dir)
        dir = os.path.join(self.rootpath, self.src_dir, self.pkgname, self.prjname)
        self.src_files = os.listdir(dir)

        dir = os.path.join(self.rootpath, self.prj_dir, self.pkgname)
        for item in os.listdir(dir):
            if self.prjname in item:
                self.prj_files.append(item)

    def generate(self, des_pkgname, des_prjname):
        desdir = os.path.join(self.rootpath, self.src_dir, string.lower(des_pkgname), string.lower(des_prjname))
        if not os.path.exists(desdir):
            os.makedirs(desdir)

        desdir = os.path.join(self.rootpath, self.inc_dir, string.lower(des_pkgname), string.lower(des_prjname))
        if not os.path.exists(desdir):
            os.makedirs(desdir)

        for item in self.api_files:
            srcfile = os.path.join(self.rootpath, self.inc_dir, string.lower(self.pkgname), string.lower(self.prjname), item)
            desfile = os.path.join(self.rootpath, self.inc_dir, string.lower(des_pkgname), string.lower(des_prjname), item.replace(string.lower(self.prjname), string.lower(des_prjname), 1))
            self.__copyfile(srcfile, desfile, des_pkgname, des_prjname)

        for item in self.src_files:
            srcfile = os.path.join(self.rootpath, self.src_dir, string.lower(self.pkgname), string.lower(self.prjname), item)
            desfile = os.path.join(self.rootpath, self.src_dir, string.lower(des_pkgname), string.lower(des_prjname), item.replace(string.lower(self.prjname), string.lower(des_prjname), 1))
            self.__copyfile(srcfile, desfile, des_pkgname, des_prjname)

        for item in self.prj_files:
            srcfile = os.path.join(self.rootpath, self.prj_dir, string.lower(self.pkgname), item)
            desfile = os.path.join(self.rootpath, self.prj_dir, string.lower(des_pkgname), item.replace(string.lower(self.prjname), string.lower(des_prjname), 1))
            self.__copyfile(srcfile, desfile, des_pkgname, des_prjname)

    def __copyfile(self, srcfile, desfile, des_pkg, des_prj):
        src_str = open(srcfile, "rb").read()
        des_str = self.__replace(src_str, des_pkg, des_prj)
        open(desfile, 'wb').write(des_str)
        print '[generate] %s' % desfile

    def __replace(self, src_str, pkgname, prjname):
        ret = src_str.replace('{{pkg_name}}', pkgname)
        ret = ret.replace('{{project_name}}', prjname)
        ret = ret.replace('{{project_name_upper}}', string.upper(prjname))
        ret = ret.replace('{{project_name_lower}}', string.lower(prjname))
        ret = ret.replace('{{uuid}}', str(uuid.uuid1()))
        return ret

if __name__=="__main__":
    def inputparam(index, prompt, default='', options=None):
        if len(sys.argv) > index:
            ret = sys.argv[index]
        else:
            ret = raw_input(prompt)

        if ret == '':
            ret = default

        if(options is not None and ret not in options):
            print 'select one of the options please!\n'
            ret = inputparam(index, prompt, default, options)

        return ret

    types = ['general', 'pane', 'view']
    prjtype = inputparam(1, 'select plugin type(general/pane/view)\nplugin type(default: general): ', 'general', types)
    prjname = inputparam(2, 'project name: ')
    pkgname = inputparam(3, 'package name of the new project (default: plugins): ', 'plugins')

    prj = Project(prjtype)
    prj.generate(pkgname, prjname)

    if len(sys.argv) < 3:
        raw_input("Press <ENTER> to end.")


text:
from django.conf.urls import patterns, url
from fitness import views

urlpatterns = patterns('fitness.views',
    url(r'^rides/$', views.rides, name = 'rides'),
    url(r'^log/$', views.log, name = 'log')
)


text:
package org.usfirst.frc5933.StevenDave.mapping;

public class Coordinate {

    private double x_ = 0;
    private double y_ = 0;
    private double z_ = 0;

    public Coordinate() {
    }

    public Coordinate(double x, double y, double z) {
        x_ = x;
        y_ = y;
        z_ = y;
    }

    public final double getX() {
        return x_;
    }

    public final double getY() {
        return y_;
    }

    public final double getZ() {
        return z_;
    }
}


text:
Use the JSX syntax in ES6 template strings!

[React](http://facebook.github.io/react) is awesome. And the optional
[JSX](http://facebook.github.io/jsx) syntax that comes with it makes it
even more convenient to author components in a natural XML-like syntax.
However, it has two major drawbacks:

* it adds a new type of expression in the JavaScript syntax, which
is bizarre and can make JSLint or JSHint go crazy;
* it requires a compile step to become valid JavaScript.

The ES6 specification describes a new type of strings: template strings.
They can be used to interpolate variables in a string, but can also be
used with a tag to parse any type of DSL.

See the
[HTML5 Rocks article on template strings](http://updates.html5rocks.com/2015/01/ES6-Template-Strings)
for more information.
Based on [a gist from @lygaret](https://gist.github.com/lygaret/a68220defa69174bdec5).

This module takes advatange of this new syntax to enable you to write
ESX in pure JavaScript syntax.

## Install

```sh
$ npm install --save esx
```

## Usage

Import the `esx` module then use it as a tag in front of template strings.
The syntax is almost the same as JSX, but you have to wrap your ESX code
with `esx` and backticks, and to use `${regular JS expression}` rather
than `{regular JS expression}`.

Example (taken from the JSX spec):

```js
var esx = require('esx');
var Dropdown = require('./dropdown');
var Menu = require('./menu');
var MenuItem = require('./menu').Item;

var dropdown = esx`
    <${Dropdown}>
        A dropdown list

        <${Menu}>
            <${MenuItem}>Do Something</${MenuItem}>
            <${MenuItem}>Do Something Fun!</${MenuItem}>
            <${MenuItem}>Do Something Else</${MenuItem}>
        </${Menu}>
    </${Dropdown}>
`;
```

## Compatibility

This module is compatible with any JS engine that implements ES6 template
strings, for example with `Node.JS >= 4.0.0` or with up-to-date browsers.

## Commit convention

:book:      Documentation updates
:bug:       Bug fixes
:ledger:    Rename/move files
:bulb:      Features
:lipstick:  Fix coding style

## License

See LICENSE.


text:
require 'net/http'
require 'uri'

module Wink

  # An interface to the Akismet spam detection service.
  #
  # === Comment Information
  #
  # The various Akismet request methods (e.g., #spam!, #ham!, #check) supported by this
  # class take a +params+ argument, which is a Hash of the following key values:
  #
  # <tt>:user_ip</tt> (required)::
  #    IP address of the comment submitter. Care must be taken to get this right when
  #    a gateway/reverse proxy or other intermediary is involved in the
  #    request. The +X-Forwarded-For+ request header can often be used to determine
  #    the IP in these scenarios.
  #
  # <tt>:user_agent</tt> (required)::
  #    The +User-Agent+ request header included with the comment submission
  #    request.
  #
  # <tt>:referrer</tt> (optional)::
  #    The +Referer+ request header included with the comment submission
  #
  # <tt>:permalink</tt> (optional)::
  #    The permanent location of the entry the comment was submitted to.
  #
  # <tt>:comment_type</tt> (optional)::
  #    May be blank, comment, trackback, pingback, or a made up value like "registration".
  #
  # <tt>:comment_author</tt> (optional)::
  #    Comment author's full name.
  #
  # <tt>:comment_author_email</tt> (optional)::
  #    Comment author's email address.
  #
  # <tt>:comment_author_url</tt> (optional)::
  #    Comment author's URL.
  #
  # <tt>:comment_content</tt> (optional)::
  #    The content of the comment that was submitted.
  #
  # === Other server enviroment variables
  #
  # In PHP there is an array of enviroment variables called $_SERVER which
  # contains information about the web server itself as well as a key/value
  # for every HTTP header sent with the request. This data is highly useful
  # to Akismet as how the submited content interacts with the server can be
  # very telling, so please include as much information as possible.
  #
  # === See Also
  #
  # {Offical Akismet API Documentation}[http://akismet.com/development/api/]
  # {David Czarnecki akismet.rb}[http://www.blojsom.com/blog/nerdery/2005/12/02/Akismet-API-in-Ruby.html]
  #
  class Akismet

    # Hash of request headers included with Akismet requests.
    STANDARD_HEADERS = {
      'User-Agent'   => "Wink/#{Wink::VERSION} | Akismet Ruby API/1.0",
      'Content-Type' => 'application/x-www-form-urlencoded'
    }

    # The URL of the blog or website that uses Akismet.
    attr_reader :url

    # The API key associate with the blog or website URL.
    attr_reader :key

    # A Hash of request headers delivered with each request.
    attr_reader :headers

    # Create a new Akismet call site. The +key+ and +url+ arguments are
    # required and
    def initialize(key, url, headers={})
      raise ArgumentError, "Expected key and url" if [key,url].any?{ |v| v.nil? }
      @key = key
      @url = url
      @headers = STANDARD_HEADERS.dup.merge(headers)
      @verified = false
    end

    # Has the key been verified?
    def verified?
      @verified
    end

    # Call to check and verify your API key. You may then call the #verified? method to see if
    # your key has been validated.
    def verify!
      return true if verified?
      http = Net::HTTP.new('rest.akismet.com', 80)
      resp, data = http.post('/1.1/verify-key', "key=#{@key}&blog=#{@blog}", @headers)
      @verified = (data == "valid")
    end

    # This is basically the core of everything. This call takes a number of
    # arguments and characteristics about the submitted content and then returns
    # a thumbs up or thumbs down. Almost everything is optional, but performance
    # can drop dramatically if you exclude certain elements.
    def check(params={})
      call 'comment-check', params
    end

    # This call is for submitting comments that weren't marked as spam but
    # should have been. It takes identical arguments as comment check.
    def spam!(params={})
      call 'submit-spam', params
    end

    # This call is intended for the marking of false positives, things that were
    # incorrectly marked as spam. It takes identical arguments as comment check
    # and submit spam.
    def ham!(params={})
      call 'submit-ham', params
    end

  private

    # Regular expression used for escaping parameters in the Akismet post
    # body. This is used in place of URL::REGEXP::UNSAFE.
    #
    ESCAPE_CHARS = Regexp.union(URI::REGEXP::UNSAFE, /[&?=]/n)

    # Internal call to Akismet. Prepares the data for posting to the Akismet service.
    #
    # The +params+ Hash keys are described in the Akismet class documentation.
    def call(method, params={})
      params = params.reject{|k,v| v.nil?}.merge(:blog => @url)
      res =
        Net::HTTP.start("#{@key}.rest.akismet.com", 80) do |http|
          http.post("/1.1/#{method}", post_data(params), headers)
        end
      res.body == "true"
    end

    # Convert the Hash provided into a URL encoded string suitable for passing
    # to Akismet's POST messages.
    def post_data(params={})
      params.
        reject { |k,v| k.nil? }.
        merge(:blog => @url).
        collect { |k,v| [k, URI.escape(v, ESCAPE_CHARS)].join('=') }.
        join('&')
    end

  end

end


text:
-- phpMyAdmin SQL Dump
-- version 4.0.4.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 04, 2015 at 09:09 PM
-- Server version: 5.5.32
-- PHP Version: 5.4.16

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `trackmytruck`
--
CREATE DATABASE IF NOT EXISTS `trackmytruck` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `trackmytruck`;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_dr_num`
--

CREATE TABLE IF NOT EXISTS `tbl_dr_num` (
  `DR_NUM` int(11) NOT NULL,
  `IS_USED` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`DR_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_truck`
--

CREATE TABLE IF NOT EXISTS `tbl_truck` (
  `TRUCK_ID` int(11) NOT NULL AUTO_INCREMENT,
  `TRUCK_NUM` varchar(10) NOT NULL,
  `COMMODITY` varchar(40) NOT NULL,
  `DEST_FROM` varchar(50) NOT NULL,
  `DEST_TO` varchar(50) NOT NULL,
  `SOLD_TO` varchar(50) NOT NULL,
  `VOLUME` int(11) NOT NULL,
  `DRIVER` varchar(50) NOT NULL,
  `DR_NUM` int(15) DEFAULT NULL,
  `REMARKS` text NOT NULL,
  `DATE_ISSUED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ISSUED_BY` varchar(50) NOT NULL,
  `DELETE_FLAG` tinyint(1) NOT NULL,
  PRIMARY KEY (`TRUCK_ID`),
  UNIQUE KEY `DR_NUM` (`DR_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
using Crystal3;
using Crystal3.UI;
using Neptunium.Glue;
using Neptunium.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace Neptunium.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    [Crystal3.Navigation.NavigationViewModel(typeof(Neptunium.ViewModel.SettingsPageViewModel))]
    public sealed partial class SettingsPage : Page, IXboxInputPage
    {
        public SettingsPage()
        {
            this.InitializeComponent();

            switch(DeviceInformation.GetDevicePlatform())
            {
                case Crystal3.Core.Platform.Mobile:
                    HapticFeedbackSwitch.IsEnabled = true;
                    break;
                default:
                    HapticFeedbackSwitch.IsEnabled = false;
                    HapticFeedbackSwitch.XYFocusUp = null;
                    HapticFeedbackSwitch.XYFocusDown = null;
                    HapticFeedbackSwitch.IsTabStop = false;

                    SongNotificationSwitch.XYFocusDown = MetadataSwitch;
                    MetadataSwitch.XYFocusUp = SongNotificationSwitch;
                    break;
            }
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (DeviceInformation.GetDevicePlatform() != Crystal3.Core.Platform.Xbox)
            {
                UpdateLockScreenSwitch.Visibility = Visibility.Visible;
            }
            else
            {
                //force focus on Xbox.
                RootPivot.Focus(FocusState.Keyboard);
            }
        }

        private async void SetFallBackLockScreenBtn_Click(object sender, RoutedEventArgs e)
        {
            var picker = new Windows.Storage.Pickers.FileOpenPicker();
            picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
            if (file != null)
            {
                // Application now has read/write access to the picked file

                //todo check if less or equal to 2MB on mobile before proceeding.

                await NepApp.UI.LockScreen.SetFallbackImageAsync(file);
            }
            else
            {
                //cancelled
            }
        }

        public void SetLeftFocus(UIElement elementToTheLeft)
        {

        }

        public void SetRightFocus(UIElement elementToTheRight)
        {

        }

        public void SetTopFocus(UIElement elementAbove)
        {

        }

        public void SetBottomFocus(UIElement elementBelow)
        {

        }

        public void RestoreFocus()
        {

        }

        public void PreserveFocus()
        {

        }

        public void FocusDefault()
        {

        }
    }
}


text:
package com.hazelcast.jet.sql.impl.connector;

import com.hazelcast.jet.core.DAG;
import com.hazelcast.jet.core.Vertex;
import com.hazelcast.jet.sql.impl.schema.MappingField;
import com.hazelcast.spi.impl.NodeEngine;
import com.hazelcast.sql.impl.expression.Expression;
import com.hazelcast.sql.impl.schema.Table;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;

/**
 * An API to bridge Jet connectors and SQL. Allows the use of a Jet
 * connector from SQL and create a mapping for remote objects available
 * through the connector.
 *

 * It's currently private because we expect significant changes to it, but
 * we plan to make it part of the public Core API in the future.
 */
public interface SqlConnector {

    /**
     * The serialization format. Used for connectors that don't have a separate
     * key and value format.
     */
    String OPTION_FORMAT = "format";

    /**
     * The key serialization format for key-value connectors.
     */
    String OPTION_KEY_FORMAT = "keyFormat";

    /**
     * The value serialization format for key-value connectors.
     */
    String OPTION_VALUE_FORMAT = "valueFormat";

    /**
     * The key Java class, if {@value #OPTION_KEY_FORMAT} is {@value
     * JAVA_FORMAT}.
     */
    String OPTION_KEY_CLASS = "keyJavaClass";

    /**
     * The value Java class, if {@value #OPTION_VALUE_FORMAT} is {@value
     * JAVA_FORMAT}.
     */
    String OPTION_VALUE_CLASS = "valueJavaClass";

    /**
     * The key Portable factory ID, if {@value #OPTION_KEY_FORMAT} is {@value
     * PORTABLE_FORMAT}.
     */
    String OPTION_KEY_FACTORY_ID = "keyPortableFactoryId";

    /**
     * The key Portable class ID, if {@value #OPTION_KEY_FORMAT} is {@value
     * PORTABLE_FORMAT}.
     */
    String OPTION_KEY_CLASS_ID = "keyPortableClassId";

    /**
     * The key Portable class version, if {@value #OPTION_KEY_FORMAT} is
     * {@value PORTABLE_FORMAT}.
     */
    String OPTION_KEY_CLASS_VERSION = "keyPortableClassVersion";

    /**
     * The value Portable factory ID, if {@value #OPTION_VALUE_FORMAT} is
     * {@value PORTABLE_FORMAT}.
     */
    String OPTION_VALUE_FACTORY_ID = "valuePortableFactoryId";

    /**
     * The value Portable class ID, if {@value #OPTION_VALUE_FORMAT} is {@value
     * PORTABLE_FORMAT}.
     */
    String OPTION_VALUE_CLASS_ID = "valuePortableClassId";

    /**
     * The value Portable class version, if {@value #OPTION_VALUE_FORMAT} is
     * {@value PORTABLE_FORMAT}.
     */
    String OPTION_VALUE_CLASS_VERSION = "valuePortableClassVersion";

    /**
     * Value for {@value #OPTION_KEY_FORMAT} and {@value #OPTION_VALUE_FORMAT}
     * for Java serialization.
     */
    String JAVA_FORMAT = "java";

    /**
     * Value for {@value #OPTION_KEY_FORMAT} and {@value #OPTION_VALUE_FORMAT}
     * for Portable serialization.
     */
    String PORTABLE_FORMAT = "portable";

    /**
     * Value for {@value #OPTION_KEY_FORMAT}, {@value #OPTION_VALUE_FORMAT}
     * and {@value #OPTION_FORMAT} for JSON serialization.
     */
    String JSON_FORMAT = "json";

    /**
     * Value for {@value #OPTION_FORMAT} for CSV (comma-separated values)
     * serialization.
     */
    String CSV_FORMAT = "csv";

    /**
     * Value for {@value #OPTION_FORMAT}, {@value #OPTION_KEY_FORMAT} and
     * {@value #OPTION_VALUE_FORMAT} for Avro serialization.
     */
    String AVRO_FORMAT = "avro";

    /**
     * Value for {@value #OPTION_FORMAT} for Parquet serialization.
     */
    String PARQUET_FORMAT = "parquet";

    /**
     * A key in the table options (TO).
     *

     * Specifies the accessed object name. If missing, the external table name
     * itself is used.
     */
    String OPTION_OBJECT_NAME = "objectName";

    /**
     * Return the name of the connector as seen in the {@code TYPE} clause in
     * the {@code CREATE EXTERNAL MAPPING} command.
     */
    String typeName();

    /**
     * Returns {@code true}, if {@link #fullScanReader} is an unbounded source.
     */
    boolean isStream();

    /**
     * Resolves the final field list given an initial field list and options
     * from the user. Jet calls this method when processing a CREATE MAPPING
     * statement.
     *

     * The {@code userFields} can be empty, in this case the connector is
     * supposed to resolve them from a sample or from options. If it's not
     * empty, it should only validate it — it should neither add/remove
     * columns nor change the type. It can add the external name.
     *

     * The returned list must not be empty. Jet stores it in the catalog, and
     * the user can see it by listing the catalog. Jet will later pass it to
     * {@link #createTable}.
     *
     * @param nodeEngine an instance of {@link NodeEngine}
     * @param options    user-provided options
     * @param userFields user-provided list of fields, possibly empty
     * @return final field list, must not be empty
     */
    @Nonnull
    List<MappingField> resolveAndValidateFields(
            @Nonnull NodeEngine nodeEngine,
            @Nonnull Map<String, String> options,
            @Nonnull List<MappingField> userFields
    );

    /**
     * Creates a {@link Table} object with the given fields. Should return
     * quickly; specificially it should not attempt to connect to the remote
     * service.
     *

     * Jet calls this method for each statement execution and for each mapping.
     *
     * @param nodeEngine     an instance of {@link NodeEngine}
     * @param options        connector specific options
     * @param resolvedFields list of fields as returned from {@link
     *                       #resolveAndValidateFields}
     */
    @Nonnull
    Table createTable(
            @Nonnull NodeEngine nodeEngine,
            @Nonnull String schemaName,
            @Nonnull String tableName,
            @Nonnull Map<String, String> options,
            @Nonnull List<MappingField> resolvedFields
    );

    /**
     * Returns whether this connector supports the {@link #fullScanReader}. The
     * default implementation returns {@code false}.
     */
    default boolean supportsFullScanReader() {
        return false;
    }

    /**
     * Returns a supplier for a source vertex reading the input according to
     * the projection/predicate. The output type of the source is Object[].
     *

     * The field indexes in the predicate and projection refer to the
     * zero-based indexes of the original fields of the {code table}. For
     * example, if the table has fields {@code a, b, c} and the query is:
     *
{@code
     *     SELECT b FROM t WHERE c=10
     * }

     * Then the projection will be {@code {1}} and the predicate will be {@code
     * {2}=10}.
     *
     * @param table      the table object
     * @param predicate  SQL expression to filter the rows
     * @param projection the list of field names to return
     * @return The DAG Vertex handling the reading
     */
    @Nonnull
    default Vertex fullScanReader(
            @Nonnull DAG dag,
            @Nonnull Table table,
            @Nullable Expression<Boolean> predicate,
            @Nonnull List<Expression<?>> projection
    ) {
        assert !supportsFullScanReader();
        throw new UnsupportedOperationException("Full scan not supported for " + typeName());

    }

    /**
     * Returns whether this connector supports the {@link #sink}. The default
     * implementation returns {@code false}.
     */
    default boolean supportsSink() {
        return false;
    }

    /**
     * Returns whether this connector supports the {@code INSERT} statement.
     * The default implementation returns {@code false}.
     */
    default boolean supportsInsert() {
        return false;
    }

    /**
     * Returns the supplier for the sink processor.
     */
    @Nonnull
    default Vertex sink(
            @Nonnull DAG dag,
            @Nonnull Table table
    ) {
        assert !supportsSink();
        throw new UnsupportedOperationException("Sink not supported for " + typeName());
    }
}


text:
import * as React from 'react';
import cx = require('classnames');
import { TableComponent, TableProps } from './types';

const Table: TableComponent = (props: TableProps) => {
    const rest = Object.assign({}, props);
    delete rest.striped;

    return (
        <table {...rest} className={cx({'table-striped': props.striped})}>
            {props.children}
        </table>
    );
}

export default Table;


text:
import * as plugins from './smartshell.plugins'

// interfaces
import { ChildProcess } from 'child_process'
import { Deferred } from 'smartq'

/**
 * interface for ExecResult
 */
export interface IExecResult {
  exitCode: number,
  stdout: string
}

/**
 * interface for streaming ExecResult
 */
export interface IExecResultStreaming {
  childProcess: ChildProcess,
  finalPromise: Promise<IExecResult>
}

/**
 * import path
 */
let importPath = (stringArg): string => {
  if (process.env.SMARTSHELL_PATH) {
    let commandResult = `PATH=${process.env.SMARTSHELL_PATH} && ${stringArg}`
    // console.log(commandResult)
    return commandResult
  } else {
    return stringArg
  }
}

/**
 * executes a given command async
 * @param commandStringArg
 */
export let exec = (commandStringArg: string, silentArg: boolean = false, strictArg = false): Promise<IExecResult> => {
  let done = plugins.smartq.defer<IExecResult>()
  plugins.shelljs.exec(importPath(commandStringArg), { async: true, silent: silentArg }, (code, stdout, stderr) => {
    if (
      stderr
      && (stderr !== '')
      && (!silentArg || strictArg)
      && (process.env.DEBUG === 'true')
    ) {
      console.log('StdErr found.')
      console.log(stderr)
    }
    if (strictArg) {
      done.reject(new Error(stderr))
      return
    }
    done.resolve({
      exitCode: code,
      stdout: stdout
    })
  })
  return done.promise
}

/**
 * executes a given command async and silent
 * @param commandStringArg
 */
export let execSilent = async (commandStringArg: string): Promise<IExecResult> => {
  return await exec(commandStringArg, true)
}

/**
 * executes strict, meaning it rejects the promise if something happens
 */
export let execStrict = async (commandStringArg: string): Promise<IExecResult> => {
  return await exec(commandStringArg, true, true)
}

/**
 * executes a command and allws you to stream output
 */
export let execStreaming = (commandStringArg: string, silentArg: boolean = false) => {
  let childProcessEnded = plugins.smartq.defer<IExecResult>()
  let execChildProcess = plugins.shelljs.exec(importPath(commandStringArg), {async: true, silent: silentArg}, (code, stdout, stderr) => {
    childProcessEnded.resolve({
      exitCode: code,
      stdout: stdout
    })
  })
  return {
    childProcess: execChildProcess,
    finalPromise: childProcessEnded.promise
  }
}

export let execStreamingSilent = (commandStringArg: string) => {
  return execStreaming(commandStringArg, true)
}

/**
 * executes a command and returns promise that will be fullfilled once an putput line matches RegexArg
 * @param commandStringArg
 * @param regexArg
 */
export let execAndWaitForLine = (commandStringArg: string, regexArg: RegExp, silentArg: boolean = false) => {
  let done = plugins.smartq.defer()
  let execStreamingResult = execStreaming(commandStringArg, silentArg)
  execStreamingResult.childProcess.stdout.on('data', (stdOutChunk: string) => {
    if (regexArg.test(stdOutChunk)) {
      done.resolve()
    }
  })
  return done.promise
}

export let execAndWaitForLineSilent = (commandStringArg: string, regexArg: RegExp) => {
  execAndWaitForLine(commandStringArg, regexArg, true)
}

/**
 * get a path
 */
export let which = (cmd: string): Promise<string> => {
  let done = plugins.smartq.defer<string>()
  plugins.which(cmd, (err, path: string) => {
    if (err) {
      done.reject(err)
    }
    done.resolve(path)
  })
  return done.promise
}


text:
I practice yoga 3 times a week
Cooking is ok,I odn't like it but don't hate it
I love to read


text:
package org.apache.activemq.usecases;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

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

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.QueueBrowser;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QueueZeroPrefetchLazyDispatchPriorityTest {

    private static final Logger LOG = LoggerFactory.getLogger(QueueZeroPrefetchLazyDispatchPriorityTest.class);

    private final byte[] PAYLOAD = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    private final int ITERATIONS = 6;

    private BrokerService broker;

    @Before
    public void setUp() throws Exception {
        broker = createBroker();
        broker.start();
        broker.waitUntilStarted();
    }

    @After
    public void tearDown() throws Exception {
        if (broker != null) {
            broker.stop();
        }
    }

    @Test(timeout=120000)
    public void testPriorityMessages() throws Exception {

        for (int i = 0; i < ITERATIONS; i++) {

            // send 4 message priority MEDIUM
            produceMessages(4, 4, "TestQ");

            // send 1 message priority HIGH
            produceMessages(1, 5, "TestQ");

            LOG.info("On iteration {}", i);

            Thread.sleep(500);

            // consume messages
            ArrayList<Message> consumeList = consumeMessages("TestQ");
            LOG.info("Consumed list " + consumeList.size());

            // compare lists
            assertEquals("message 1 should be priority high", 5, consumeList.get(0).getJMSPriority());
            assertEquals("message 2 should be priority medium", 4, consumeList.get(1).getJMSPriority());
            assertEquals("message 3 should be priority medium", 4, consumeList.get(2).getJMSPriority());
            assertEquals("message 4 should be priority medium", 4, consumeList.get(3).getJMSPriority());
            assertEquals("message 5 should be priority medium", 4, consumeList.get(4).getJMSPriority());
        }
    }

    @Test(timeout=120000)
    public void testPriorityMessagesMoreThanPageSize() throws Exception {

        final int numToSend = 450;
        for (int i = 0; i < ITERATIONS; i++) {
            produceMessages(numToSend - 1, 4, "TestQ");

            // ensure we get expiry processing
            Thread.sleep(700);

            // send 1 message priority HIGH
            produceMessages(1, 5, "TestQ");

            Thread.sleep(500);

            LOG.info("On iteration {}", i);

            // consume messages
            ArrayList<Message> consumeList = consumeMessages("TestQ");
            LOG.info("Consumed list {}", consumeList.size());

            // compare lists
            assertFalse("Consumed list should not be empty", consumeList.isEmpty());
            assertEquals("message 1 should be priority high", 5, consumeList.get(0).getJMSPriority());
            for (int j = 1; j < (numToSend - 1); j++) {
                assertEquals("message " + j + " should be priority medium", 4, consumeList.get(j).getJMSPriority());
            }
        }
    }

    @Test(timeout=120000)
    public void testLongLivedPriorityConsumer() throws Exception {

        final int numToSend = 150;

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());
        Connection connection = connectionFactory.createConnection();

        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(new ActiveMQQueue("TestQ"));
            connection.start();

            for (int i = 0; i < ITERATIONS; i++) {
                produceMessages(numToSend - 1, 4, "TestQ");

                // send 1 message priority HIGH
                produceMessages(1, 5, "TestQ");

                Message message = consumer.receive(4000);

                assertEquals("message should be priority high", 5, message.getJMSPriority());
            }
        } finally {
            connection.close();
        }

        ArrayList<Message> consumeList = consumeMessages("TestQ");
        LOG.info("Consumed list {}", consumeList.size());

        for (Message message : consumeList) {
            assertEquals("should be priority medium", 4, message.getJMSPriority());
        }
    }

    @Test(timeout=120000)
    public void testPriorityMessagesWithJmsBrowser() throws Exception {

        final int numToSend = 250;

        for (int i = 0; i < ITERATIONS; i++) {
            produceMessages(numToSend - 1, 4, "TestQ");

            ArrayList<Message> browsed = browseMessages("TestQ");

            LOG.info("Browsed: {}", browsed.size());

            // send 1 message priority HIGH
            produceMessages(1, 5, "TestQ");

            Thread.sleep(500);

            LOG.info("On iteration {}", i);

            Message message = consumeOneMessage("TestQ");
            assertNotNull(message);
            assertEquals(5, message.getJMSPriority());

            // consume messages
            ArrayList<Message> consumeList = consumeMessages("TestQ");
            LOG.info("Consumed list {}", consumeList.size());

            // compare lists
            // assertEquals("Iteration: " + i
            // +", message 1 should be priority high", 5,
            // consumeList.get(0).getJMSPriority());
            for (int j = 1; j < (numToSend - 1); j++) {
                assertEquals("Iteration: " + i + ", message " + j + " should be priority medium", 4, consumeList.get(j).getJMSPriority());
            }
        }
    }

    @Test(timeout=120000)
    public void testJmsBrowserGetsPagedIn() throws Exception {
        final int numToSend = 10;

        for (int i = 0; i < ITERATIONS; i++) {
            produceMessages(numToSend, 4, "TestQ");

            ArrayList<Message> browsed = browseMessages("TestQ");

            LOG.info("Browsed: {}", browsed.size());

            assertEquals(0, browsed.size());

            Message message = consumeOneMessage("TestQ", Session.CLIENT_ACKNOWLEDGE);
            assertNotNull(message);

            browsed = browseMessages("TestQ");

            LOG.info("Browsed: {}", browsed.size());

            assertEquals("see only the paged in for pull", 1, browsed.size());

            // consume messages
            ArrayList<Message> consumeList = consumeMessages("TestQ");
            LOG.info("Consumed list " + consumeList.size());
            assertEquals(numToSend, consumeList.size());
        }
    }

    private void produceMessages(int numberOfMessages, int priority, String queueName) throws Exception {
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());
        connectionFactory.setConnectionIDPrefix("pri-" + priority);
        Connection connection = connectionFactory.createConnection();

        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(new ActiveMQQueue(queueName));
            connection.start();

            for (int i = 0; i < numberOfMessages; i++) {
                BytesMessage m = session.createBytesMessage();
                m.writeBytes(PAYLOAD);
                m.setJMSPriority(priority);
                producer.send(m, Message.DEFAULT_DELIVERY_MODE, m.getJMSPriority(), Message.DEFAULT_TIME_TO_LIVE);
            }
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    private ArrayList<Message> consumeMessages(String queueName) throws Exception {
        ArrayList<Message> returnedMessages = new ArrayList<Message>();

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());
        Connection connection = connectionFactory.createConnection();
        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(queueName));
            connection.start();
            boolean finished = false;

            while (!finished) {
                Message message = consumer.receive(returnedMessages.isEmpty() ? 5000 : 1000);
                if (message == null) {
                    finished = true;
                }

                if (message != null) {
                    returnedMessages.add(message);
                }
            }

            consumer.close();
            return returnedMessages;
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    private Message consumeOneMessage(String queueName) throws Exception {
        return consumeOneMessage(queueName, Session.AUTO_ACKNOWLEDGE);
    }

    private Message consumeOneMessage(String queueName, int ackMode) throws Exception {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());
        Connection connection = connectionFactory.createConnection();
        try {
            Session session = connection.createSession(false, ackMode);
            MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(queueName));
            connection.start();

            return consumer.receive(5000);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    private ArrayList<Message> browseMessages(String queueName) throws Exception {
        ArrayList<Message> returnedMessages = new ArrayList<Message>();

        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectorByScheme("tcp").getPublishableConnectString());
        Connection connection = connectionFactory.createConnection();
        try {
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueBrowser consumer = session.createBrowser(new ActiveMQQueue(queueName));
            connection.start();

            Enumeration<?> enumeration = consumer.getEnumeration();
            while (enumeration.hasMoreElements()) {
                Message message = (Message) enumeration.nextElement();
                returnedMessages.add(message);
            }

            return returnedMessages;
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }

    private BrokerService createBroker() throws Exception {
        BrokerService broker = new BrokerService();
        broker.setDeleteAllMessagesOnStartup(true);

        // add the policy entries
        PolicyMap policyMap = new PolicyMap();
        List<PolicyEntry> entries = new ArrayList<PolicyEntry>();
        PolicyEntry pe = new PolicyEntry();

        pe.setPrioritizedMessages(true);

        pe.setExpireMessagesPeriod(500);

        pe.setMaxPageSize(100);
        pe.setMaxExpirePageSize(0);
        pe.setMaxBrowsePageSize(0);

        pe.setQueuePrefetch(0);
        pe.setLazyDispatch(true);

        pe.setOptimizedDispatch(true);

        pe.setUseCache(false);

        pe.setQueue(">");
        entries.add(pe);
        policyMap.setPolicyEntries(entries);
        broker.setDestinationPolicy(policyMap);

        broker.addConnector("tcp://0.0.0.0:0");
        return broker;
    }
}


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

<title>Uses of Interface javax.swing.ListSelectionModel (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
javax.swing.ListSelectionModel

Packages that use ListSelectionModel

Package
Description

javax.swing

Provides a set of "lightweight"
(all-Java language) components that,
to the maximum degree possible, work the same on all platforms.

javax.swing.plaf.basic

Provides user interface objects built according to the
Basic look and feel.

javax.swing.table

Provides classes and interfaces for dealing with
javax.swing.JTable.

Uses of ListSelectionModel in javax.swing

Classes in javax.swing that implement ListSelectionModel

Modifier and Type
Class and Description

class
DefaultListSelectionModel

Default data model for list selections.

Fields in javax.swing declared as ListSelectionModel

Modifier and Type
Field and Description

protected ListSelectionModel
JTable.selectionModel

The ListSelectionModel of the table, used to keep track of row selections.

Methods in javax.swing that return ListSelectionModel

Modifier and Type
Method and Description

protected ListSelectionModel
JTable.createDefaultSelectionModel()

Returns the default selection model object, which is
 a DefaultListSelectionModel.

protected ListSelectionModel
JList.createSelectionModel()

Returns an instance of DefaultListSelectionModel; called
 during construction to initialize the list's selection model
 property.

ListSelectionModel
JList.getSelectionModel()

Returns the current selection model.

ListSelectionModel
JTable.getSelectionModel()

Returns the ListSelectionModel that is used to maintain row
 selection state.

Methods in javax.swing with parameters of type ListSelectionModel

Modifier and Type
Method and Description

void
JList.setSelectionModel(ListSelectionModel selectionModel)

Sets the selectionModel for the list to a
 non-null ListSelectionModel
 implementation.

void
JTable.setSelectionModel(ListSelectionModel newModel)

Sets the row selection model for this table to newModel
 and registers for listener notifications from the new selection model.

Constructors in javax.swing with parameters of type ListSelectionModel

Constructor and Description

JTable(TableModel dm,
      TableColumnModel cm,
      ListSelectionModel sm)

Constructs a JTable that is initialized with
 dm as the data model, cm as the
 column model, and sm as the selection model.

Uses of ListSelectionModel in javax.swing.plaf.basic

Methods in javax.swing.plaf.basic with parameters of type ListSelectionModel

Modifier and Type
Method and Description

protected void
BasicListUI.paintCell(Graphics g,
         int row,
         Rectangle rowBounds,
         ListCellRenderer cellRenderer,
         ListModel dataModel,
         ListSelectionModel selModel,
         int leadIndex)

Paint one List cell: compute the relevant state, get the "rubber stamp"
 cell renderer component, and then use the CellRendererPane to paint it.

Uses of ListSelectionModel in javax.swing.table

Fields in javax.swing.table declared as ListSelectionModel

Modifier and Type
Field and Description

protected ListSelectionModel
DefaultTableColumnModel.selectionModel

Model for keeping track of column selections

Methods in javax.swing.table that return ListSelectionModel

Modifier and Type
Method and Description

protected ListSelectionModel
DefaultTableColumnModel.createSelectionModel()

Creates a new default list selection model.

ListSelectionModel
TableColumnModel.getSelectionModel()

Returns the current selection model.

ListSelectionModel
DefaultTableColumnModel.getSelectionModel()

Returns the ListSelectionModel that is used to
 maintain column selection state.

Methods in javax.swing.table with parameters of type ListSelectionModel

Modifier and Type
Method and Description

void
TableColumnModel.setSelectionModel(ListSelectionModel newModel)

Sets the selection model.

void
DefaultTableColumnModel.setSelectionModel(ListSelectionModel newModel)

Sets the selection model for this TableColumnModel
  to newModel
  and registers for listener notifications from the new selection
  model.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev

Next

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
namespace Migr8
{
    /// <summary>
    /// Enumeration over available database types
    /// </summary>
    public enum Db
    {
        /// <summary>
        /// Microsoft SQL Server
        /// </summary>
        SqlServer,

        /// <summary>
        /// Postgres
        /// </summary>
        PostgreSql
    }
}


text:
class AbstractExecutorService
{
	public  java.util.concurrent.Future<?> submit(java.lang.Runnable task) {
		task.run();
		return null;
	}

	public <T> java.util.concurrent.Future<T> submit(java.lang.Runnable task, T result) {
		task.run();
		return null;
	}

	public <T> java.util.concurrent.Future<T> submit(java.util.concurrent.Callable<T> task) {
		try{
			task.call();
		}catch(Exception e){}
		return null;
	}

}


text:
define(function (require) {
	var _ = require("underscore"),
	    BaseView = require("baseView"),
	    buttonHelpers = require("utilities/buttonHelpers"),
	    SoundBrowserTemplateString = require("text!templates/soundBrowser/soundBrowser.html"),
	    soundBrowserError = require("text!templates/soundBrowser/soundBrowserError.txt"),
	    FreeSoundCollection = require("collections/freeSoundCollection"),
	    SoundCloudCollection = require("collections/soundCloudCollection"),
	    SoundsView = require("./views/soundsView"),
	    VolumeView = require("application/volumeView"),
	    Alertify = require("alertify");

	var soundsViewColumns = 7,
	    soundsViewRows = 4,
	    soundsViewTotal = soundsViewColumns * soundsViewRows;

	var SoundBrowserView = BaseView.extend({
		className: "sound-browser",
		soundBrowserTemplate: _.template(SoundBrowserTemplateString),
		soundBrowserErrorTemplate: _.template(soundBrowserError.trim()),
		refreshIconClass: "sprite-buttons-refresh-large",
		refreshErrorIconClass: "sprite-buttons-error-large",
		page: 1,

		collectionOptions: {
			defaultFetchOptions: {
				duration: 3,
				limit: soundsViewTotal
			}
		},

		initialize: function () {
			this.enabled = true;

			this.collections = [
				new FreeSoundCollection(this.collectionOptions),
				new SoundCloudCollection(this.collectionOptions)
			];
		},

		events: {
			"change .collection-select": function (event) {
				if (this.collection.className === event.target.value)
					return;

				var collection = _.find(this.collections, function (collection) {
					return collection.className === event.target.value;
				});

				this.changeCollection(collection);
			},

			"click .refresh": "fetch",

			"click .previous": "fetchPrevious",

			"click .next": "fetchNext",

			"change .search-input": "fetch"
		},

		fetch: function () {
			if (this.enabled) {
				this.page = 1;

				this._fetch();
			}
		},

		fetchNext: function () {
			if (this.nextEnabled) {
				this.page += 1;

				this._fetch();
			}
		},

		fetchPrevious: function () {
			if (this.previousEnabled) {
				this.page -= 1;

				this._fetch();
			}
		},

		_fetch: function () {
			var self = this;

			this.refreshButton.data("options").setIcon(this.refreshIconClass);

			this.setEnabled(false);
			this.soundsView.render();

			var data = {
				page: this.page,
				search: this.searchInput.val()
			};

			this.collection.fetch({
				data: data,
				success: function (collection, response) {
					self.setEnabled(true);

					// rendering can be time-intensive.
					// delay it so that the CSS animation can finish smoothly first.
					setTimeout(function () {
						self.soundsView.render(collection);
					}, 100);
				},
				error: function (collection, response) {
					var error, errorContext = {
						name: self.collection.name
					};

					if (response.status === 0)
						errorContext.error = "Network error - the host is unreachable or returning an incorrect response";
					else
						errorContext.error = "Error " + response.status + " - " + response.statusText;

					self.refreshButton.data("options").setIcon(self.refreshErrorIconClass);

					error = self.soundBrowserErrorTemplate(errorContext);

					self.refreshButton.prop("title", error);

					self.setEnabled(true);

					Alertify.dialog.confirm(error, function () {
						self._fetch();
					});
				}
			});
		},

		render: function () {
			this.removeAllChildViews();

			this.$el.html(this.soundBrowserTemplate({
				collections: this.collections,
				_: _
			}));

			var volumeView = this.addChildView(VolumeView, {
				el: this.$(".master-volume:first"),
				model: this.model.soundOutput
			}).render();

			volumeView.on("change", this.volumeViewChange, this);

			this.collectionSelect = buttonHelpers.buttonset(this.$(".collection-select:first"));

			this.refreshButton = buttonHelpers.button(this.$(".refresh:first"), this.refreshIconClass);

			this.nextButton = buttonHelpers.button(this.$(".next:first"), "sprite-buttons-next-large");

			this.previousButton = buttonHelpers.button(this.$(".previous:first"), "sprite-buttons-previous-large");

			this.searchInput = this.$(".search-input:first");

			var sounds = this.$(".sounds:first");

			this.soundsView = this.addChildView(SoundsView, {
				el: sounds,
				columns: soundsViewColumns,
				rows: soundsViewRows
			});

			this.collectionSource = buttonHelpers.button(this.$(".collection-source:first"), "sprite-buttons-source-large");

			// start with a random collection.
			this.changeCollection(this.collections[_.random(this.collections.length - 1)]);

			return this;
		},

		volumeViewChange: function (value) {
			this.eventBus.trigger("setSoundOutputVolume", {
				volume: value
			});
		},

		changeCollection: function (collection) {
			if (this.collection)
				this.$el.removeClass(this.collection.className);

			this.collection = collection;

			this.$el.addClass(this.collection.className);

			this.searchInput.prop("placeholder", "Search " + this.collection.name);

			this.collectionSelect.find("input:radio[value=" + this.collection.className + "]").prop("checked", true).change();

			this.collectionSource.attr("href", this.collection.siteURL);
			this.collectionSource.prop("title", "Visit " + this.collection.name);

			this.fetch();
		},

		setEnabled: function (value) {
			var limit = this.collectionOptions.defaultFetchOptions.limit;
			this.enabled = value;
			this.previousEnabled = this.page > 1;
			this.nextEnabled = this.collection.length >= limit;

			this.collectionSelect.data('options').disable(!value);
			this.searchInput.attr('disabled', !value);
			this.refreshButton.data('options').disable(!value);
			this.previousButton.data('options').disable(!(value && this.previousEnabled));
			this.nextButton.data('options').disable(!(value && this.nextEnabled));
		}
	});

	return SoundBrowserView;
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.palomamobile.android.sdk.media.sampleApp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".RegisterUserActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data android:name="com.palomamobile.android.sdk.ClientId" android:value="@string/palomamobile_client_id" />
        <meta-data android:name="com.palomamobile.android.sdk.Endpoint" android:value="@string/paloma_test_endpoint" />

        <activity
            android:name=".MediaSampleActivity"
            android:label="@string/title_activity_media_sample" >
        </activity>
    </application>

</manifest>


text:
<?php

namespace Parvula\Services;

use Parvula\Session;

class AuthenticationService
{
	/**
	 * @var mixed Token
	 */
	private $token;

	/**
	 * @var Session
	 */
	private $session;

	/**
	 * Constructor
	 *
	 * @param string $name
	 * @param mixed $token
	 */
	public function __construct(Session $session, $token) {
		$this->token = $token;
		$this->session = $session;
	}

	/**
	 * Check if username is currently logged
	 *
	 * @param  string  $username
	 * @return boolean If the given username is currently logged
	 */
	public function isLogged($username) {
		return $this->session->get('username') === $username && $this->session->get('token') === $this->token;
	}

	/**
	 * Log the given user **without checking any password or role**
	 *
	 * @param string $username
	 */
	public function log($username) {
		$this->session->regenerateId();

		// Create a session
		$this->session->set('username', $username);
		$this->session->set('token', $this->token);
	}

	/**
	 * Logout all sessions
	 *
	 * @return bool
	 */
	public function logout() {
		$this->session->regenerateId();

		return $this->session->destroy();
	}
}


text:
package smile.wavelet;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Haifeng Li
 */
public class D4WaveletTest {

    public D4WaveletTest() {
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of filter method, of class D4Wavelet.
     */
    @Test
    public void testFilterD4() {
        System.out.println("filter");
        double[] a = {.2,-.4,-.6,-.5,-.8,-.4,-.9,0,-.2,.1,-.1,.1,.7,.9,0,.3};
        double[] b = a.clone();
        D4Wavelet instance = new D4Wavelet();
        instance.transform(a);
        instance.inverse(a);
        for (int i = 0; i < a.length; i++) {
            assertEquals(b[i], a[i], 1E-7);
        }
    }

}


text:
> Block users from running your app with root permissions.

![screenshot](screenshot.png)

## Install

Install with [npm](https://npmjs.org): `npm install --save sudo-block`

## Example

```js
var sudoBlock = require('sudo-block');
sudoBlock();
```

## API

### sudoBlock(*message*)

When a file containing this function is run with root permissions it will exit and show an error message telling the user how to fix the problem so they don't have to run it with `sudo`. Accepts a custom `message`.

### sudoBlock.isRoot

Boolean indicating whether the current user is `root`.

## License

MIT © [Sindre Sorhus](http://sindresorhus.com)


text:
package com.telepin.cellTower;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

import android.provider.Settings;

public class LocationInfo extends CordovaPlugin {

	public static final String ACTION = "getCID";

	/**
	 * Constructor.
	 */
	public LocationInfo() {
	}

	@Override
	public void initialize(CordovaInterface cordova, CordovaWebView webView) {
		super.initialize(cordova, webView);
	}

	@Override
	public boolean execute(String action, JSONArray data,
			CallbackContext callbackContext) throws JSONException {

		if (action.equals(ACTION)) {

			this.getCID(callbackContext);
			return true;
		}
		return false;

	}

	public void getCID(CallbackContext callbackContext) throws IOException {
		TelephonyManager tm = (TelephonyManager) this.cordova.getActivity()
				.getApplicationContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
		int cellID = location.getCid();
		Log.i("Cell ID", cellID + "");
		if (cellID != null) {
			callbackContext.success(cellID + "");
		} else {
			callbackContext.error("Cell ID is null");
		}

	}

}


text:
package com.tqmall.search.benz.analysis;

import com.tqmall.search.benz.Config;
import com.tqmall.search.commons.nlp.Segment;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;

import java.io.Reader;

/**
 * Created by xing on 16/3/19.
 *
 * @author xing
 */
public class BenzAnalyzer extends Analyzer {

    private final Config config;

    private final Segment segment;

    public BenzAnalyzer(Config config, Segment segment) {
        this.config = config;
        this.segment = segment;
    }

    @Override
    protected Reader initReader(String fieldName, Reader reader) {
        return new BenzCjkCharFilter(reader);
    }

    @Override
    protected TokenStreamComponents createComponents(String fieldName) {
        final Tokenizer tokenizer = new BenzTokenizer(segment);
        TokenStream result = tokenizer;
        Config.AnalysisConfig analysisConfig = config.getSegmentConfig(segment.getName());
        if (analysisConfig.getEnStem() != null) {
            result = analysisConfig.getEnStem().wrapper(result);
        }
        if (analysisConfig.isNeedStopWord()) {
            result = new StopFilter(result, config.getStopWords());
        }
        return new TokenStreamComponents(tokenizer, result);
    }
}


text:
<!doctype html>

    <link rel="stylesheet" href="https://s3.amazonaws.com/codecademy-content/projects/bootstrap.min.css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="style.css">

Bonsai

U say something?

I'm all ears

Create a meme

                    <form role="form">

                            Image URL
                            <input id="image-url" type="text" class="form-control">

                            Top text
                            <input id="top-text" type="text" class="form-control">

                            Bottom text
                            <input id="bottom-text" type="text" class="form-control">

                    </form>