text:
"""****************************************************************************
Copyright (c) 2014 cocos2d-x.org

http://www.cocos2d-x.org

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

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

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

'''
This script will install environment variables needed to by cocos2d-x. It will set these envrironment variables:
* COCOS_CONSOLE_ROOT: used to run cocos console tools, more information about cocos console tools please refer to
https://github.com/cocos2d/cocos2d-console
* NDK_ROOT: used to build android native codes
* ANDROID_SDK_ROOT: used to generate applicatoin on Android through commands
* ANT_ROOT: used to generate applicatoin on Android through commands
* COCOS_X_ROOT: path where cocos2d-x is installed
* COCOS_TEMPLATES_ROOT: path where cocos2d-x's templates are installed

On Max OS X, when start a shell, it will read these files and execute commands in sequence:

~/.bash_profile
~/.bash_login
~/.profile

And it will read only one of them. So we will add environment variable in the same sequence.
Which means that
* add environment variables into ~/.bash_profile if it exists
* otherwise it will the add environment variables into ~/.bash_login if it exists
* otherwise it will the add environment variables into ~/.profile if it exists

Will create ~/.bash_profile when none of them exist, and add environment variables into it.
'''

import os
import sys
import fileinput
import shutil
import subprocess
from optparse import OptionParser

COCOS_CONSOLE_ROOT = 'COCOS_CONSOLE_ROOT'
COCOS_X_ROOT = 'COCOS_X_ROOT'
COCOS_TEMPLATES_ROOT = 'COCOS_TEMPLATES_ROOT'
NDK_ROOT = 'NDK_ROOT'
ANDROID_SDK_ROOT = 'ANDROID_SDK_ROOT'
ANT_ROOT = 'ANT_ROOT'

def _check_python_version():
    major_ver = sys.version_info[0]
    if major_ver > 2:
        print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
               "Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
        return False

    return True

class SetEnvVar(object):

    RESULT_UPDATE_FAILED = -2
    RESULT_ADD_FAILED = -1
    RESULT_DO_NOTHING = 0
    RESULT_UPDATED = 1
    RESULT_ADDED = 2

    MAC_CHECK_FILES = ['.bash_profile', '.bash_login', '.profile']
    LINUX_CHECK_FILES = ['.bashrc']
    ZSH_CHECK_FILES = ['.zshrc']
    RE_FORMAT = r'^export[ \t]+%s=(.+)'

    def __init__(self):
        self.need_backup = True
        self.backup_file = None
        self.current_absolute_path = os.path.dirname(
            os.path.realpath(__file__))
        self.file_used_for_setup = ''

    def _isWindows(self):
        return sys.platform == 'win32'

    def _isLinux(self):
        return sys.platform.startswith('linux')

    def _is_mac(self):
        return sys.platform == 'darwin'

    def _is_zsh(self):
        shellItem = os.environ.get('SHELL')
        if shellItem is not None:
            if len(shellItem) >= 3:
                return shellItem[-3:] == "zsh"
        return False

    def _get_unix_file_list(self):
        file_list = None

        if self._is_zsh():
            file_list = SetEnvVar.ZSH_CHECK_FILES
        elif self._isLinux():
            file_list = SetEnvVar.LINUX_CHECK_FILES
        elif self._is_mac():
            file_list = SetEnvVar.MAC_CHECK_FILES

        return file_list

    def _get_filepath_for_setup(self):
        file_list = self._get_unix_file_list()

        file_to_write = None
        if file_list is None:
            return ''

        home = os.path.expanduser('~')
        for file_name in file_list:
            file_path = os.path.join(home, file_name)
            if os.path.exists(file_path):
                file_to_write = file_path
                break

        if file_to_write is None:
            self.need_backup = False
            file_to_write = os.path.join(home, file_list[0])
            file_obj = open(file_to_write, 'w')
            file_obj.close()

        return file_to_write

    # modify registry table to add an environment variable on windows
    def _set_environment_variable_win32(self, key, value):
        ret = False
        import _winreg
        try:
            env = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                    'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            _winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, value)
            _winreg.FlushKey(env)
            _winreg.CloseKey(env)
            ret = True
        except Exception:
            if env:
                _winreg.CloseKey(env)
            ret = False

        return ret

    def _gen_backup_file(self):
        file_name = os.path.basename(self.file_used_for_setup)
        file_path = os.path.dirname(self.file_used_for_setup)
        backup_file_name = file_name + ".backup"
        path = os.path.join(file_path, backup_file_name)
        i = 1
        while os.path.exists(path):
            backup_file_name = file_name + ".backup%d" % i
            path = os.path.join(file_path, backup_file_name)
            i += 1

        return path

    def _set_environment_variable_unix(self, key, value):

        if self.need_backup:
            # backup the environment file
            self.backup_file = self._gen_backup_file()
            shutil.copy(self.file_used_for_setup, self.backup_file)
            self.need_backup = False

        file = open(self.file_used_for_setup, 'a')
        file.write('\n# Add environment variable %s for cocos2d-x\n' % key)
        file.write('export %s=%s\n' % (key, value))
        file.write('export PATH=$%s:$PATH\n' % key)
        if key == ANDROID_SDK_ROOT:
            file.write(
                'export PATH=$%s/tools:$%s/platform-tools:$PATH\n' % (key, key))
        file.close()
        return True

    def _set_environment_variable(self, key, value):

        print("  -> Add %s environment variable..." % key)
        ret = False
        if self._isWindows():
            ret = self._set_environment_variable_win32(key, value)
        else:
            ret = self._set_environment_variable_unix(key, value)

        if ret:
            print("    ->Added %s=%s\n" % (key, value))
        else:
            print("    ->Add failed\n")

        return ret

    def _search_unix_variable(self, var_name, file_name):
        if not os.path.isfile(file_name):
            return None

        import re
        str_re = SetEnvVar.RE_FORMAT % var_name
        patten = re.compile(str_re)
        ret = None
        for line in open(file_name):
            str1 = line.lstrip(' \t')
            match = patten.match(str1)
            if match is not None:
                ret = match.group(1)

        return ret

    def _find_environment_variable(self, var):
        print("  ->Search for environment variable %s..." % var)
        ret = None
        try:
            ret = os.environ[var]
        except Exception:
            if not self._isWindows():
                file_list = self._get_unix_file_list()

                if file_list is not None:
                    home = os.path.expanduser('~')
                    for name in file_list:
                        path = os.path.join(home, name)
                        ret = self._search_unix_variable(var, path)
                        if ret is not None:
                            break
            else:
                import _winreg
                try:
                    env = None
                    env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                            'Environment',
                                            0,
                                            _winreg.KEY_READ)

                    ret = _winreg.QueryValueEx(env, var)[0]
                    _winreg.CloseKey(env)
                except Exception:
                    if env:
                        _winreg.CloseKey(env)
                    ret = None

        if ret is None:
            print("    ->%s not found\n" % var)
        else:
            print("    ->%s is found : %s\n" % (var, ret))

        return ret

    def _get_input_value(self, var_name):
        ret = raw_input(
            '  ->Please enter the path of %s (or press Enter to skip):' % var_name)
        ret.rstrip(" \t")
        return ret

# python on linux doesn't include Tkinter model, so let user input in terminal
#         if self._isLinux():
#             input_value = raw_input('Couldn\'t find the "%s" envrironment variable. Please enter it: ' % sys_var)
#         else:

# pop up a window to let user select path for ndk root
#             import Tkinter
#             import tkFileDialog

#             self.tmp_input_value = None

#             root = Tkinter.Tk()

#             if sys_var == NDK_ROOT:
#                 root.wm_title('Set NDK_ROOT')
#             else:
#                 root.wm_title('Set ANDROID_SDK_ROOT')

#             def callback():
#                 self.tmp_input_value = tkFileDialog.askdirectory()
#                 root.destroy()

#             if sys_var == NDK_ROOT:
#                 label_content = 'Select path for Android NDK:'
#                 label_help = """
# The Android NDK is needed to develop games for Android.
# For further information, go to:
# http://developer.android.com/tools/sdk/ndk/index.html.

# You can safely skip this step now. You can set the NDK_ROOT later.
#                 """

#             if sys_var == ANDROID_SDK_ROOT:
#                 label_content = 'Select path for Android SDK'
#                 label_help = """
# The Android SDK is needed to develop games for Android.
# For further information, go to:
# https://developer.android.com/tools/sdk/ndk/index.html.

# You can safely skip this step now. You can set the ANDROID_SDK_ROOT later.
#                 """

#             Tkinter.Label(root, text=label_help).pack()
#             Tkinter.Button(root, text=label_content, command=callback).pack()
#             self._center(root)
#             root.mainloop()

#             input_value = self.tmp_input_value
#             self.tmp_input_value = None

#         return input_value

# display a window in center and put it on top
#     def _center(self, win):
#         win.update_idletasks()
#         width = win.winfo_width()
#         height = win.winfo_height()
#         x = (win.winfo_screenwidth() / 2) - (width / 2)
#         y = (win.winfo_screenheight() / 2) - (height / 2)
#         win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
#         win.wm_attributes('-topmost', 1)

    def _check_valid(self, var_name, value):
        ret = False
        if var_name == NDK_ROOT:
            ret = self._is_ndk_root_valid(value)
        elif var_name == ANDROID_SDK_ROOT:
            ret = self._is_android_sdk_root_valid(value)
        elif var_name == ANT_ROOT:
            ret = self._is_ant_root_valid(value)
        else:
            ret = False

        if not ret:
            print(
                '    ->Error: "%s" is not a valid path of %s. Ignoring it.' % (value, var_name))

        return ret

    def _is_ndk_root_valid(self, ndk_root):
        if not ndk_root:
            return False

        ndk_build_path = os.path.join(ndk_root, 'ndk-build')
        if os.path.isfile(ndk_build_path):
            return True
        else:
            return False

    def _is_android_sdk_root_valid(self, android_sdk_root):
        if not android_sdk_root:
            return False

        if self._isWindows():
            android_path = os.path.join(
                android_sdk_root, 'tools', 'android.bat')
        else:
            android_path = os.path.join(android_sdk_root, 'tools', 'android')
        if os.path.isfile(android_path):
            return True
        else:
            return False

    def _is_ant_root_valid(self, ant_root):

        ant_path = ''
        if self._isWindows():
            ant_path = os.path.join(ant_root, 'ant.bat')
        else:
            ant_path = os.path.join(ant_root, 'ant')

        if os.path.isfile(ant_path):
            return True
        else:
            return False

    def remove_dir_from_win_path(self, remove_dir):
        import _winreg
        try:
            env = None
            path = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                    'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            path = _winreg.QueryValueEx(env, 'Path')[0]

            path_lower = path.lower()
            remove_dir = remove_dir.replace('/', '\\')
            remove_dir_lower = remove_dir.lower()
            start_pos = path_lower.find(remove_dir_lower)
            if (start_pos >= 0):
                length = len(remove_dir_lower)
                need_remove = path[start_pos:(start_pos + length)]
                path = path.replace(need_remove, '')
                path = path.replace(';;', ';')
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
            _winreg.CloseKey(env)

            print('  ->Remove directory \"%s\" from PATH!\n' % remove_dir)
        except Exception:
            print('  ->Remove directory \"%s\" from PATH failed!\n' %
                  remove_dir)

    def set_windows_path(self, add_dir):
        ret = False
        import _winreg
        try:
            env = None
            path = None
            env = _winreg.OpenKeyEx(_winreg.HKEY_CURRENT_USER,
                                    'Environment',
                                    0,
                                    _winreg.KEY_SET_VALUE | _winreg.KEY_READ)
            path = _winreg.QueryValueEx(env, 'Path')[0]

            # add variable if can't find it in PATH
            path_lower = path.lower()
            add_dir_lower = add_dir.lower()
            if (path_lower.find(add_dir_lower) == -1):
                path = add_dir + ';' + path
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)

            _winreg.CloseKey(env)
            ret = True
        except Exception:
            if not path:
                path = add_dir
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
                ret = True
            else:
                _winreg.SetValueEx(env, 'Path', 0, _winreg.REG_SZ, path)
                _winreg.FlushKey(env)
                ret = False

            if env:
                _winreg.CloseKey(env)

        if ret:
            print("  ->Add directory \"%s\" into PATH succeed!\n" % add_dir)
        else:
            print("  ->Add directory \"%s\" into PATH failed!\n" % add_dir)

    def set_console_root(self):
        print("->Check environment variable %s" % COCOS_CONSOLE_ROOT)
        cocos_consle_root = os.path.join(
            self.current_absolute_path, 'tools', 'cocos2d-console', 'bin')
        old_dir = self._find_environment_variable(COCOS_CONSOLE_ROOT)
        if old_dir is None:
            # add environment variable
            if self._isWindows():
                self.set_windows_path(cocos_consle_root)

            self._set_environment_variable(
                COCOS_CONSOLE_ROOT, cocos_consle_root)
        else:
            if old_dir == cocos_consle_root:
                # is same with before, nothing to do
                return

            # update the environment variable
            if self._isWindows():
                self.remove_dir_from_win_path(old_dir)
                self.set_windows_path(cocos_consle_root)

            self._force_update_env(COCOS_CONSOLE_ROOT, cocos_consle_root)
    def set_cocos_x_root(self):
        print("->Check environment variable %s" % COCOS_X_ROOT)
        cocos_x_root = os.path.dirname(self.current_absolute_path)
        old_dir = self._find_environment_variable(COCOS_X_ROOT)
        if old_dir is None:
            # add environment variable
            if self._isWindows():
                self.set_windows_path(cocos_x_root)

            self._set_environment_variable(COCOS_X_ROOT, cocos_x_root)
        else:
            if old_dir == cocos_x_root:
                # is same with before, nothing to do
                return

            # update the environment variable
            if self._isWindows():
                self.remove_dir_from_win_path(old_dir)
                self.set_windows_path(cocos_x_root)

            self._force_update_env(COCOS_X_ROOT, cocos_x_root)
    def set_templates_root(self):
        print("->Check environment variable %s" % COCOS_TEMPLATES_ROOT)
        cocos_templates_root = os.path.join(self.current_absolute_path, 'templates')
        old_dir = self._find_environment_variable(COCOS_TEMPLATES_ROOT)
        if old_dir is None:
            # add environment variable
            if self._isWindows():
                self.set_windows_path(cocos_templates_root)

            self._set_environment_variable(COCOS_TEMPLATES_ROOT, cocos_templates_root)
        else:
            if old_dir == cocos_templates_root:
                # is same with before, nothing to do
                return

            # update the environment variable
            if self._isWindows():
                self.remove_dir_from_win_path(old_dir)
                self.set_windows_path(cocos_templates_root)

            self._force_update_env(COCOS_TEMPLATES_ROOT, cocos_templates_root)

    def _force_update_unix_env(self, var_name, value):
        import re
        home = os.path.expanduser('~')
        str_re = SetEnvVar.RE_FORMAT % var_name
        patten = re.compile(str_re)
        replace_str = 'export %s=%s\n' % (var_name, value)

        file_list = SetEnvVar.MAC_CHECK_FILES
        if self._isLinux():
            file_list = SetEnvVar.LINUX_CHECK_FILES

        print("  ->Update variable %s in files %s" %
              (var_name, str(file_list)))
        variable_updated = False
        for file_name in file_list:
            path = os.path.join(home, file_name)
            if os.path.isfile(path):
                lines = []
                # read files
                need_over_write = False
                file_obj = open(path, 'r')
                for line in file_obj:
                    str_temp = line.lstrip(' \t')
                    match = patten.match(str_temp)
                    if match is not None:
                        variable_updated = True
                        need_over_write = True
                        lines.append(replace_str)
                    else:
                        lines.append(line)
                file_obj.close()

                # rewrite file
                if need_over_write:
                    file_obj = open(path, 'w')
                    file_obj.writelines(lines)
                    file_obj.close()
                    print("    ->File %s updated!" % path)

        # nothing updated, should add variable
        if not variable_updated:
            print("\n  ->No files updated, add variable %s instead!" %
                  var_name)
            ret = self._set_environment_variable(var_name, value)
        else:
            ret = True

        return ret

    def _force_update_env(self, var_name, value):
        ret = False
        if self._isWindows():
            print("  ->Force update environment variable %s" % var_name)
            ret = self._set_environment_variable_win32(var_name, value)
            if not ret:
                print("    ->Failed!")
            else:
                print("    ->Succeed : %s=%s" % (var_name, value))
        else:
            ret = self._force_update_unix_env(var_name, value)
        return ret

    def _get_ant_path(self):
        return self._get_sdkpath_for_cmd("ant", False)

    def _get_androidsdk_path(self):
        return self._get_sdkpath_for_cmd("android")

    def _get_ndkbuild_path(self):
        return self._get_sdkpath_for_cmd("ndk-build", False)

    def _get_sdkpath_for_cmd(self, cmd, has_bin_folder=True):
        ret = None
        print("  ->Search for command " + cmd + " in system...")
        if not self._isWindows():
            import commands
            state, result = commands.getstatusoutput("which " + cmd)
            if state == 0:
                ret = os.path.realpath(result)
                ret = os.path.dirname(ret)
                # Use parent folder if has_bin_folder was set
                if has_bin_folder:
                    ret = os.path.dirname(ret)

        if ret is not None:
            print("    ->Path " + ret + " was found\n")
        else:
            print("    ->Command " + cmd + " not found\n")
        return ret

    def _find_value_from_sys(self, var_name):
        if var_name == ANT_ROOT:
            return self._get_ant_path()
        elif var_name == NDK_ROOT:
            return self._get_ndkbuild_path()
        elif var_name == ANDROID_SDK_ROOT:
            return self._get_androidsdk_path()
        else:
            return None

    def set_variable(self, var_name, value):
        print("->Check environment variable %s" % var_name)
        find_value = self._find_environment_variable(var_name)
        var_found = (find_value is not None)
        action_none = 0
        action_add = 1
        action_update = 2

        need_action = action_none
        if var_found:
            if value and self._check_valid(var_name, value):
                # should update
                need_action = action_update
            else:
                # do nothing
                need_action = action_none
        else:
            if not value:
                # find the command path in system
                value = self._find_value_from_sys(var_name)

            if not value:
                value = self._get_input_value(var_name)

            if value and self._check_valid(var_name, value):
                # should add variable
                need_action = action_add
            else:
                # do nothing
                need_action = action_none

        if need_action == action_none:
            # do nothing
            return SetEnvVar.RESULT_DO_NOTHING
        elif need_action == action_add:
            # add variable
            if self._set_environment_variable(var_name, value):
                return SetEnvVar.RESULT_ADDED
            else:
                return SetEnvVar.RESULT_ADD_FAILED
        elif need_action == action_update:
            # update variable
            if self._force_update_env(var_name, value):
                # update succeed
                return SetEnvVar.RESULT_UPDATED
            else:
                # update failed
                return SetEnvVar.RESULT_UPDATE_FAILED
        else:
            return SetEnvVar.RESULT_DO_NOTHING

    def set_environment_variables(self, ndk_root, android_sdk_root, ant_root, quiet):

        print('\nSetting up cocos2d-x...')

        self.file_used_for_setup = self._get_filepath_for_setup()

        self.set_console_root()
        self.set_cocos_x_root()
        self.set_templates_root()

        if self._isWindows():
            print(
                '->Configuration for Android platform only, you can also skip and manually edit your environment variables\n')
        else:
            print('->Configuration for Android platform only, you can also skip and manually edit "%s"\n' %
                  self.file_used_for_setup)
        if(quiet) :
            ndk_ret = self.set_variable(NDK_ROOT, ndk_root)
            sdk_ret = self.set_variable(ANDROID_SDK_ROOT, android_sdk_root)
            ant_ret = self.set_variable(ANT_ROOT, ant_root)

        # tip the backup file
        if (self.backup_file is not None) and (os.path.exists(self.backup_file)):
            print('\nA backup file \"%s\" is created for \"%s\".' %
                  (self.backup_file, self.file_used_for_setup))

        if self._isWindows():
            print(
                '\nPlease restart the terminal or restart computer to make added system variables take effect\n')
        else:
            print('\nPlease execute command: "source %s" to make added system variables take effect\n' %
                  self.file_used_for_setup)

if __name__ == '__main__':
    if not _check_python_version():
        exit()

    parser = OptionParser()
    parser.add_option(
        '-n', '--ndkroot', dest='ndk_root', help='directory of ndk root')
    parser.add_option('-a', '--androidsdkroot',
                      dest='android_sdk_root', help='directory of android sdk root')
    parser.add_option(
        '-t', '--antroot', dest='ant_root', help='directory that contains ant/ant.bat')

    parser.add_option(
        '-q', '--quiet', dest='quiet',action="store_false", default = True, help='setup without setting NDK,SDK,ANT')
    opts, args = parser.parse_args()

    # set environment variables
    env = SetEnvVar()
    env.set_environment_variables(
        opts.ndk_root, opts.android_sdk_root, opts.ant_root, opts.quiet)

    if env._isWindows():
        import ctypes
        HWND_BROADCAST = 0xFFFF
        WM_SETTINGCHANGE = 0x1A
        SMTO_ABORTIFHUNG = 0x0002
        result = ctypes.c_long()
        SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
        SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0,
                            u'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result))


text:
require "Array"

module ArrayTree
end

redpajama_set_name: RedPajamaGithub


text:
require "rails_helper"

describe "Managing an HD DNA Session", type: :request do
  describe "GET show" do
    it "renders successfully" do
      dna_session = create(:hd_dna_session)
      get patient_hd_session_path(patient_id: dna_session.patient, id: dna_session.id)

      expect(response).to be_successful
    end

    context "when the session is still mutable" do
      it "renders successfully" do
        dna_session = create(:hd_dna_session)
        get edit_patient_hd_session_path(patient_id: dna_session.patient, id: dna_session.id)

        expect(response).to be_successful
      end
    end

    context "when the session is no longer mutable" do
      it "redirects to #show with a flash message", type: :system do
        dna_session = travel_to(Time.zone.now - 1.day) do
          create(:hd_dna_session)
        end

        route_params = { patient_id: dna_session.patient, id: dna_session.id }
        show_path = patient_hd_session_path(route_params)
        login_as_clinical
        edit_path = edit_patient_hd_session_path(route_params)

        visit edit_path

        # Disallows edit and redirect to the show page
        expect(page).to have_current_path(show_path)
      end
    end
  end
end


text:
package com.inari.dash.game.cave.unit.rockford;

import com.inari.commons.GeomUtils;
import com.inari.commons.geom.Direction;
import com.inari.commons.geom.Position;
import com.inari.dash.game.cave.CaveSystem.CaveState;
import com.inari.dash.game.cave.unit.EUnit;
import com.inari.dash.game.cave.unit.UnitAspect;
import com.inari.dash.game.cave.unit.UnitController;
import com.inari.dash.game.cave.unit.UnitType;
import com.inari.dash.game.cave.unit.action.UnitActionType;
import com.inari.dash.game.cave.unit.rockford.Rockford.StateChangeEnum;
import com.inari.dash.game.cave.unit.rockford.Rockford.StateEnum;
import com.inari.firefly.FFInitException;
import com.inari.firefly.audio.AudioSystemEvent;
import com.inari.firefly.audio.AudioSystemEvent.Type;
import com.inari.firefly.control.action.ActionSystemEvent;
import com.inari.firefly.control.state.StateSystem;
import com.inari.firefly.control.state.StateSystemEvent;
import com.inari.firefly.entity.EEntity;
import com.inari.firefly.graphics.tile.ETile;
import com.inari.firefly.prototype.Prototype;
import com.inari.firefly.system.FireFlyApp;
import com.inari.firefly.system.external.FFInput;
import com.inari.firefly.system.external.FFInput.ButtonType;

public final class RFController extends UnitController {

    private static final int ENTERING_ANIMATION_DURATION = 5;
    private static final int APPEARING_ANIMATION_DURATION = 6;
    private static final int IDLE_BLINKING_DURATION = 6;
    private static final int IDLE_FRETFUL_DURATION = 20;

    private FFInput input;
    private StateSystem stateSystem;

    private Position currentPos = new Position();
    private Position nextPos = new Position();

    protected RFController( int id ) {
        super( id );
    }

    @Override
    public final void init() throws FFInitException {
        super.init();

        input = context.getInput();
        stateSystem = context.getSystem( StateSystem.SYSTEM_KEY );
    }

    @Override
    protected final void update( int entityId ) {
        Rockford rfHandle = context.getSystemComponent( Prototype.TYPE_KEY, UnitType.ROCKFORD.name(), Rockford.class );
        CaveState caveState = caveService.getCaveState();
        if ( caveState == CaveState.WON || caveState == CaveState.INIT ) {
            return;
        }

        EUnit unit = context.getEntityComponent( entityId, EUnit.TYPE_KEY );
        EEntity entity = context.getEntityComponent( entityId, EEntity.TYPE_KEY );
        String state = stateSystem.getCurrentState( Rockford.NAME );

        if ( StateEnum.APPEARING.is( state ) || StateEnum.ENTERING.is( state ) ) {
            unit.incrementAnimationCount();
            int animationCount = unit.getAnimationCount();
            if ( StateEnum.ENTERING.is( state ) && animationCount > ENTERING_ANIMATION_DURATION ) {
                unit.resetAnimationCount();
                context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.ENTERING_APPEARING.name() ) );
                context.notify( new AudioSystemEvent( rfHandle.inSoundId, Type.PLAY_SOUND ) );
                return;
            }
            if ( StateEnum.APPEARING.is( state ) && animationCount > APPEARING_ANIMATION_DURATION ) {
                unit.resetAnimationCount();
                context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.APPEARING_IDLE.name() ) );
                entity.setAspects( EEntity.ENTITY_ASPECT_GROUP.createAspects( UnitAspect.ALIVE, UnitAspect.DESTRUCTIBLE  ) );
                return;
            }
            return;
        }

        if ( !caveService.hasAspect( entityId, UnitAspect.ALIVE ) ) {
            return;
        }

        if ( unit.isHit() ) {
            unit.setChangeTo( UnitType.SPACE );
            context.notify( new ActionSystemEvent( UnitActionType.EXPLODE.index(), entityId ) );
            return;
        }

        if ( input.isPressed( ButtonType.UP ) ) {
            unit.setMovement( Direction.NORTH );
        } else if ( input.isPressed( ButtonType.RIGHT ) ) {
            unit.setMovement( Direction.EAST );
        } else if ( input.isPressed( ButtonType.DOWN ) ) {
            unit.setMovement( Direction.SOUTH );
        } else if ( input.isPressed( ButtonType.LEFT ) ) {
            unit.setMovement( Direction.WEST );
        } else {
            unit.setMovement( Direction.NONE );
        }

        if ( unit.getMovement() == Direction.NONE ) {
            if ( StateEnum.BLINKING.is( state ) || StateEnum.FRETFUL.is( state ) ) {
                unit.incrementAnimationCount();
                int animationCount = unit.getAnimationCount();
                if ( StateEnum.BLINKING.is( state ) && animationCount > IDLE_BLINKING_DURATION ) {
                    context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.BLINKING_IDLE.name() ) );
                    unit.resetAnimationCount();
                    return;
                }
                if ( StateEnum.FRETFUL.is( state ) && animationCount > IDLE_FRETFUL_DURATION ) {
                    context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.FRETFUL_IDLE.name() ) );
                    unit.resetAnimationCount();
                    return;
                }
                return;
            } else if ( !StateEnum.IDLE.is( state ) ) {
                context.notify( StateSystemEvent.createDoStateChangeEventTo( Rockford.NAME, StateEnum.IDLE.name() ) );
            }
            if ( FireFlyApp.RANDOM.nextInt( 100 ) < 5 ) {
                context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.IDLE_BLINKING.name() ) );
                return;
            }
            if ( FireFlyApp.RANDOM.nextInt( 100 ) < 3 ) {
                context.notify( StateSystemEvent.createDoStateChangeEvent( Rockford.NAME, StateChangeEnum.IDLE_FRETFUL.name() ) );
                return;
            }

            return;
        }

        ETile tile = context.getEntityComponent( entityId, ETile.TYPE_KEY );
        currentPos.x = tile.getGridXPos();
        currentPos.y = tile.getGridYPos();
        nextPos.x = currentPos.x;
        nextPos.y = currentPos.y;
        Direction move = unit.getMovement();
        boolean grabbing = input.isPressed( ButtonType.FIRE_1 );

        if ( ( move == Direction.WEST || move == Direction.NORTH ) && !StateEnum.LEFT.is( state ) ) {
            context.notify( StateSystemEvent.createDoStateChangeEventTo( Rockford.NAME, StateEnum.LEFT.name() ) );
        } else if ( ( move == Direction.EAST || move == Direction.SOUTH ) && !StateEnum.RIGHT.is( state ) ) {
            context.notify( StateSystemEvent.createDoStateChangeEventTo( Rockford.NAME, StateEnum.RIGHT.name() ) );
        }

        GeomUtils.movePosition( nextPos, move, 1, true );
        int nextEntityId = caveService.getEntityId( nextPos.x, nextPos.y );
        EUnit nextUnit = context.getEntityComponent( nextEntityId, EUnit.TYPE_KEY );
        EEntity nextEntity = context.getEntityComponent( nextEntityId, EEntity.TYPE_KEY );
        UnitType nextType = nextUnit.getUnitType();

        if ( nextEntity.hasAspect( UnitAspect.WALKABLE ) ) {
           if ( nextType == UnitType.DIAMOND ) {
               context.notify( new ActionSystemEvent( UnitActionType.COLLECT.index(), nextEntityId ) );
               context.notify( new AudioSystemEvent( rfHandle.collectSoundId, Type.PLAY_SOUND ) );
           } else if ( nextType == UnitType.SPACE ) {
               if ( !grabbing ) {
                   context.notify( new AudioSystemEvent( rfHandle.spaceSoundId, Type.PLAY_SOUND ) );
               }
           } else {
               context.notify( new AudioSystemEvent( rfHandle.sandSoundId, Type.PLAY_SOUND ) );
           }

           if ( grabbing ) {
               if ( nextType != UnitType.SPACE ) {
                   caveService.deleteUnit( nextPos.x, nextPos.y );
                   caveService.createOne( nextPos.x, nextPos.y, UnitType.SPACE );
               }
           } else {
               context.notify( new ActionSystemEvent( UnitActionType.MOVE.index(), entityId ) );
           }
           return;
        }

        if ( GeomUtils.isHorizontal( move ) && ( nextType == UnitType.ROCK ) ) {
            pushRock( move, grabbing, entityId );
            return;
        }
    }

    private final void pushRock( Direction move, boolean grabbing, int rockfordId ) {
        int rockEntityId = caveService.getEntityId( nextPos.x, nextPos.y );
        GeomUtils.movePosition( nextPos, move, 1, true );
        if ( !caveService.isOfType( nextPos.x, nextPos.y, UnitType.SPACE ) ) {
            return;
        }

        if ( FireFlyApp.RANDOM.nextInt( 100 ) < 20 ) {
            EUnit unit = context.getEntityComponent( rockEntityId, EUnit.TYPE_KEY );
            unit.setMovement( move );
            context.notify( new ActionSystemEvent( UnitActionType.MOVE.index(), rockEntityId ) );
            if ( !grabbing ) {
                context.notify( new ActionSystemEvent( UnitActionType.MOVE.index(), rockfordId ) );
            }
            unit.setMovement( Direction.NONE );
            context.notify( new AudioSystemEvent( getUnit( UnitType.ROCK ).getSoundId(), Type.PLAY_SOUND ) );
        }
    }

}


text:
package com.kindredgames.wordclues.amazon.purchase;

/**
 * Represents the state of a request which goes from SENT, RECEIVED to
 * FULFILLED.
 */
public enum RequestState {

    NOT_AVAILABLE(0), //
    SENT(1), //
    RECEIVED(2), //
    FULFILLED(3);

    private int state;

    private RequestState(int state) {
        this.state = state;
    }

    public int getState() {
        return state;
    }

    /**
     * Gets RequestState enum by int state.
     */
    public static RequestState valueOf(int state) {
        for (RequestState requestState : values()) {
            if (requestState.getState() == state) {
                return requestState;
            }
        }
        return null;
    }
}


text:
Install Mono and F# and enjoy!

- [F# on Linux](http://fsharp.org/use/linux/)
- [F# on Mac](http://fsharp.org/use/mac/)
  - Alternatively use homebrew with `brew install fsharp` and `export MONO_GAC_PREFIX="/usr/local"`
- [F# on Windows](http://fsharp.org/use/windows/)
  - Note: if you use Visual Studio, make sure the Linux build scripts work as well.


text:
package com.orientechnologies.orient.core.config;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Represents a context configuration where custom setting could be defined for the context only. If not defined, globals will be
 * taken.
 *
 * @author Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 */
public class OContextConfiguration implements Serializable {
  private final Map<String, Object> config = new ConcurrentHashMap<String, Object>();

  /**
   * Empty constructor to create just a proxy for the OGlobalConfiguration. No values are setted.
   */
  public OContextConfiguration() {
  }

  /**
   * Initializes the context with custom parameters.
   *
   * @param iConfig
   *          Map of parameters of type Map<String, Object>.
   */
  public OContextConfiguration(final Map<String, Object> iConfig) {
    this.config.putAll(iConfig);
  }

  public OContextConfiguration(final OContextConfiguration iParent) {
    if (iParent != null)
      config.putAll(iParent.config);
  }

  public Object setValue(final OGlobalConfiguration iConfig, final Object iValue) {
    if (iValue == null)
      return config.remove(iConfig.getKey());

    return config.put(iConfig.getKey(), iValue);
  }

  public Object setValue(final String iName, final Object iValue) {
    if (iValue == null)
      return config.remove(iName);

    return config.put(iName, iValue);
  }

  public Object getValue(final OGlobalConfiguration iConfig) {
    if (config != null && config.containsKey(iConfig.getKey()))
      return config.get(iConfig.getKey());
    return iConfig.getValue();
  }

  @SuppressWarnings("unchecked")
  public <T> T getValue(final String iName, final T iDefaultValue) {
    if (config != null && config.containsKey(iName))
      return (T) config.get(iName);

    final String sysProperty = System.getProperty(iName);
    if (sysProperty != null)
      return (T) sysProperty;

    return iDefaultValue;
  }

  public boolean getValueAsBoolean(final OGlobalConfiguration iConfig) {
    final Object v = getValue(iConfig);
    if( v == null )
      return false;
    return v instanceof Boolean ? ((Boolean) v).booleanValue() : Boolean.parseBoolean(v.toString());
  }

  public String getValueAsString(final String iName, final String iDefaultValue) {
    return getValue(iName, iDefaultValue);
  }

  public String getValueAsString(final OGlobalConfiguration iConfig) {
    final Object v = getValue(iConfig);
    if (v == null)
      return null;
    return v.toString();
  }

  public int getValueAsInteger(final OGlobalConfiguration iConfig) {
    final Object v = getValue(iConfig);
    if (v == null)
      return 0;
    return v instanceof Integer ? ((Integer) v).intValue() : Integer.parseInt(v.toString());
  }

  public long getValueAsLong(final OGlobalConfiguration iConfig) {
    final Object v = getValue(iConfig);
    if (v == null)
      return 0;
    return v instanceof Long ? ((Long) v).intValue() : Long.parseLong(v.toString());
  }

  public float getValueAsFloat(final OGlobalConfiguration iConfig) {
    final Object v = getValue(iConfig);
    if (v == null)
      return 0;
    return v instanceof Float ? ((Float) v).floatValue() : Float.parseFloat(v.toString());
  }

  public int getContextSize() {
    return config.size();
  }

  public java.util.Set<String> getContextKeys() {
    return config.keySet();
  }
}


text:
/* Insert sytle here */

/*
Flatly theme colors:
#E74C3C = red;
#F39C12 = yellow;
#3498DB = light blue;
#18BC9C = sea green;
#2C3E50 = dark blue;
*/

/* navbar icon colors */
.logo-icon1 {
  color: #F39C12;
}

.logo-icon2 {
  color: #3498DB;
}

.logo-icon3 {
  color: #18BC9C;
}

/* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}

body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  line-height: 60px; /* Vertically center the text there */
  background-color: #2C3E50;
  text-align: center;
  color: white;
}

/* Links and their hovers into light blue */
/*
.postLink, .postLink:hover{
  color: #3498DB;
}
*/

/* labels for topics */
/*
Hockey Analytics
Academic
R
E-Prime
EEG
Power Play
*/

/* About Me */
.prof-pic{
  text-align: center;
  padding-top: 10px;
}

.social-icons ul {
  width: 100%;
  text-align: center;
  padding-right: 25px;
  padding-top: 10px;
}

.social-icons ul li {
  display: inline-block;
}

.social-icons ul li a i {
  font-size: 25px;
}

.schoollogo{
  float: none;
  display: inline-block;
  vertical-align: middle;
}

.progress-label {
    margin-right: 1em;
    line-height: 15px;
    font-size: 15px;
    text-align: center;
}

 .progress-skill {
   height: 15px;
 }


text:
Template.configureLoginServiceDialogForEve.helpers({
  siteUrl: function () {
    return Meteor.absoluteUrl();
  }
});

Template.configureLoginServiceDialogForEve.fields = function () {
  return [
    {property: 'clientId', label: 'Client ID'},
    {property: 'secret', label: 'App Secret'}
  ];
};


text:
Titanium.UI.setBackgroundColor('#000');

function isAndroid() {
	return (Ti.Platform.name == 'android');
}

function setupSettings() {

	var view = Ti.UI.createView({});

	var tableView = Ti.UI.createTableView({
			style:										Ti.UI.iPhone.TableViewStyle.GROUPED,
			scrollable:									true,
	});

	var firstSection = Ti.UI.createTableViewSection({ headerTitle: 'First',
													  footerTitle: 'Lots of contextual information'});

	var firstRow = Ti.UI.createTableViewRow({title: 'A setting',
											 hasChild: true});

	var secondRow = Ti.UI.createTableViewRow({height: 50});

	var theTitle = Ti.UI.createLabel({
        text:'The title',
        font:{fontSize:'16',fontWeight:'bold'},
        minimumFontSize:'12',
        textAlign:'left',
        top:'2',
        left:'10',
        height:'20'
     });

     secondRow.add(theTitle);

var theSnippet =  Titanium.UI.createLabel({
        text:'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor',
        font:{fontSize:'11',fontWeight:'normal'},
            textAlign:'left',
        color:'#666',
        bottom:'0',
        left:'10',
        height:'26'
     });

     secondRow.add(theSnippet);

	firstSection.add(firstRow);
	firstSection.add(secondRow);
	tableView.setData([firstSection]);
	view.add(tableView);
	return view;
}

function addMenu(win) {

	if (isAndroid()) {
	var activity = win.activity;

	activity.onCreateOptionsMenu = function(e){

 	var firstItem = e.menu.add({ title: 'First Item' });
	firstItem.addEventListener("click", function(e) {Ti.API.debug('First Item'); });

 	var secondItem = e.menu.add({ title: 'Second Item'});
	secondItem.addEventListener("click", function(e) {Ti.API.warn('Second Item'); });

	var thirdItem = e.menu.add({ title: 'Third Item'});
	thirdItem.addEventListener("click", function(e) {alert('Third Item'); });
	}
};
}

function rightButton(win) {
    if (!isAndroid()) {

      var right = Ti.UI.createButton({
         systemButton:Ti.UI.iPhone.SystemButton.INFO_LIGHT
      });
      right.addEventListener('click',function()
      {
         alert('button clicked!');
      });
      win.setRightNavButton(right);
   }
}

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({
    title:'Tab 1',
    backgroundColor:'#fff'
});
var tab1 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Tab 1',
    window:win1
});

var label1 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 1',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

win1.add(label1);
addMenu(win1);
rightButton(win1);
//
// create controls tab and root window
//
var win2 = Titanium.UI.createWindow({
    title:'Tab 2',
    backgroundColor:'#fff'
});
var tab2 = Titanium.UI.createTab({
    icon:'KS_nav_ui.png',
    title:'Tab 2',
    window:win2
});

var label2 = Titanium.UI.createLabel({
	color:'#999',
	text:'I am Window 2',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});

var view = Ti.UI.createView({
	top:20,
	bottom:'50%',
	left:20,
	right:'50%',
	backgroundColor:'red'
});

win2.add(view);

var button1 = Titanium.UI.createButton({
	color:'#000',
	title:'Button in View',
	textAlign:'center',
	top:10,
	left:10
});

button1.addEventListener('click', function(e) {alert('You clicked me!')});

view.add(button1);
win2.add(label2);

var win3 = Ti.UI.createWindow({
	backgroundColor:'black'
});

var tab3 = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Vertical Stack',
    window:win3
});

var winSettings = Ti.UI.createWindow({
});

var tabSettings = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'Settings',
    window:winSettings
});

winSettings.add(setupSettings());

var view = Ti.UI.createView({layout:'vertical'});
var textField = Ti.UI.createTextField({backgroundColor:'white',
                                       hintText:'Here is a hint.',
                                       height:40,
                                       top:50,
                                       width:200});
view.add(textField);

win3.add(view);
//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);
tabGroup.addTab(tab3);
tabGroup.addTab(tabSettings);

// open tab group
tabGroup.open();


text:
import datetime
import os

from cryptography import x509
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509 import oid

def _new_cert(issuer=None, is_issuer=False, serial_number=None, **subject):
    backend = backends.default_backend()
    private_key = rsa.generate_private_key(
        public_exponent=65537, key_size=4096, backend=backend
    )
    public_key = private_key.public_key()
    subject = x509.Name(
        [
            x509.NameAttribute(getattr(oid.NameOID, key.upper()), value)
            for key, value in subject.items()
        ]
    )
    builder = (
        x509.CertificateBuilder()
        .subject_name(subject)
        .public_key(public_key)
        .serial_number(serial_number or int.from_bytes(os.urandom(8), "big"))
    )
    if issuer:
        issuer_cert, signing_key = issuer
        builder = (
            builder.issuer_name(issuer_cert.subject)
            .not_valid_before(issuer_cert.not_valid_before)
            .not_valid_after(issuer_cert.not_valid_after)
        )
        aki_ext = x509.AuthorityKeyIdentifier(
            key_identifier=issuer_cert.extensions.get_extension_for_class(
                x509.SubjectKeyIdentifier
            ).value.digest,
            authority_cert_issuer=[x509.DirectoryName(issuer_cert.subject)],
            authority_cert_serial_number=issuer_cert.serial_number,
        )
    else:
        signing_key = private_key
        builder = (
            builder.issuer_name(subject)
            .not_valid_before(
                datetime.datetime.today() - datetime.timedelta(days=1)
            )
            .not_valid_after(
                datetime.datetime.today() + datetime.timedelta(weeks=1000)
            )
        )
        aki_ext = x509.AuthorityKeyIdentifier.from_issuer_public_key(
            public_key
        )
    if is_issuer:
        builder = (
            builder.add_extension(
                x509.BasicConstraints(ca=True, path_length=None),
                critical=False,
            )
            .add_extension(
                x509.SubjectKeyIdentifier.from_public_key(public_key),
                critical=False,
            )
            .add_extension(
                aki_ext,
                critical=False,
            )
        )
    else:
        builder = (
            builder.add_extension(
                x509.KeyUsage(
                    digital_signature=True,
                    content_commitment=False,
                    key_encipherment=True,
                    data_encipherment=False,
                    key_agreement=False,
                    key_cert_sign=False,
                    crl_sign=False,
                    encipher_only=False,
                    decipher_only=False,
                ),
                critical=False,
            )
            .add_extension(
                x509.BasicConstraints(ca=False, path_length=None),
                critical=False,
            )
            .add_extension(
                x509.ExtendedKeyUsage([oid.ExtendedKeyUsageOID.SERVER_AUTH]),
                critical=False,
            )
            .add_extension(
                x509.SubjectAlternativeName([x509.DNSName("localhost")]),
                critical=False,
            )
            .add_extension(
                x509.SubjectKeyIdentifier.from_public_key(public_key),
                critical=False,
            )
            .add_extension(
                aki_ext,
                critical=False,
            )
        )
    certificate = builder.sign(
        private_key=signing_key,
        algorithm=hashes.SHA256(),
        backend=backend,
    )
    return certificate, private_key

def _write_cert(path, cert_key_pair, password=None):
    certificate, private_key = cert_key_pair
    if password:
        encryption = serialization.BestAvailableEncryption(password)
    else:
        encryption = serialization.NoEncryption()
    with open(path + ".key.pem", "wb") as f:
        f.write(
            private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=encryption,
            )
        )
    with open(path + ".cert.pem", "wb") as f:
        f.write(
            certificate.public_bytes(
                encoding=serialization.Encoding.PEM,
            )
        )

def new_ca(path, **subject):
    cert_key_pair = _new_cert(is_issuer=True, **subject)
    _write_cert(path, cert_key_pair)
    return cert_key_pair

def new_cert(
    path, ca_cert_key_pair, password=None, is_issuer=False, **subject
):
    cert_key_pair = _new_cert(
        issuer=ca_cert_key_pair, is_issuer=is_issuer, **subject
    )
    _write_cert(path, cert_key_pair, password)
    return cert_key_pair

def new_crl(path, issuer, cert):
    issuer_cert, signing_key = issuer
    revoked_cert = (
        x509.RevokedCertificateBuilder()
        .serial_number(cert[0].serial_number)
        .revocation_date(datetime.datetime.today())
        .build()
    )
    builder = (
        x509.CertificateRevocationListBuilder()
        .issuer_name(issuer_cert.subject)
        .last_update(datetime.datetime.today())
        .next_update(datetime.datetime.today() + datetime.timedelta(days=1))
        .add_revoked_certificate(revoked_cert)
    )
    crl = builder.sign(private_key=signing_key, algorithm=hashes.SHA256())
    with open(path + ".crl.pem", "wb") as f:
        f.write(crl.public_bytes(encoding=serialization.Encoding.PEM))

def main():
    ca = new_ca(
        "ca",
        country_name="US",
        state_or_province_name="California",
        locality_name="San Francisco",
        organization_name="EdgeDB Inc.",
        organizational_unit_name="EdgeDB tests",
        common_name="EdgeDB test root ca",
        email_address="hello@edgedb.com",
    )
    server = new_cert(
        "server",
        ca,
        country_name="US",
        state_or_province_name="California",
        organization_name="EdgeDB Inc.",
        organizational_unit_name="EdgeDB tests",
        common_name="localhost",
        email_address="hello@edgedb.com",
        serial_number=4096,
    )
    new_crl('server', ca, server)

if __name__ == "__main__":
    main()


text:
NSUInteger const AWSKinesisAbstractClientByteLimitDefault = 5 * 1024 * 1024; // 5MB
NSTimeInterval const AWSKinesisAbstractClientAgeLimitDefault = 0.0; // Keeps the data indefinitely unless it hits the size limit.
NSString *const AWSKinesisAbstractClientUserAgent = @"recorder";
NSUInteger const AWSKinesisAbstractClientBatchRecordByteLimitDefault = 512 * 1024 * 1024;
NSString *const AWSKinesisAbstractClientRecorderDatabasePathPrefix = @"com/amazonaws/AWSKinesisRecorder";

@protocol AWSKinesisRecorderHelper <NSObject>

- (instancetype)initWithConfiguration:(AWSServiceConfiguration *)configuration;

- (AWSTask *)submitRecordsForStream:(NSString *)streamName
                            records:(NSArray *)temporaryRecords
                      partitionKeys:(NSArray *)partitionKeys
                   putPartitionKeys:(NSMutableArray *)putPartitionKeys
                 retryPartitionKeys:(NSMutableArray *)retryPartitionKeys;

- (NSError *)dataTooLargeError;

- (void)checkByteThresholdForNotification:(NSUInteger)notificationByteThreshold
                       notificationSender:(id)notificationSender
                                 fileSize:(NSUInteger)fileSize;

@end

@interface AWSAbstractKinesisRecorder()

@property (nonatomic, strong) id<AWSKinesisRecorderHelper> recorderHelper;
@property (nonatomic, strong) AWSFMDatabaseQueue *databaseQueue;
@property (nonatomic, strong) NSString *databasePath;

@end

@implementation AWSAbstractKinesisRecorder

- (instancetype)init {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:@"You must use subslasses of `AWSAbstractKinesisRecorder`. Use `AWSKinesisRecorder` or `AWSFirehoseRecorder`."
                                 userInfo:nil];
}

- (instancetype)initWithConfiguration:(AWSServiceConfiguration *)configuration
                           identifier:(NSString *)identifier
                            cacheName:(NSString *)cacheName {
    if (self = [super init]) {
        AWSServiceConfiguration *_configuration = [configuration copy];
        [_configuration addUserAgentProductToken:AWSKinesisAbstractClientUserAgent];
        NSString *databaseDirectoryPath = [NSTemporaryDirectory() stringByAppendingPathComponent:AWSKinesisAbstractClientRecorderDatabasePathPrefix];

        _databasePath = [databaseDirectoryPath stringByAppendingPathComponent:identifier];
        _diskByteLimit = AWSKinesisAbstractClientByteLimitDefault;
        _diskAgeLimit = AWSKinesisAbstractClientAgeLimitDefault;
        _batchRecordsByteLimit = AWSKinesisAbstractClientBatchRecordByteLimitDefault;

        // Creates a directory for storing databases if it doesn't exist.
        BOOL fileExistsAtPath = [[NSFileManager defaultManager] fileExistsAtPath:databaseDirectoryPath];
        if (!fileExistsAtPath) {
            NSError *error = nil;
            BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:databaseDirectoryPath
                                                     withIntermediateDirectories:YES
                                                                      attributes:nil
                                                                           error:&error];
            if (!success) {
                AWSLogError(@"Failed to create a directory for database. [%@]", error);
            }
        }

        // Creates a database for the identifier if it doesn't exist.
        AWSLogDebug(@"Database path: [%@]", _databasePath);
        _databaseQueue = [AWSFMDatabaseQueue databaseQueueWithPath:_databasePath];
        [_databaseQueue inDatabase:^(AWSFMDatabase *db) {
            if (![db executeStatements:@"PRAGMA auto_vacuum = FULL"]) {
                AWSLogError(@"Failed to enable 'aut_vacuum' to 'FULL'. %@", db.lastError);
            }

            if (![db executeUpdate:
                  @"CREATE TABLE IF NOT EXISTS record ("
                  @"partition_key TEXT NOT NULL,"
                  @"stream_name TEXT NOT NULL,"
                  @"data BLOB NOT NULL,"
                  @"timestamp REAL NOT NULL,"
                  @"retry_count INTEGER NOT NULL)"]) {
                AWSLogError(@"SQLite error. [%@]", db.lastError);
            }

            if (![db executeUpdate:@"VACUUM"]) {
                AWSLogError(@"SQLite error. [%@]", db.lastError);
            }
        }];
    }
    return self;
}

+ (dispatch_queue_t)sharedQueue {
    static dispatch_queue_t queue;
    static dispatch_once_t predicate;

    dispatch_once(&predicate, ^{
        queue = dispatch_queue_create("com.amazonaws.AWSKinesisRecorder", DISPATCH_QUEUE_SERIAL);
    });

    return queue;
}

- (AWSTask *)saveRecord:(NSData *)data
             streamName:(NSString *)streamName {
    // Returns error if the total size of data and partition key exceeds 256KB.
    if ([data length] > 256 * 1024) {
        return [AWSTask taskWithError:[self.recorderHelper dataTooLargeError]];
    }

    AWSFMDatabaseQueue *databaseQueue = self.databaseQueue;
    NSTimeInterval diskAgeLimit = self.diskAgeLimit;
    NSString *databasePath = self.databasePath;
    NSUInteger notificationByteThreshold = self.notificationByteThreshold;
    NSUInteger diskByteLimit = self.diskByteLimit;
    __weak id notificationSender = self;

    return [[AWSTask taskWithResult:nil] continueWithSuccessBlock:^id(AWSTask *task) {
        // Inserts a new record to the database.
        __block NSError *error = nil;
        [databaseQueue inDatabase:^(AWSFMDatabase *db) {
            BOOL result = [db executeUpdate:
                           @"INSERT INTO record ("
                           @"partition_key, stream_name, data, timestamp, retry_count"
                           @") VALUES ("
                           @":partition_key, :stream_name, :data, :timestamp, :retry_count"
                           @")"
                    withParameterDictionary:@{
                                              @"partition_key" : [[NSUUID UUID] UUIDString],
                                              @"stream_name" : streamName,
                                              @"data" : data,
                                              @"timestamp" : @([[NSDate date] timeIntervalSince1970]),
                                              @"retry_count" : @0
                                              }
                           ];

            if (!result) {
                AWSLogError(@"SQLite error. [%@]", db.lastError);
                error = db.lastError;
            }
        }];

        if (!error && diskAgeLimit > 0) {
            [databaseQueue inDatabase:^(AWSFMDatabase *db) {
                // Deletes old records exceeding the threshold.
                BOOL result = [db executeUpdate:
                               @"DELETE FROM record "
                               @"WHERE timestamp < :timestamp"
                        withParameterDictionary:@{
                                                  @"timestamp" : @([[NSDate date] timeIntervalSince1970] - diskAgeLimit)
                                                  }
                               ];
                if (!result) {
                    AWSLogError(@"SQLite error. [%@]", db.lastError);
                    error = db.lastError;
                }
            }];
        }

        if (error) {
            return [AWSTask taskWithError:error];
        }

        NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:databasePath
                                                                                error:&error];
        if (attributes) {
            NSUInteger fileSize = (NSUInteger)[attributes fileSize];
            [self.recorderHelper checkByteThresholdForNotification:notificationByteThreshold
                                                notificationSender:notificationSender
                                                          fileSize:fileSize];
            if (fileSize > diskByteLimit) {
                // Deletes the oldest record if it exceeds the disk size threshold.
                [databaseQueue inDatabase:^(AWSFMDatabase *db) {
                    BOOL result = [db executeUpdate:
                                   @"DELETE FROM record "
                                   @"WHERE partition_key IN ( "
                                   @"SELECT partition_key "
                                   @"FROM record "
                                   @"ORDER BY timestamp ASC "
                                   @"LIMIT 1 "
                                   @")"
                                   ];
                    if (!result) {
                        AWSLogError(@"SQLite error. [%@]", db.lastError);
                        error = db.lastError;
                        return;
                    }
                }];

            }
        } else if (error) {
            return [AWSTask taskWithError:error];
        }

        return nil;
    }];
}

- (AWSTask *)submitAllRecords {
    AWSFMDatabaseQueue *databaseQueue = self.databaseQueue;

    return [[AWSTask taskWithResult:nil] continueWithExecutor:[AWSExecutor executorWithDispatchQueue:[AWSKinesisRecorder sharedQueue]] withSuccessBlock:^id _Nullable(AWSTask * _Nonnull task) {
        __block NSError *error = nil;
        __block NSUInteger batchSize = 0;

        do {
            [databaseQueue inTransaction:^(AWSFMDatabase *db, BOOL *rollback) {
                NSMutableArray *partitionKeys = nil;

                AWSFMResultSet *rs = [db executeQuery:
                                      @"SELECT partition_key, data, retry_count, stream_name "
                                      @"FROM record "
                                      @"WHERE stream_name = (SELECT stream_name FROM record ORDER BY timestamp ASC LIMIT 1) "
                                      @"ORDER BY timestamp ASC "
                                      @"LIMIT 128"];
                if (!rs) {
                    AWSLogError(@"SQLite error. Rolling back... [%@]", db.lastError);
                    error = db.lastError;
                    *rollback = YES;
                    return;
                }

                NSUInteger batchDataSize = 0;
                NSMutableArray *temporaryRecords = [NSMutableArray new];
                partitionKeys = [NSMutableArray new];
                while ([rs next]) {
                    [temporaryRecords addObject:@{
                                                  @"partition_key": [rs stringForColumn:@"partition_key"],
                                                  @"data": [rs dataForColumn:@"data"],
                                                  @"stream_name": [rs stringForColumn:@"stream_name"],
                                                  }];

                    [partitionKeys addObject:[rs stringForColumn:@"partition_key"]];
                    batchDataSize += [[rs dataForColumn:@"data"] length];

                    if (batchDataSize > self.batchRecordsByteLimit) { // if the batch size exceeds `batchRecordsByteLimit`, stop there.
                        break;
                    }
                }
                rs = nil;
                batchSize = [temporaryRecords count];

                if (batchSize > 0) {
                    __block NSMutableArray *putPartitionKeys = [NSMutableArray new];
                    __block NSMutableArray *retryPartitionKeys = [NSMutableArray new];

                    NSString *streamName = temporaryRecords[0][@"stream_name"];

                    [[self.recorderHelper submitRecordsForStream:streamName
                                                         records:temporaryRecords
                                                   partitionKeys:partitionKeys
                                                putPartitionKeys:putPartitionKeys
                                              retryPartitionKeys:retryPartitionKeys] waitUntilFinished];

                    for (NSString *partitionKey in putPartitionKeys) {
                        BOOL result = [db executeUpdate:@"DELETE FROM record WHERE partition_key = :partition_key"
                                withParameterDictionary:@{
                                                          @"partition_key" : partitionKey
                                                          }];
                        if (!result) {
                            AWSLogError(@"SQLite error. [%@]", db.lastError);
                            error = db.lastError;
                        }
                    }

                    for (NSString *partitionKey in retryPartitionKeys) {
                        BOOL result = [db executeUpdate:@"UPDATE record SET retry_count = retry_count + 1 WHERE partition_key = :partition_key"
                                withParameterDictionary:@{
                                                          @"partition_key" : partitionKey
                                                          }];
                        if (!result) {
                            AWSLogError(@"SQLite error. [%@]", db.lastError);
                            error = db.lastError;
                        }
                    }
                }

                // If a record failed three times, give up and delete the record.
                BOOL result = [db executeUpdate:@"DELETE FROM record WHERE retry_count > 3"];
                if (!result) {
                    AWSLogError(@"SQLite error. [%@]", db.lastError);
                    error = db.lastError;
                }
            }];
        } while (!error && batchSize > 0);

        if (error) {
            return [AWSTask taskWithError:error];
        }

        return nil;
    }];
}

- (AWSTask *)removeAllRecords {
    AWSFMDatabaseQueue *databaseQueue = self.databaseQueue;

    return [[AWSTask taskWithResult:nil] continueWithSuccessBlock:^id(AWSTask *task) {
        __block NSError *error = nil;
        [databaseQueue inDatabase:^(AWSFMDatabase *db) {
            if (![db executeUpdate:@"DELETE FROM record"]) {
                AWSLogError(@"SQLite error. [%@]", db.lastError);
                error = db.lastError;
            }
        }];

        if (error) {
            return [AWSTask taskWithError:error];
        }

        return nil;
    }];
}

- (NSUInteger)diskBytesUsed {
    NSError *error = nil;
    NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:self.databasePath
                                                                                error:&error];
    if (attributes) {
        return (NSUInteger)[attributes fileSize];
    } else {
        AWSLogError(@"Error [%@]", error);
        return 0;
    }
}

- (void)setBatchRecordsByteLimit:(NSUInteger)batchRecordsByteLimit {
    if (batchRecordsByteLimit > 4 * 1024 * 1024) {
        _batchRecordsByteLimit = 4 * 1024 * 1024;
    } else {
        _batchRecordsByteLimit = batchRecordsByteLimit;
    }
}

@end


text:
@interface ShadowedTextFieldCell : NSTextFieldCell
{
}

@end


text:
namespace peloton {
namespace tcop {

// global singleton
TrafficCop &TrafficCop::GetInstance(void) {
  static TrafficCop traffic_cop;
  catalog::Bootstrapper::bootstrap();
  catalog::Bootstrapper::global_catalog->CreateDatabase(DEFAULT_DB_NAME);
  return traffic_cop;
}

TrafficCop::TrafficCop() {
  // Nothing to do here !
}

TrafficCop::~TrafficCop() {
  // Nothing to do here !
}

Result TrafficCop::ExecuteStatement(
    const std::string &query, std::vector<ResultType> &result,
    std::vector<FieldInfoType> &tuple_descriptor, int &rows_changed,
    std::string &error_message) {
  LOG_TRACE("Received %s", query.c_str());

  // Prepare the statement
  std::string unnamed_statement = "unnamed";
  auto statement = PrepareStatement(unnamed_statement, query, error_message);

  if (statement.get() == nullptr) {
    return Result::RESULT_FAILURE;
  }

  // Then, execute the statement
  bool unnamed = true;
  auto status =
      ExecuteStatement(statement, unnamed, result, rows_changed, error_message);

  if (status == Result::RESULT_SUCCESS) {
    LOG_TRACE("Execution succeeded!");
    tuple_descriptor = std::move(statement->GetTupleDescriptor());
  } else {
    LOG_TRACE("Execution failed!");
  }

  return status;
}

Result TrafficCop::ExecuteStatement(
    const std::shared_ptr<Statement> &statement,
    UNUSED_ATTRIBUTE const bool unnamed,
    std::vector<ResultType> &result,
    UNUSED_ATTRIBUTE int &rows_changed,
    UNUSED_ATTRIBUTE std::string &error_message) {

  LOG_TRACE("Execute Statement %s", statement->GetStatementName().c_str());
  std::vector<Value> params;
  bridge::PlanExecutor::PrintPlan(statement->GetPlanTree().get(), "Plan");
  bridge::peloton_status status =
      bridge::PlanExecutor::ExecutePlan(statement->GetPlanTree().get(), params, result);
  LOG_TRACE("Statement executed. Result: %d", status.m_result);
  return status.m_result;
}

std::shared_ptr<Statement> TrafficCop::PrepareStatement(
    const std::string &statement_name, const std::string &query_string,
    UNUSED_ATTRIBUTE std::string &error_message) {
  std::shared_ptr<Statement> statement;

  LOG_TRACE("Prepare Statement %s", query_string.c_str());

  std::vector<std::string> query_tokens;
    boost::split(query_tokens, query_string, boost::is_any_of(" "),
        boost::token_compress_on);

  statement.reset(new Statement(statement_name, query_string));

  auto &peloton_parser = parser::Parser::GetInstance();
  auto sql_stmt = peloton_parser.BuildParseTree(query_string);

  statement->SetPlanTree(
      optimizer::SimpleOptimizer::BuildPelotonPlanTree(sql_stmt));

  if(sql_stmt->GetType() == STATEMENT_TYPE_SELECT){
      LOG_TRACE("******* SELECT STATEMENT DETECTED *******");

      auto select_stmt = (parser::SelectStatement*)sql_stmt.get();

      std::vector<FieldInfoType> t_desc;

      auto target_table = static_cast<storage::DataTable *>(
        catalog::Bootstrapper::global_catalog->GetTableFromDatabase(
            DEFAULT_DB_NAME, select_stmt->from_table->name));

      auto columns = target_table->GetSchema()->GetColumns();

      if(select_stmt->select_list->at(0)->GetExpressionType() == EXPRESSION_TYPE_STAR){

         for(oid_t i = 0; i < columns.size(); ++i){

          if(columns[i].column_type == VALUE_TYPE_INTEGER){
            LOG_TRACE("******* INTEGER *******");
            t_desc.push_back(std::make_tuple(columns[i].column_name , 23 , 4));
          }

          else if(columns[i].column_type == VALUE_TYPE_DOUBLE){
            LOG_TRACE("******* FLOAT *******");
            t_desc.push_back(std::make_tuple(columns[i].column_name , 701 , 8));
          }

          else if(columns[i].column_type == VALUE_TYPE_VARCHAR){
            LOG_TRACE("******* TEXT *******");
            t_desc.push_back(std::make_tuple(columns[i].column_name, 25, 255));
          }

          else{
            LOG_ERROR("Unrecognized column type: %d", columns[i].column_type);
            t_desc.push_back(std::make_tuple(columns[i].column_name, 25, 255));
          }
         }
      }
      else if(query_tokens[1].find("COUNT(") != std::string::npos){
        t_desc.push_back(make_tuple(query_tokens[1] , 23 , 4));
        LOG_TRACE("query_tokens is ----------------> %s" , query_tokens[1].c_str());
      }
      else if(query_tokens[1].find("MAX(") != std::string::npos){
        t_desc.push_back(make_tuple(query_tokens[1] , 23 , 4));
      }
      else if(query_tokens[1].find("MIN(") != std::string::npos){
        t_desc.push_back(make_tuple(query_tokens[1] , 23 , 4));
      }
      else if(query_tokens[1].find("AVG(") != std::string::npos){
        t_desc.push_back(make_tuple(query_tokens[1] , 701 , 8));
      }
      statement->SetTupleDescriptor(t_desc);
    }

  bridge::PlanExecutor::PrintPlan(statement->GetPlanTree().get(), "Plan");
  LOG_TRACE("Statement Prepared!");
  return std::move(statement);
}

}  // End tcop namespace
}  // End peloton namespace


text:
package edu.banda.coel.server.dao.evo;

import org.springframework.beans.factory.annotation.Autowired;

import com.banda.core.domain.um.User;
import com.banda.math.domain.evo.EvoGaSetting;
import com.banda.serverbase.persistence.GenericDAO;

import edu.banda.coel.server.dao.CoelBasicDaoTest;

/**
 * @author Peter Banda
 * @since 2011
 */
public class EvoGaSettingDaoTest extends CoelBasicDaoTest<EvoGaSetting, Long> {

	private static final Long EXISTING_GA_SETTING_ID = 1l;

	@Autowired
	GenericDAO<EvoGaSetting, Long> evoGaSettingDAO;

	@Override
	public void setUpTestData() {
		setUp(evoGaSettingDAO, EvoGaSetting.class, EXISTING_GA_SETTING_ID);
	}

	@Override
	protected GenericDAO<EvoGaSetting, Long> getDao() {
		return evoGaSettingDAO;
	}

	@Override
	protected EvoGaSetting getTestObject() {
		EvoGaSetting newGaSetting = super.getTestObject();

		User existingUser = new User();
		existingUser.setId(1l);
		newGaSetting.setCreatedBy(existingUser);

		return newGaSetting;
	}
}


text:
package gozmo

import (
	"fmt"
)

func IsTrue(value interface{}, err error) bool {
	if err != nil {
		fmt.Println(err)
		return false
	}
	isTrue, ok := value.(bool)
	if !ok {
		return false
	}
	return isTrue
}

func CastBool(value interface{}) (bool, error) {
	flag, ok := value.(bool)
	if ok {
		return flag, nil
	}
	// Special case for allowing numbers as boolean.
	num, err := CastFloat32(value)
	if err == nil {
		return num != 0, nil
	}
	return false, fmt.Errorf("expects a bool")
}


text:
/*jslint node: true */
'use strict';

var _ = require('underscore');
var errorUtil = require(global.VX_UTILS + 'error');
var jobUtil = require(global.VX_UTILS + 'job-utils');
var async = require('async');
var solrXform = require(global.VX_UTILS + 'solr-xform');

function handle(log, config, environment, job, handlerCallback) {
    log.debug('store-record-request-handler.handle: Received request to store record (%s) %j', job.dataDomain, job);

    if (!jobUtil.isValid(jobUtil.storeRecordType(), job)) {
        log.warn('store-record-request-handler.handle: Invalid job received.  Job: %j', job);
        return handlerCallback(errorUtil.createFatal('Invalid format for job', job));
    } else {
        log.debug('store-record-request-handler.handle: Valid job received');
    }

    // validate record
    if (_.isUndefined(job.record)) {
        log.error('store-record-request-handler.handle: Missing record.  Job: %j', job);
        return handlerCallback(errorUtil.createFatal('Missing record', job));
    }
    if (_.isUndefined(job.record.uid)) {
        log.error('store-record-request-handler.handle: Missing uid.  Job: %j', job);
        return handlerCallback(errorUtil.createFatal('Missing UID', job));
    }
    if (_.isUndefined(job.record.stampTime)) {
        log.error('store-record-request-handler.handle: Missing stampTime.  Job: %j', job);
        return handlerCallback(errorUtil.createFatal('Missing stampTime', job));
    }
    if (_.isUndefined(job.record.pid) && _.isUndefined(job.record.icn)) {
        log.error('store-record-request-handler.handle: Missing patient identifier.  Job: %j', job);
        return handlerCallback(errorUtil.createFatal('Missing patient identifier', job));
    }

    log.debug('store-record-request-handler.handle: Storing to JDS: %j', job);
    async.series({
        storeJds: function(callback) {
            environment.jds.storePatientDataFromJob(job, function(error, response, body) {
                log.debug('store-record-request-handler.handle: JDS response code: %s', (response ? response.statusCode : undefined));
                if (error) {
                    log.debug('store-record-request-handler.handle: error: %s; response: %j; body: %j', error, response, body);
                    return callback(error);
                }
                if (response.statusCode !== 201) {
                    log.debug('store-record-request-handler.handle: error: %s; response: %j; body: %j', error, response, body);
                }

                log.debug('store-record-request-handler.handle: JDS STORED RECORD!  error: %s; response: %j; body: %j', error, response, body);
                return callback();
            });
        },
        storeSolr: function(callback) {
            var solrClient = environment.solr;

            var solrRecord = solrXform(job.record, log);
            if (_.isObject(solrRecord)) {
                log.debug('store-record-request-handler.handle: Storing SOLR record.  uid: %s; solrRecord: %j', job.record.uid, solrRecord);
                solrClient.add(solrRecord, function(error) {
                    if (error) {
                        // error storing to solr.  log it, but don't kill stuff
                        log.error('store-record-request-handler.handle: Error storing to SOLR.  error: %s; uid: %s, solrRecord: %j', error, job.record.uid, solrRecord);
                        return callback();
                    } else {
                        log.debug('store-record-request-handler.handle: Record stored to SOLR successfully.  uid: %s', job.record.uid);
                        return callback();
                    }
                });
            } else {
                log.debug('store-record-request-handler.handle: SOLR xform returned null There is no SOLR record to store.  uid: %s', job.record.uid);
                return callback();
            }
        },
        publish: function(callback) {
            var meta = {
                jpid: job.jpid,
                rootJobId: job.rootJobId,
                param: job.param
            };
            var jobToPublish = jobUtil.createPublishVxDataChange(job.patientIdentifier, job.dataDomain, job.record, meta);
            environment.publisherRouter.publish(jobToPublish, callback);
        }
    }, function(error) {
        log.debug('store-record-request-handler.handle: Completed call to async.series.  error: %s', error);
        if (error) {
            if (error.message) {
                log.error('store-record-request-handler.handle: Unable to store record.  error: %j', error.message.error.errors);
                return handlerCallback(errorUtil.createFatal('Unable to store record', error.message.error.errors));
            }
            log.error('store-record-request-handler.handle: Unable to handle publish vx data change.  error: %j', error);
            return handlerCallback(errorUtil.createFatal('Unable to handle publish vx data change', error));
        }

        log.debug('store-record-request-handler.handle: Exiting final callback.');
        handlerCallback(null, 'success');
    });

}

module.exports = handle;


text: <%= streamusIsTakingALongTimeToLoadReloadingMayHelpMessage %>


text:
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase

class BytearrayTests(TranspileTestCase):
    def test_setattr(self):
        self.assertCodeExecution("""
            x = bytearray([1,2,3])
            try:
                x.attr = 42
            except AttributeError as err:
                print(err)
            """)

    def test_getattr(self):
        self.assertCodeExecution("""
            x = bytearray([1,2,3])
            try:
                print(x.attr)
            except AttributeError as err:
                print(err)
            """)

    def test_contains(self):
        self.assertCodeExecution("""
            print(bytearray([1,2,3]) in bytearray([1,2]))
            print(bytearray([1,2]) in bytearray([1,2,3]))
            print(bytearray([1,2,4]) in bytearray([1,2,3]))
            print(bytearray([8,9,0,1]) in bytearray([1,2,3]))
            print(101 in bytearray([1,2,3]))
            print(101 in bytearray([1,2,3,101]))
            print(b'pybee' in bytearray([1,2]))
            print(bytearray([1,2]) in b'pybee')
        """)
        self.assertCodeExecution("""
            try:
                print(300 in bytearray([1,2,3]))
                print("No error raised")
            except ValueError:
                print("Raised a ValueError")
        """)
        self.assertCodeExecution("""
            try:
                print(['b', 'e'] in bytearray([1,2,3]))
                print("No error raised")
            except TypeError:
                print("Raised a TypeError")
        """)

    def test_capitalize(self):
        self.assertCodeExecution("""
            print(bytearray(b'abc').capitalize())
            print(bytearray().capitalize())
        """)

    def test_islower(self):
        # TODO: add this test when adding support for literal hex bytes
        # print(b'\xf0'.islower())

        self.assertCodeExecution("""
            print(bytearray(b'abc').islower())
            print(bytearray(b'').islower())
            print(bytearray(b'Abccc').islower())
            print(bytearray(b'HELLO WORD').islower())
            print(bytearray(b'@#$%!').islower())
            print(bytearray(b'hello world').islower())
            print(bytearray(b'hello world   ').islower())
        """)

    def test_isspace(self):
        self.assertCodeExecution("""
            print(bytearray(b'testupper').isspace())
            print(bytearray(b'test isspace').isspace())
            print(bytearray(b' ').isspace())
            print(bytearray(b'').isspace())
            print(bytearray(b'\x46').isspace())
            print(bytearray(b'   \t\t').isspace())
            print(bytearray(b' \x0b').isspace())
            print(bytearray(b' \f').isspace())
            print(bytearray(b' \\n').isspace())
            print(bytearray(b' \\r').isspace())
        """)

    def test_upper(self):
        # TODO: add this test when adding support for literal hex bytes
        # print(bytearray(b'\xf0').upper())

        self.assertCodeExecution("""
            print(bytearray(b'abc').upper())
            print(bytearray(b'').upper())
            print(bytearray(b'Abccc').upper())
            print(bytearray(b'HELLO WORD').upper())
            print(bytearray(b'@#$%!').upper())
            print(bytearray(b'hello world').upper())
            print(bytearray(b'hello world   ').upper())
        """)

    def test_ljust(self):
        self.assertCodeExecution("""
            print(bytearray(b'testMoreThanWidth').ljust(5))
            print(bytearray(b'testEqualWidth').ljust(14))
            print(bytearray(b'testLessThanWidth').ljust(20))
            print(bytearray(b'testMoreWithFill').ljust(2, b'x'))
            print(bytearray(b'testEqualWithFill').ljust(17, b'x'))
            print(bytearray(b'testLessWithFill').ljust(25, b'x'))
            print(bytearray(b'testNegative').ljust(-20))
            print(bytearray(b'').ljust(5))
            print(bytearray(b'testNoChangeWidthOne').ljust(True, b'x'))
            print(bytearray(b'testBArraySecondArg').ljust(True, bytearray(b'x')))
            try:
                print(bytearray(b'testStrArgError').ljust('5'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testMoreLengthError').ljust(12, b'as'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testStrFillingChar').ljust(12, 'a'))
            except Exception as e:
                print(str(e))
        """)

    def test_rjust(self):
        self.assertCodeExecution("""
            print(bytearray(b'testMoreThanWidth').rjust(5))
            print(bytearray(b'testEqualWidth').rjust(14))
            print(bytearray(b'testLessThanWidth').rjust(20))
            print(bytearray(b'testMoreWithFill').rjust(2, b'x'))
            print(bytearray(b'testEqualWithFill').rjust(17, b'x'))
            print(bytearray(b'testLessWithFill').rjust(25, b'x'))
            print(bytearray(b'testNegative').rjust(-20))
            print(bytearray(b'').rjust(5))
            print(bytearray(b'testNoChangeWidthOne').rjust(True, b'x'))
            print(bytearray(b'testBArraySecondArg').rjust(True, bytearray(b'x')))
            try:
                print(bytearray(b'testStrArgError').rjust('5'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testMoreLengthError').rjust(12, b'as'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testStrFillingChar').rjust(12, 'a'))
            except Exception as e:
                print(str(e))
        """)

    def test_expandtabs(self):
        self.assertCodeExecution("""
            print(bytearray(b'testNoTabs').expandtabs())
            print(bytearray(b'test\t').expandtabs())
            print(bytearray(b'testDoubleTab\t\t').expandtabs())
            print(bytearray(b'testTab\tandText').expandtabs())
            print(bytearray(b'testTab\t').expandtabs(4))
            print(bytearray(b'testTab\t\t').expandtabs(4))
            print(bytearray(b'test\t\t').expandtabs(-4))
            print(bytearray(b'').expandtabs(5))
            try:
                print(bytearray(b'testErrorChar\t').expandtabs('a'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testErrorChars\t').expandtabs('as'))
            except Exception as e:
                print(str(e))
            try:
                print(bytearray(b'testErrorCharNum\t').expandtabs('1'))
            except Exception as e:
                print(str(e))
        """)

    def test_isalpha(self):
        # TODO: add this test when adding support for literal hex bytes
        # print(bytearray(b'\xf0').isalpha())

        self.assertCodeExecution("""
            print(bytearray(b'abc').isalpha())
            print(bytearray(b'').isalpha())
            print(bytearray(b'Abccc').isalpha())
            print(bytearray(b'HELLO WORD').isalpha())
            print(bytearray(b'@#$%!').isalpha())
            print(bytearray(b'hello world').isalpha())
            print(bytearray(b'hello world   ').isalpha())
        """)

    def test_isupper(self):
        self.assertCodeExecution("""
            print(bytearray(b'abc').isupper())
            print(bytearray(b'ABC').isupper())
            print(bytearray(b'').isupper())
            print(bytearray(b'Abccc').isupper())
            print(bytearray(b'HELLO WORD').isupper())
            print(bytearray(b'@#$%!').isupper())
            print(bytearray(b'hello world').isupper())
            print(bytearray(b'hello world   ').isupper())
        """)

    def test_lower(self):
        self.assertCodeExecution("""
            print(bytearray(b"abc").lower())
            print(bytearray(b"HELLO WORLD!").lower())
            print(bytearray(b"hElLO wOrLd").lower())
            print(bytearray(b"[Hello] World").lower())
            """)

    def test_count(self):
        self.assertCodeExecution("""
            print(bytearray(b'abcabca').count(97))
            print(bytearray(b'abcabca').count(b'abc'))
            print(bytearray(b'qqq').count(b'q'))
            print(bytearray(b'qqq').count(b'qq'))
            print(bytearray(b'qqq').count(b'qqq'))
            print(bytearray(b'qqq').count(b'qqqq'))
            print(bytearray(b'abcdefgh').count(b'bc',-7, -5))
            print(bytearray(b'abcdefgh').count(b'bc',1, -5))
            print(bytearray(b'abcdefgh').count(b'bc',0, 3))
            print(bytearray(b'abcdefgh').count(b'bc',-7, 500))
            print(bytearray(b'qqaqqbqqqcqqqdqqqqeqqqqf').count(b'qq'),1)
            print(bytearray(b'').count(b'q'),0)
        """)

    def test_find(self):
        self.assertCodeExecution("""
            print(bytearray(b'').find(b'a'))
            print(bytearray(b'abcd').find(b''))
            print(bytearray(b'abcd').find(b'...'))
            print(bytearray(b'abcd').find(b'a'))
            print(bytearray(b'abcd').find(b'b'))
            print(bytearray(b'abcd').find(b'c'))
            print(bytearray(b'abcd').find(b'd'))
            print(bytearray(b'abcd').find(bytearray(b'ab')))
            print(bytearray(b'abcd').find(b'bc'))
            print(bytearray(b'abcd').find(b'cd'))
            print(bytearray(b'abcd').find(b'cd', 2))
            print(bytearray(b'abcd').find(bytearray(b'ab'), 3))
            print(bytearray(b'abcd').find(b'cd', 2, 3))
            print(bytearray(b'abcd').find(bytearray(b'ab'), 3, 4))
        """)

    def test_center(self):
        self.assertCodeExecution("""
            print(bytearray(b'pybee').center(12))
            print(bytearray(b'pybee').center(13))
            print(bytearray(b'pybee').center(2))
            print(bytearray(b'pybee').center(2, b'a'))
            print(bytearray(b'pybee').center(12, b'a'))
            print(bytearray(b'pybee').center(13, b'a'))
            print(bytearray(b'pybee').center(-5))
            print(bytearray(b'').center(5))
            print(bytearray(b'pybee').center(True, b'a'))
            print(bytearray(b'pybee').center(True, bytearray(b'a')))
        """)

    def test_title(self):
        self.assertCodeExecution(r"""
            print(bytearray(b"").title())
            print(bytearray(b"abcd").title())
            print(bytearray(b"NOT").title())
            print(bytearray(b"coca cola").title())
            print(bytearray(b"they are from UK, are they not?").title())
            print(bytearray(b'/@.').title())
            print(bytearray(b'\x46\x55\x43\x4B').title())
            print(bytearray(b"py.bee").title())
        """)

    def test_istitle(self):
        self.assertCodeExecution(r"""
            print(bytearray(b"").istitle())
            print(bytearray(b"abcd").istitle())
            print(bytearray(b"NOT").istitle())
            print(bytearray(b"coca cola").istitle())
            print(bytearray(b"they are from UK, are they not?").istitle())
            print(bytearray(b'/@.').istitle())
            print(bytearray(b'\x46\x55\x43\x4B').istitle())
            print(bytearray(b"py.bee").title())
        """)

    def test_repr(self):
        self.assertCodeExecution(r"""
            print(repr(bytearray(b'\xc8')))
            print(repr(bytearray(b'abcdef \xc8 abcdef')))
            print(repr(bytearray(b'abcdef \xc8 abcdef\n\r\t')))
            print(bytearray(b'abcdef \xc8 abcdef\n\r\t'))
            for b in range(0, 256, 16):
                print(repr(bytearray(range(b, b+16))))
            for b in range(0, 256, 16):
                print(bytearray(range(b, b+16)))
        """)

    def test_endswith(self):
        self.assertCodeExecution(r"""
            print(bytearray(b'banana').endswith(b'ana'))
            print(bytearray(b'banana').endswith(b''))
            print(bytearray(b'').endswith(b'ana'))
            print(bytearray(b'').endswith(b''))
        """)

    def test_startswith(self):
        self.assertCodeExecution(r"""
            print(bytearray(b'banana').startswith(b'ana'))
            print(bytearray(b'banana').startswith(b''))
            print(bytearray(b'').startswith(b'ana'))
            print(bytearray(b'').startswith(b''))
        """)

    def test_isalnum(self):
        self.assertCodeExecution("""
            print(bytearray(b'0').isalnum())
            print(bytearray(b'9').isalnum())
            print(bytearray(b'1234567890').isalnum())
            print(bytearray(b'89A23gM23z').isalnum())
            print(bytearray(b':923').isalnum())
            print(bytearray(b'\\923').isalnum())
            print(bytearray(b' jdf fhd 33').isalnum())
            print(bytearray(b'@#$%^&*').isalnum())
            print(bytearray(b'"478\t47ads:').isalnum())
            print(bytearray(b'AbZ').isalnum())
        """)

    def test_isdigit(self):
        self.assertCodeExecution("""
            print(bytearray(b'0').isdigit())
            print(bytearray(b'9').isdigit())
            print(bytearray(b'1234567890').isdigit())
            print(bytearray(b'8923g23823').isdigit())
            print(bytearray(b'923').isdigit())
            print(bytearray(b'\\923').isdigit())
            print(bytearray(b'000').isdigit())
            print(bytearray(b'@#$%^&*').isdigit())
            print(bytearray(b'"478\t47ads:').isdigit())
            print(bytearray(b'AbZ').isdigit())
        """)

    def test_join(self):
        self.assertCodeExecution("""
            b = bytearray(b'.')
            print(b.join([b'12', b'dh']))
            print(b.join([bytearray(b'12'), bytearray(b'dh')]))
            b = bytearray(b' ')
            print(b.join([b'd', bytearray(b'l22-'), b'=ej*']))
            print(b.join([bytearray(b'31'), b'`', b'^']))
            print(b.join([bytearray(b'dh')]))
            b = bytearray(b'%#@!')
            print(b.join([b'1',b'd',b'<']))
            print(b.join([b'12']))
        """)

class UnaryBytearrayOperationTests(UnaryOperationTestCase, TranspileTestCase):
    data_type = 'bytearray'

class BinaryBytearrayOperationTests(BinaryOperationTestCase, TranspileTestCase):
    data_type = 'bytearray'

    not_implemented_versions = {
        'test_modulo_complex': (3.4, ),
    }

class InplaceBytearrayOperationTests(InplaceOperationTestCase, TranspileTestCase):
    data_type = 'bytearray'

    not_implemented_versions = {
        'test_modulo_complex': (3.4, ),
    }