text:
package com.hpba.bankman.controller;

import com.hpba.bankman.view.*;
import com.hpba.bankman.model.*;
import java.io.*;
import java.time.*;
import java.time.format.*;
import java.util.*;
import org.slf4j.*;

/**
 * This class handles all interaction between the
 * {@link com.hpba.bankman.model model} and the
 * {@link com.hpba.bankman.view view}.
 *

 * The heart of the application, everything is controlled by this class,
 * including the database connection handling.
 *
 * @author generalhpba
 * @version 1.0
 * @since 1.0
 */
public final class Controller {

    /**
     * The logger.
     */
    Logger LOGGER = LoggerFactory.getLogger(Controller.class);
    /**
     * The pointer to the actual {@link com.hpba.bankman.model model}.
     */
    Model model;
    /**
     * The pointer to the actual {@link com.hpba.bankman.view view}.
     */
    View view;
    /**
     * State which represents whether the application is currently loading.
     */
    private static boolean isLoading = false;

    /**
     * The parameterless constructor.
     */
    public Controller() {
    }

    /**
     * Constructor with {@link com.hpba.bankman.model model} and
     * {@link com.hpba.bankman.view view} parameters.
     *
     * @param model the current model
     * @param view the current view
     */
    public Controller(Model model, View view) {
        this.model = model;
        this.view = view;
    }

    /**
     * The starter method of the controller.
     */
    public void start() {
        view.switchToConnect();
        new Thread(rCon).start();
    }

    /**
     * Configures the connection to the database using the configuration file.
     *
     * @param args connection specifying switches
     */
    public void loadConfiguration(String... args) {
        Properties prop = new Properties();
        InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties");

        if (is == null) {
            LOGGER.error("Configuration file error!");
        }

        try {
            prop.load(is);
        } catch (Exception ex) {
            LOGGER.error("Configuration file error!", ex);
        }

        if (args.length > 0) {
            for (String s : args) {
                if (s.equals("-l")) {
                    ConnectionFactory.setConnection(prop.getProperty("URL_l"),
                            prop.getProperty("USER_l"), prop.getProperty("PASS_l"));
                } else if (s.equals("-s")) {
                    ConnectionFactory.setConnection(prop.getProperty("URL_s"),
                            prop.getProperty("USER_s"), prop.getProperty("PASS_s"));
                }
            }
        } else {
            ConnectionFactory.setConnection(prop.getProperty("URL"),
                    prop.getProperty("USER"), prop.getProperty("PASS"));
        }
    }

    /**
     * Connects to the database.
     */
    Runnable rCon = () -> {
        connectToDatabase(0);
    };

    /**
     * Loads data from the database into the
     * {@link com.hpba.bankman.model model}.
     */
    Runnable rLoad = () -> {
        if (!isLoading) {
            isLoading = true;
            view.getMainPanel().setLoading(true);
            loadModelFromDB(model);
            view.getMainPanel().setLoading(false);
            isLoading = false;
        }
    };

    /**
     * Handles the login process.
     */
    public void aLogin() {
        view.switchToLoading();
        Runnable rLogin = () -> {
            String[] userData = DB_DAO.login(view.getLogin().getLoginUsername(), view.getLogin().getLoginPassword());
            if (userData != null) {
                model.setClient(new Client(userData[0], userData[1]));
                LOGGER.info("User: " + userData[1] + " has logged in");
                switchToMain("main");
            } else {
                view.switchToLogin();
                view.initInfo("Warning", "Invalid username / password!");
            }
        };
        new Thread(rLogin).start();
    }

    /**
     * Registers the new user.
     */
    public void aRegister() {
        view.switchToLoading();
        Runnable rRegister = () -> {
            try {
                String[] userData = view.getRegisterData();
                if (userData[0].trim().equals("") || userData[0].length() < 3) {
                    view.initInfo("Warning", "Selected username is invalid!");
                    view.switchToLogin();
                    view.showRegister();
                } else if (userData[0].length() > 0) {
                    for (char c : userData[0].toCharArray()) {
                        if (Character.isWhitespace(c)) {
                            view.initInfo("Warning", "Usernames can't contain any whitespaces!");
                            view.switchToLogin();
                            view.showRegister();
                        }
                    }
                } else if (userData[1].trim().equals("")) {
                    view.initInfo("Warning", "Selected password is invalid!");
                    view.switchToLogin();
                    view.showRegister();
                }
                if (!DB_DAO.isUserExists(userData[0])) {
                    if (DB_DAO.register(userData[0], userData[1])) {
                        view.initInfo("Success", "User registration successful!");
                        LOGGER.info("User: " + userData[1] + " has successfully registered");
                        view.switchToLogin();
                        view.showRegister();
                    } else {
                        LOGGER.warn("Database error");
                        view.initInfo("Warning", "Database error, please try again.");
                        view.switchToLogin();
                        view.showRegister();
                    }
                } else {
                    view.initInfo("Warning", "This username is already taken!");
                    view.switchToLogin();
                    view.showRegister();
                }
            } catch (Exception e) {
                view.switchToLogin();
            }
        };
        new Thread(rRegister).start();
    }

    /**
     * Retries connection to the database.
     */
    public void aRetry() {
        switchToConnect();
        new Thread(rCon).start();
    }

    /**
     * Switches back to the login screen.
     */
    public void aBackToLogin() {
        view.switchToLogin();
        model.reset();
    }

    /**
     * Updates the currently selected account in the
     * {@link com.hpba.bankman.model model} from the
     * {@link com.hpba.bankman.view view}.
     */
    public void aSelectCurrent() {
        model.setCurrentAccount(view.getSelectedAccount());
        switchToAccount();
    }

    /**
     * Handles the open account process.
     *
     * @return status code of the operation
     */
    public int aOpenAccount() {
        if (view.getMain().getOpenAccount().isEditValid()) {
            ArrayList<String> al = view.getOpenAccountData();
            view.switchToLoading();
            new Thread() {
                @Override
                public void run() {
                    if (!DB_DAO.isAccountExists(al.get(0))) {
                        switch (al.get(1)) {
                            case "Transactional Account":
                                new Thread() {
                                    @Override
                                    public void run() {
                                        if (DB_DAO.insertTransactional(new Transactional(al.get(0), 0), model.getClientId())) {
                                            LOGGER.info("New transactional account with number " + al.get(0) + " has been created");
                                            switchToMain("main");
                                        } else {
                                            switchToMain("main");
                                            LOGGER.warn("Database error");
                                            view.initInfo("Warning", "INSERT ERROR
Account insertion into database has failed.");
                                        }
                                    }
                                }.start();
                                break;
                            case "Savings Account":
                                new Thread() {
                                    @Override
                                    public void run() {
                                        if (DB_DAO.insertSavings(new Savings(al.get(0), 0, 2.3), model.getClientId())) {
                                            LOGGER.info("New savings account with number " + al.get(0) + " has been created");
                                            switchToMain("main");
                                        } else {
                                            switchToMain("main");
                                            LOGGER.warn("Database error");
                                            view.initInfo("Warning", "INSERT ERROR
Account insertion into database has failed.");
                                        }
                                    }
                                }.start();
                                break;
                            case "Term Deposit":
                                new Thread() {
                                    @Override
                                    public void run() {
                                        if (DB_DAO.insertTerm(new Term(al.get(0), 0, 4.5), model.getClientId())) {
                                            LOGGER.info("New term deposit account with number " + al.get(0) + " has been created");
                                            switchToMain("main");
                                        } else {
                                            switchToMain("main");
                                            LOGGER.warn("Database error");
                                            view.initInfo("Warning", "INSERT ERROR
Account insertion into database has failed.");
                                        }
                                    }
                                }.start();
                                break;
                            default:
                                view.initInfo("Error", "Account type not supported");
                        }
                    } else {
                        switchToMain("main");
                        view.initInfo("Warning", "Account with this number already exits!");
                    }
                }
            }.start();
            return 0;
        } else {
            view.showInvalidLabel();
            return 1;
        }
    }

    /**
     * Initializes the open account process.
     */
    public void aOpenAccountDisplay() {
        view.initOpenAccount();
    }

    /**
     * Handles the close account process.
     */
    public void aCloseAccount() {
        view.switchToLoading();
        new Thread() {
            @Override
            public void run() {
                String accountNumber = view.getSelectedAccount();
                if (DB_DAO.closeAccount(model.getAccount(accountNumber))) {
                    LOGGER.info("Account with number " + accountNumber + " has been closed");
                    switchToMain("main");
                } else {
                    switchToMain("main");
                    LOGGER.warn("Database error");
                    view.initInfo("Error", "Database error, operation failed!");
                }
            }
        }.start();
    }

    /**
     * Initializes the close account process.
     */
    public void aCloseAccountDisplay() {
        view.initCloseAccount();
    }

    /**
     * Connects to the database using the
     * {@link ConnectionFactory ConnectionFactory}.
     *
     * @param retries number of failed connections
     */
    void connectToDatabase(int retries) {
        if (ConnectionFactory.getConnection() != null) {
            LOGGER.info("Successfully connected to the database.");
            view.switchToLogin();
        } else {
            if (retries == 3) {
                LOGGER.warn("Couldn't connect to the database.");
                switchToOffline();
            } else {
                retries++;
                connectToDatabase(retries);
            }
        }
    }

    /**
     * Switches to the main display.
     *
     * @param str specifies the sub display
     */
    public void switchToMain(String str) {
        view.switchToMain(str);
        if (str.equals("main")) {
            model.setCurrentAccount(null);
            new Thread(rLoad).start();
            updateMain();
        }
    }

    /**
     * Updates the main display with data from the
     * {@link com.hpba.bankman.model model}.
     */
    void updateMain() {
        ArrayList<String> accs = new ArrayList<>();
        ArrayList<String> types = new ArrayList<>();
        ArrayList<Integer> balances = new ArrayList<>();
        for (String str : model.getClient().getAccounts()) {
            accs.add(model.getAccount(str).getNumber());
            types.add(model.getAccount(str).getType());
            balances.add((int) model.getAccount(str).getBalance());
        }
        view.updateAccountList(accs, types, balances);
        view.updateUserInfo(model.getUsername(), model.getAccountCount(), model.getTransactionalCount(),
                model.getSavingsCount(), model.getTermCount(), model.getBalanceSum());
    }

    /**
     * Updates the term display.
     */
    void updateTerm() {
        Term act = (Term) model.getAccount();
        view.updateTermInfo(
                act.isLocked(),
                act.getInterestRate(),
                act.getLockStart(),
                act.getLockEnd());
    }

    /**
     * Updates the savings display.
     */
    void updateSavings() {
        Savings act = (Savings) model.getAccount();
        view.updateSavingsInfo(
                act.getInterestRate(),
                Model.calcInterestPerMonth(act),
                act.getTransferLimit(),
                act.getTransferLimit() - act.getTransfersThisMonth());
    }

    /**
     * Calculates the term deposit account interest.
     */
    public void aTermCalcInterest() {
        Term act = (Term) model.getAccount();
        String months = view.getTermPanel().getLockTimeTF().getText();
        int length = Integer.valueOf(months.replaceAll("[^\\d.]", ""));
        double value = Model.calcInterest(act, length);
        view.interestDialog(value, LocalDate.now().plusMonths(length));
    }

    /**
     * Locks the currently selected term deposit account.
     */
    public void aTermLock() {
        try {
            int length = Integer.valueOf(view.getTermPanel().getLockTimeTF().getText());
            if (length > 0) {
                Term act = (Term) model.getAccount();
                act.lock(length);
                updateTerm();
                DB_DAO.updateTerm(act);
                view.getTermPanel().lockDialog(Model.calcInterest(act, length), act.getBalance(), act.getLockEnd());
            } else {
                view.getTermPanel().lockDenyDialog();
            }
        } catch (NumberFormatException e) {
            view.initInfo("Warning", "Term length must be between 1 - 999!");
        }
    }

    /**
     * Transfers money between two accounts.
     *

     * This is an action method, called from the
     * {@link com.hpba.bankman.view view} as a result of an interaction.
     *

     * The transaction data retrieved from the
     * {@link com.hpba.bankman.view view}:
     *

     *
0 = Account number

     *
1 = The desired amount

     *
2 = description about the transaction

     *

     */
    public void aTransfer() {
        view.switchToLoading();
        new Thread() {
            @Override
            public void run() {
                try {
                    ArrayList<Object> al = view.getTransactionData();
                    view.closeTransactionDialog();
                    if (DB_DAO.isAccountExists((String) al.get(0))) {
                        if (al.get(1).equals("")) {
                            switchToMain("");
                            view.initInfo("Warning", "Transfer amount field can't be empty!");
                            return;
                        } else if (Double.parseDouble((String) al.get(1)) < 1.0) {
                            switchToMain("");
                            view.initInfo("Warning", "Minimum transfer amount is $1.0!");
                            return;
                        }
                        Account to = DB_DAO.getAccountFully((String) al.get(0));
                        model.setAccount(DB_DAO.getAccountFully(view.getSelectedAccount()));
                        int res = model.transfer(model.getAccount(), to,
                                Double.parseDouble((String) al.get(1)),
                                (String) al.get(2));
                        switch (res) {
                            case 0:
                                if (DB_DAO.updateAccounts(new Account[]{model.getAccount(), to},
                                        new Entry[]{model.getAccount().getLastEntry(), to.getLastEntry()})) {
                                    LOGGER.info("Successful transaction between " + model.getCurrentAccount() + " and " + to.getNumber());
                                    view.initInfo("Success", "Transfer has been completed successfully!");
                                } else {
                                    view.initInfo("Error", "Database error, transfer was unsuccessful!");
                                }
                                break;
                            case 1:
                                view.initInfo("Warning", "Insufficient funds!");
                                break;
                            case 2:
                                view.initInfo("Warning", "Savings account has reached maximum transfer count!"
                                        + "
Transfer count reset is at the 1st day of each month.");
                                break;
                            case 3:
                                view.initInfo("Warning", "Term locked!");
                                break;
                            case 4:
                                view.initInfo("Error", "Database error, transfer was unsuccessful!");
                                break;
                            case 5:
                                view.initInfo("Error", "Unknown exception, pls contact administrator!");
                                break;
                            case 6:
                                view.initInfo("Warning", "Can't transfer money to the same account!");
                                break;
                        }
                        if (model.getAccount() instanceof Savings) {
                            updateSavings();
                        }
                        view.updateAccountInfo(model.getCurrentAccount(), Double.valueOf(model.getBalance()));
                        view.updateTransactionalHistory(getHistoryData(model.getCurrentAccount()));
                        switchToMain("");
                    } else {
                        switchToMain("");
                        view.initInfo("Warning", "Given account doesn't exists!");
                    }
                } catch (Exception e) {
                    LOGGER.error("Exception during transfer", e);
                    switchToMain("");
                }
            }
        }.start();
    }

    /**
     * Switches the display to the currently selected account.
     */
    private void switchToAccount() {
        String acc = view.getSelectedAccount();
        if (model.getAccount(acc) != null) {
            view.switchToLoading();
            new Thread() {
                @Override
                public void run() {
                    switch (model.getAccount(acc).getType()) {
                        case "Term Deposit":
                            model.setAccount(DB_DAO.getTerm(model.getAccount(model.getCurrentAccount())));
                            model.updateAccountInfo(DB_DAO.getAccount(model.getNumber())); // in case of change
                            view.switchToMain("term");
                            updateTerm();
                            break;
                        case "Savings Account":
                            model.setAccount(DB_DAO.getSavings(model.getAccount(model.getCurrentAccount())));
                            model.updateAccountInfo(DB_DAO.getAccount(model.getNumber())); // in case of change
                            view.switchToMain("savings");
                            updateSavings();
                            break;
                        case "Transactional Account":
                            model.setAccount(model.getAccount(acc));
                            model.updateAccountInfo(DB_DAO.getAccount(model.getNumber())); // in case of change
                            view.updateTransactionalHistory(getHistoryData(model.getCurrentAccount()));
                            view.switchToMain("transactional");
                            break;
                    }
                    view.updateAccountInfo(model.getCurrentAccount(), Double.valueOf(model.getBalance()));
                }
            }.start();
        }
    }

    /**
     * Switches to the offline display.
     */
    private void switchToOffline() {
        view.switchToOffline();
    }

    /**
     * Switches to the connection display.
     */
    private void switchToConnect() {
        view.switchToConnect();
    }

    /**
     * Initializes the transaction display.
     */
    public void transaction() {
        view.initTransaction();
    }

    /**
     * Retrieves the history of the owner of the provided account number.
     *
     * @param number account number
     * @return history contained in an ArrayList
     */
    private ArrayList<String[]> getHistoryData(String number) {
        ArrayList<String[]> al = new ArrayList<>();
        for (Entry e : DB_DAO.getEntries(number)) {
            al.add(new String[]{e.getDate().format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)),
                e.getOperation(), e.getParty(), String.valueOf(e.getAmount()), e.getStatement()});
        }
        return al;
    }

    /**
     * Displays the history of the currently selected account.
     */
    public void history() {
        view.switchToLoading();
        new Thread() {
            @Override
            public void run() {
                view.initHistory("Transaction History", getHistoryData(model.getCurrentAccount()));
                switchToMain("");
            }
        }.start();
    }

    /**
     * Loads the {@link com.hpba.bankman.model model} from the database.
     *
     * @param model target model
     */
    void loadModelFromDB(Model model) {
        model.reset();
        ArrayList<Account> al = DB_DAO.getAccounts(model.getClientId());
        for (Account a : al) {
            model.addAccount(a);
            model.getClient().add(a.getNumber());
        }
        updateMain();
    }

    /**
     * Sets the currently active {@link com.hpba.bankman.model model}.
     *
     * @param model model
     */
    public void setModel(Model model) {
        this.model = model;
    }

    /**
     * Sets the currently active {@link com.hpba.bankman.view view}.
     *
     * @param view view
     */
    public void setView(View view) {
        this.view = view;
    }
}


text:
import { test, moduleForComponent } from 'ember-qunit';
import startApp from '../../helpers/start-app';
import Ember from 'ember';
import JWT from 'simple-auth-token/authenticators/jwt';
import Configuration from 'simple-auth-token/configuration';

var App;

var createFakeToken = function(obj) {
  var token = window.btoa(JSON.stringify(obj));
  return 'a.' + token + '.b';
};

module('JWT Authenticator', {
  setup: function() {
    App = startApp();
    App.xhr = sinon.useFakeXMLHttpRequest();
    App.server = sinon.fakeServer.create();
    App.server.autoRespond = true;
    App.authenticator = JWT.create();
    sinon.spy(Ember.run, 'later');
  },
  teardown: function() {
    Ember.run(App, App.destroy);
    App.xhr.restore();
    Ember.run.later.restore();
  }
});

test('assigns serverTokenRefreshEndpoint from the configuration object', function() {
  Configuration.serverTokenRefreshEndpoint = 'serverTokenRefreshEndpoint';

  equal(JWT.create().serverTokenRefreshEndpoint, 'serverTokenRefreshEndpoint');

  Configuration.load({}, {});
});

test('assigns refreshAccessTokens from the configuration object', function() {
  Configuration.refreshAccessTokens = 'refreshAccessTokens';

  equal(JWT.create().refreshAccessTokens, 'refreshAccessTokens');

  Configuration.load({}, {});
});

test('assigns tokenExpireName from the configuration object', function() {
  Configuration.tokenExpireName = 'tokenExpireName';

  equal(JWT.create().tokenExpireName, 'tokenExpireName');

  Configuration.load({}, {});
});

test('assigns timeFactor from the configuration object', function() {
  Configuration.timeFactor = 'timeFactor';

  equal(JWT.create().timeFactor, 'timeFactor');

  Configuration.load({}, {});
});

test('#restore resolves when the data includes `token` and `expiresAt`', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data.expiresAt = expiresAt;

  App.server.respondWith('POST', '/api-token-refresh/', [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  Ember.run(function() {
    App.authenticator.restore(data).then(function(content) {
      // Check that the resolved data matches the init data.
      equal(JSON.stringify(content), JSON.stringify(data));
    }, function () {
      ok(false);
    });
  });
});

test('#restore resolves when the data includes `token` and excludes `expiresAt`', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  App.server.respondWith('POST', '/api-token-refresh/', [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  Ember.run(function() {
    App.authenticator.restore(data).then(function(content) {
      equal(JSON.stringify(content), JSON.stringify(data), 'Check that the resolved data matches the init data');
    }).catch(function () {
      ok(false);
    });
  });
});

test('#restore rejects when `refreshAccessTokens` is false and token is expired', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime();

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data['expiresAt'] = expiresAt;

  App.authenticator.refreshAccessTokens = false;

  App.server.respondWith('POST', '/api-token-refresh/', [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  Ember.run(function() {
    App.authenticator.restore(data).then(function () {
      ok(false);
    }, function() {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    });
  });
});

test('#restore rejects when `token` is excluded.', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data['expiresAt'] = expiresAt;

  App.server.respondWith('POST', '/api-token-refresh/', [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  Ember.run(function() {
    App.authenticator.restore(data).then(function () {
      ok(false);
    }, function() {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    });
  });
});

test('#restore resolves when `expiresAt` is greater than `now`', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data[jwt.tokenExpireName] = expiresAt;

  App.authenticator.refreshAccessTokens = false;

  App.server.respondWith('POST', '/api-token-refresh/', [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  Ember.run(function() {
    App.authenticator.restore(data).then(function(content) {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    }).catch(function (err) {
      ok(false);
    });
  });
});

test('#restore schedules a token refresh when `refreshAccessTokens` is true.', function() {
  expect(2);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data[jwt.tokenExpireName] = expiresAt;

  // TODO: find out if there is another way besides setting Ember.testing.
  Ember.testing = false;

  Ember.run(function() {
    App.authenticator.restore(data).then(function(content) {
      // Check that Ember.run.later ran.
      var spyCall = Ember.run.later.getCall(0);
      deepEqual(spyCall.args[1], App.authenticator.refreshAccessToken);
      deepEqual(spyCall.args[2], token);
    });
  });
});

test('#restore does not schedule a token refresh when `refreshAccessTokens` is false.', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data[jwt.tokenExpireName] = expiresAt;

  App.authenticator.refreshAccessTokens = false;

  Ember.run(function() {
    App.authenticator.restore(data).then(function(content) {
      // Check that Ember.run.later ran.
      var spyCall = Ember.run.later.getCall(0);
      deepEqual(spyCall, null);
    });
  });
});

test('#restore does not schedule a token refresh when `expiresAt` < now.', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() - 10;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data[jwt.tokenExpireName] = expiresAt;

  Ember.run(function() {
    App.authenticator.restore(data).catch(function() {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    });
  });
});

test('#restore does not schedule a token refresh when `expiresAt` - `refreshLeeway` < now.', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var data = {};
  data[jwt.tokenPropertyName] = token;
  data[jwt.tokenExpireName] = expiresAt;

  // Set the refreshLeeway to > expiresAt.
  App.authenticator.refreshLeeway = 120;

  Ember.run(function() {
    App.authenticator.restore(data).catch(function() {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    });
  });
});

test('#authenticate sends an ajax request to the token endpoint', function() {
  expect(1);
  sinon.spy(Ember.$, 'ajax');

  var jwt = JWT.create();

  var credentials = {
    identification: 'username',
    password: 'password'
  };

  App.authenticator.authenticate(credentials);

  Ember.run.next(function() {
    var args = Ember.$.ajax.getCall(0).args[0];
    delete args.beforeSend;
    deepEqual(args, {
      url: jwt.serverTokenEndpoint,
      type: 'POST',
      data: '{"password":"password","username":"username"}',
      dataType: 'json',
      contentType: 'application/json',
      headers: {}
    });
    Ember.$.ajax.restore();
  });
});

test('#authenticate rejects with invalid credentials', function() {
  expect(1);
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var credentials = {
    identification: 'username',
    password: 'password'
  };

  App.server.respondWith('POST', jwt.serverTokenEndpoint, [
    400, {
      'Content-Type': 'application/json'
    },
    '{"message":["Unable to login with provided credentials."]}'
  ]);

  // TODO: find out of there is another way besides setting Ember.testing.
  Ember.testing = false;

  Ember.run(function() {
    App.authenticator.authenticate(credentials).then(null, function() {
      // Check that Ember.run.later was not called.
      deepEqual(Ember.run.later.getCall(0), null);
    });
  });
});

test('#authenticate schedules a token refresh when `refreshAccessTokens` is true', function() {
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var credentials = {
    identification: 'username',
    password: 'password'
  };

  App.server.respondWith('POST', jwt.serverTokenEndpoint, [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  // TODO: find out of there is another way besides setting Ember.testing.
  Ember.testing = false;

  Ember.run(function() {
    App.authenticator.authenticate(credentials).then(function(content) {
      var spyCall = Ember.run.later.getCall(0);
      deepEqual(spyCall.args[1], App.authenticator.refreshAccessToken);
      deepEqual(spyCall.args[2], token);
    });
  });
});

test('#authenticate does not schedule a token refresh when `refreshAccessTokens` is false', function() {
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  var credentials = {
    identification: 'username',
    password: 'password'
  };

  App.server.respondWith('POST', jwt.serverTokenEndpoint, [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  App.authenticator.refreshAccessTokens = false;

  // TODO: find out of there is another way besides setting Ember.testing.
  Ember.testing = false;

  Ember.run(function() {
    App.authenticator.authenticate(credentials).then(function(content) {
      // Check that Ember.run.later ran.
      var spyCall = Ember.run.later.getCall(0);
      deepEqual(spyCall, null);
    });
  });
});

test('#refreshAccessToken makes an AJAX request to the token endpoint.', function() {
  sinon.spy(Ember.$, 'ajax');

  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  App.authenticator.refreshAccessToken(token);

  Ember.run.next(function() {
    var args = Ember.$.ajax.getCall(0).args[0];
    delete args.beforeSend;
    deepEqual(args, {
      url: jwt.serverTokenRefreshEndpoint,
      type: 'POST',
      data: JSON.stringify({
        'token': token
      }),
      dataType: 'json',
      contentType: 'application/json',
      headers: {}
    });
    Ember.$.ajax.restore();
  });
});

test('#refreshAccessToken triggers the `sessionDataUpdated` event on successful request.', function() {
  var jwt = JWT.create(),
    expiresAt = (new Date()).getTime() + 60000;

  var token = {};
  token[jwt.identificationField] = 'test@test.com';
  token[jwt.tokenExpireName] = expiresAt;

  token = createFakeToken(token);

  App.server.respondWith('POST', jwt.serverTokenRefreshEndpoint, [
    201, {
      'Content-Type': 'application/json'
    },
    '{ "token": "' + token + '"}'
  ]);

  App.authenticator.refreshAccessToken(token);

  App.authenticator.one('sessionDataUpdated', function(data) {
    ok(data[jwt.tokenExpireName], 'Verify expiresAt was added to response');
    ok(data[jwt.tokenExpireName] > (new Date()).getTime(), 'Verify is greater than now');
    deepEqual(data.token, token);
  });
});

test('#getTokenData returns correct data', function() {
  var jwt = JWT.create();

  var stringTokenData = 'test@test.com';
  var objectTokenData = {};

  objectTokenData[jwt.identificationField] = stringTokenData;

  var objectToken = createFakeToken(objectTokenData);
  var stringToken = createFakeToken(stringTokenData);

  deepEqual(jwt.getTokenData(objectToken), objectTokenData, 'Object data returned');
  equal(jwt.getTokenData(stringToken), stringTokenData, 'String data returned');
});

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"image"
	"log"
	"os"
	"path/filepath"
	"reflect"
	"runtime"
	"sync"
	"time"

	"lec/lecimg"
)

// Work represents a job to do
type Work struct {
	dir      string
	filename string
	quit     bool
}

// Worker is a worker to process images.
type Worker struct {
	workChan <-chan Work
}

func collectImages(workChan chan<- Work, finChan chan<- bool, srcDir string, watch bool, watchDelay int) {
	defer func() {
		finChan <- true
	}()

	lastCheckTime := time.Unix(0, 0)
	var files []os.FileInfo
	var err error

	for {
		// List modified image files
		files, lastCheckTime, err = lecimg.ListModifiedImages(srcDir, watchDelay, lastCheckTime)
		if err != nil {
			log.Println(err)
			break
		}

		// add works
		for _, file := range files {
			workChan <- Work{srcDir, file.Name(), false}
		}

		if watch {
			// sleep for a while
			time.Sleep(time.Duration(5) * time.Second)
		} else {
			break
		}
	}
}

func work(worker Worker, filters []lecimg.Filter, destDir string, wg *sync.WaitGroup) {
	defer func() {
		wg.Done()
	}()

	for {
		work := <-worker.workChan
		if work.quit {
			break
		}

		log.Printf("[R] %v\n", work.filename)

		src, err := lecimg.LoadImage(filepath.Join(work.dir, work.filename))
		if err != nil {
			log.Printf("Error : %v : %v\n", work.filename, err)
			continue
		}

		// run filters
		var dest image.Image
		for _, filter := range filters {
			result := filter.Run(lecimg.NewFilterSource(src, work.filename, -1))
			result.Log()

			resultImg := result.Img()
			if resultImg == nil {
				log.Printf("Filter result is nil. filter: %v\n", reflect.TypeOf(filter))
				break
			}

			dest = resultImg
			src = dest
		}

		// save dest Img
		err = lecimg.SaveJpeg(dest, destDir, work.filename, 80)
		if err != nil {
			log.Printf("Error : %v : %v\n", work.filename, err)
			continue
		}
	}
}

func startWorks(config *Config) {
	// set maxProcess
	runtime.GOMAXPROCS(config.maxProcess)

	// Create channels
	workChan := make(chan Work, 100)
	finChan := make(chan bool)

	// WaitGroup
	wg := sync.WaitGroup{}

	// start collector
	go collectImages(workChan, finChan, config.src.dir, config.watch, config.watchDelay)

	var filters []lecimg.Filter
	for _, filterOption := range config.filterOptions {
		filters = append(filters, filterOption.filter)
	}

	// start workers
	for i := 0; i < config.maxProcess; i++ {
		worker := Worker{workChan}
		wg.Add(1)
		go work(worker, filters, config.dest.dir, &wg)
	}

	// wait for collector finish
	<-finChan

	// finish workers
	for i := 0; i < config.maxProcess; i++ {
		workChan <- Work{"", "", true}
	}

	wg.Wait()
}


text:
package modelservice.core

import scala.Numeric._
import scala.util.hashing._

//import breeze.linalg.SparseVector
import breeze.linalg.CSCMatrix

trait FeatureManager[A, B] extends Serializable {
  def parseRow(row: Map[String, A])(implicit num: Numeric[B]): CSCMatrix[B]
  def getW(): CSCMatrix[Double]
}

class HashFeatureManager extends FeatureManager[String, Double] {
  var k = 0
  var singleFeatures = List[String]()
  var quadFeatures = List[String]()
  var quads = Seq[Seq[Seq[String]]]()
  var labels = List[String]()
  var numericLabels = List[String]()
  def allFeatures = {
    singleFeatures :::
      quadFeatures
  }
  var hashFunctions = Map[String, (String => Int)]()
  var numericValue = ""

  def withK(k: Int): HashFeatureManager = {
    this.k = k
    this
  }

  def withLabels(labels: List[String]): HashFeatureManager = {
    this.labels = labels
    this
  }

  def withNumericLabels(numericLabels: List[String]): HashFeatureManager = {
    this.numericLabels = numericLabels
    this
  }

  def withSingleFeatures(singleFeatures: List[String]): HashFeatureManager = {
    this.singleFeatures = singleFeatures
    this.hashFunctions = this.allFeatures.map(
      x => (x, this.hashFactory(x))
    ).toMap
    this
  }

  def withQuadraticFeatures(quads: Seq[Seq[Seq[String]]]): HashFeatureManager = {
    this.quads = quads
    this.quadFeatures = this.quadProduct(
      this.quads,
      (x: String, y: String) => x + "_" + y
    ).toList
    this.hashFunctions = this.allFeatures.map(
      x => (x, this.hashFactory(x))
    ).toMap
    this
  }

  def withNumericValue(numericValue: String): HashFeatureManager = {
    this.numericValue = numericValue
    this
  }

  /**
    * Override the hashCode method to provide a consistent way to compare models
    * @return
    */
  override def hashCode(): Int = {
    MurmurHash3.bytesHash(
      flattenList(List[Any](
        this.k.toString,
        this.singleFeatures,
        this.quadFeatures,
        this.quads,
        this.labels,
        this.allFeatures
      )).foldLeft("")(
        (accum, next) => accum + next
      ).getBytes, 5)
  }

  override def equals(that: Any): Boolean = {
    that match {
      case thatFM: HashFeatureManager => this.hashCode() == that.hashCode()
      case _ => false
    }
  }

  private def flattenList(rec: Seq[Any], level: Int = 0): Seq[String] = {
    rec.foldLeft(List[String](level.toString)) { case (accum, nextRec) =>
      nextRec match {
        case r: Seq[Any] => accum ++ flattenList(r, level + 1)
        case r: String => accum :+ r
      }
    }
  }

  def getFeatures(row: Map[String, String], intercept: Boolean = true): List[Int] = {
    val filteredSingleFeatures = this.singleFeatures.flatMap{f =>
      row.get(f) match {
        case Some(fv) => Some((f, fv))
        case None => None
      }
    }
    val filteredQuads = this.quads.flatMap{x =>
      val rowList = x.flatMap {y =>
        val subList = y.flatMap{f =>
          row.get(f) match {
            case Some(fv) => Some((f, fv))
            case None => None
          }
        }
        subList.length match {
          case l if l > 0 => Some(subList)
          case _ => None
        }
      }
      rowList.length match {
        case l if l > 0 => Some(rowList)
        case _ => None
      }
    }
    val allKeys = filteredSingleFeatures ++ this.quadProduct(
      filteredQuads,
      (a: (String, String), b: (String, String)) => (a._1 + "_" + b._1, a._2 + "_" + b._2)
    )

    val hashedFeatures = allKeys.flatMap{
      case (k: String, v: String) => {
        this.hashFunctions.get(k) match {
          case Some(hf: (String => Int)) => Some(hf(v))
          case _ => None
        }
      }
      case _ => None
    }

    intercept match {
      case true => hashedFeatures :+ 0
      case false => hashedFeatures
    }
  }

  def getFeaturesSparse(row: Map[String, String], intercept: Boolean = true): CSCMatrix[Double] = {
    val sparseFeaturesIndex = this.getFeatures(row, intercept).sorted.toArray
    val numFeatures = sparseFeaturesIndex.length
    val sparseFeaturesData = (1 to numFeatures).map(x => 1.0).toArray

    new CSCMatrix[Double](
      sparseFeaturesData,
      1 << this.k,
      1,
      Array[Int](0, numFeatures),
      sparseFeaturesIndex
    )
  }

  def hashFactory(key: String): (String => Int) = {
    val truncBytes = (1 << k) + (~1 + 1)
    val hashSpace = (1 << 16) + (~1 + 1)
    val hashSalt = hashSpace >> 2
    val hashSeed = (key.getBytes.map(c => c.toInt) :+ hashSalt).
      reduce((x, y) => (x * y) % hashSpace)

    (value => MurmurHash3.bytesHash(value.getBytes, hashSeed) & truncBytes)
  }

  def quadProduct[T](quads: Seq[Seq[Seq[T]]], func: (T, T) => T) = {
    quads.map(
      row => row.reduce(
        (q1, q2) => for {a <- q1; b <- q2} yield func(a, b))
    ).reduce(_ ++ _)
  }

  def parseRow(row: Map[String, String])(implicit num: Numeric[Double]) = {
    this.getFeaturesSparse(row)
  }

  def getW() = {
    CSCMatrix.zeros[Double](1 << this.k, this.labels.length)
  }
}


text:
require "spec_helper"

describe Deferral do
  let(:deferral) { Deferral.new }
  subject { deferral }
  describe "Validations" do
    describe "enrollment" do
      context "should be valid when" do
        it "enrollment is not null" do
          deferral.enrollment = Enrollment.new
          deferral.should have(0).errors_on :enrollment
        end

        it "deferral_type phase has the enrollment level" do
          level = FactoryGirl.create(:level)
          phase = FactoryGirl.create(:phase)
          deferral.enrollment = FactoryGirl.create(:enrollment, :level => level)
          deferral.deferral_type = FactoryGirl.create(:deferral_type, :phase => phase)
          phase_duration = FactoryGirl.create(:phase_duration, :phase => phase, :level => level)

          deferral.should have(0).errors_on :enrollment
        end
      end
      context "should have error blank when" do
        it "enrollment is null" do
          deferral.enrollment = nil
          deferral.should have_error(:blank).on :enrollment
        end
      end

      context "should have error enrollment_level when" do
        it "deferral_type phase doesn't have the enrollment level" do
          level = FactoryGirl.create(:level)
          phase = FactoryGirl.create(:phase)
          deferral.enrollment = FactoryGirl.create(:enrollment, :level => level)
          deferral.deferral_type = FactoryGirl.create(:deferral_type, :phase => phase)

          deferral.should have_error(:enrollment_level).on :enrollment
        end
      end
    end
    describe "deferral_type" do
      context "should be valid when" do
        it "deferral_type is not null" do
          deferral.deferral_type = DeferralType.new
          deferral.should have(0).errors_on :deferral_type
        end
      end
      context "should have error blank when" do
        it "deferral_type is null" do
          deferral.deferral_type = nil
          deferral.should have_error(:blank).on :deferral_type
        end
      end
    end
    describe "approval_date" do
      context "should be valid when" do
        it "approval_date is not null" do
          deferral.approval_date = Date.parse("2014/01/01")
          deferral.should have(0).errors_on :approval_date
        end
      end
      context "should have error blank when" do
        it "approval_date is null" do
          deferral.approval_date = nil
          deferral.should have_error(:blank).on :approval_date
        end
      end
    end
  end
  describe "Methods" do
    describe "to_label" do
      it "should return the expected string" do
        deferral_type_name = "DeferralType"
        deferral.deferral_type = DeferralType.new(:name => deferral_type_name)
        deferral.to_label.should eql(deferral_type_name)
      end
    end
    describe "valid_until" do
      it "should return 31th of july 2013" do
        phase = FactoryGirl.create(:phase)
        level = FactoryGirl.create(:level)
        enrollment = FactoryGirl.create(:enrollment, :level => level, :admission_date => Date.new(2012, 3, 1))
        phase_duration = FactoryGirl.create(:phase_duration, :phase => phase, :deadline_semesters => 1, :level => level, :deadline_days => 0)
        FactoryGirl.create(:accomplishment, :phase => phase, :enrollment => enrollment)
        deferral_type = FactoryGirl.create(:deferral_type, :phase => phase, :duration_semesters => 2, :duration_days => 0)
        deferral = FactoryGirl.create(:deferral, :enrollment => enrollment, :deferral_type => deferral_type, :approval_date => Date.today)

        deferral.valid_until.should eql(Date.new(2013, 7, 31).strftime('%d/%m/%Y'))
      end

      it "should return 28th of february 2023" do
        phase = FactoryGirl.create(:phase)
        level = FactoryGirl.create(:level)
        enrollment = FactoryGirl.create(:enrollment, :level => level, :admission_date => Date.new(2017, 8, 1))
        phase_duration = FactoryGirl.create(:phase_duration, :phase => phase, :deadline_semesters => 8, :level => level, :deadline_days => 0)
        FactoryGirl.create(:accomplishment, :phase => phase, :enrollment => enrollment)
        deferral_type = FactoryGirl.create(:deferral_type, :phase => phase, :duration_semesters => 3, :duration_days => 0)
        deferral = FactoryGirl.create(:deferral, :enrollment => enrollment, :deferral_type => deferral_type, :approval_date => Date.today)

        deferral.valid_until.should eql(Date.new(2023, 2, 28).strftime('%d/%m/%Y'))
      end

      it "should return 7th of june 2014" do
        phase = FactoryGirl.create(:phase)
        level = FactoryGirl.create(:level)
        enrollment = FactoryGirl.create(:enrollment, :level => level, :admission_date => Date.new(2013, 8, 1))
        phase_duration = FactoryGirl.create(:phase_duration, :phase => phase, :deadline_semesters => 1, :level => level, :deadline_days => 0)
        FactoryGirl.create(:accomplishment, :phase => phase, :enrollment => enrollment)
        deferral_type = FactoryGirl.create(:deferral_type, :phase => phase, :duration_months => 3, :duration_days => 7)
        deferral = FactoryGirl.create(:deferral, :enrollment => enrollment, :deferral_type => deferral_type, :approval_date => Date.today)

        deferral.valid_until.should eql(Date.new(2014, 6, 7).strftime('%d/%m/%Y'))
      end
    end
  end
end


text:
//-----------------------------------------------------------------------
// <copyright file="SnapshotDirectoryFailureSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System.IO;
using Akka.Actor;
using Xunit;

namespace Akka.Persistence.Tests
{
    public class SnapshotDirectoryFailureSpec : PersistenceSpec
    {
        private const string InUseSnapshotPath = "target/inUseSnapshotPath";

        internal class TestPersistentActor : PersistentActor
        {
            private readonly string _name;
            private readonly IActorRef _probe;

            public TestPersistentActor(string name, IActorRef probe)
            {
                _name = name;
                _probe = probe;
            }

            public override string PersistenceId { get { return _name; } }

            protected override bool ReceiveRecover(object message)
            {
                if (message is SnapshotOffer)
                    _probe.Tell(message);
                else return false;
                return true;
            }

            protected override bool ReceiveCommand(object message)
            {
                if (message is string)
                    SaveSnapshot(message);
                else if (message is SaveSnapshotSuccess)
                    _probe.Tell(((SaveSnapshotSuccess)message).Metadata.SequenceNr);
                else
                    _probe.Tell(message);
                return true;
            }
        }

        FileInfo file = new FileInfo(InUseSnapshotPath);

        public SnapshotDirectoryFailureSpec() : base(Configuration("SnapshotDirectoryFailureSpec",
            extraConfig: "akka.persistence.snapshot-store.local.dir = \"" + InUseSnapshotPath + "\""))
        {
        }

        protected override void AtStartup()
        {
            base.AtStartup();
            using (file.Create()) {}
        }

        protected override void AfterTermination()
        {
            file.Delete();
            base.AfterTermination();
        }

        [Fact]
        public void LocalSnapshotStore_configured_with_a_failing_directory_name_should_throw_an_exception_at_startup()
        {
            EventFilter.Exception(typeof (ActorInitializationException)).ExpectOne(() =>
            {
                var pref = Sys.ActorOf(Props.Create(() => new TestPersistentActor("SnapshotDirectoryFailureSpec-1", TestActor)));
                pref.Tell("blahonga");
            });
        }
    }
}


text:
<?php

?>
<?php

include_once 'servicecaller.php';

class LabOrderModel {

	public function LabOrderModel(){}

	private $testid;
	private $visitid;
   	private $orderdate;
	private $duedate;
	private $orderby;
	private $orderlocation;
	private $priority;
	private $remarks;

	public function get_Testid() { return $this->testid; }
	public function get_Visitid() { return $this->visitid; }
	public function get_Orderdate() { return $this->orderdate; }
	public function get_Duedate() { return $this->duedate; }
	public function get_Orderby() { return $this->orderby; }
	public function get_Orderlocation() { return $this->orderlocation; }
	public function get_Priority() { return $this->priority; }
	public function get_Remarks() { return $this->remarks; }

	public function set_Testid($x) { $this->testid = $x; }
	public function set_Visitid($x) { $this->visitid = $x; }
	public function set_Orderdate($x) { $this->orderdate = $x; }
	public function set_Duedate($x) { $this->duedate = $x; }
	public function set_Orderby($x) { $this->orderby = $x; }
	public function set_Orderlocation($x) { $this->orderlocation = $x; }
	public function set_Priority($x) { $this->priority = $x; }
	public function set_Remarks($x) { $this->remarks = $x; }

	public function addLabOrder()
	{
		$patientJSON   = json_encode($this->jsonSerialize());
		$service_url =SERVICE_BASE_URL."OPDLabOrder/addLabOrder";
		$MediaType = "application/json";
		$curl_request  = new ServiceCaller();
	    $response =  $curl_request->curl_POST_Request($service_url,$patientJSON,$MediaType);
		return $response;
	}

	public function getDoctorLabOrders($docid)
	{
		$service_url =SERVICE_BASE_URL."OPDLabOrder/getLabOrderByUserID/".$docid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function getPatientLabOrders($patientID)
	{
		$service_url =SERVICE_BASE_URL."OPDLabOrder/getLabOrderByPatientID/".$patientID;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function getLabOrderDetails($orderid)
	{
		$service_url ="http://env-7792945.jelastic.servint.net/elab/laborder/searchStatus/".$orderid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function getVisitLabOrders($visitid)
	{
		$service_url = SERVICE_BASE_URL."OPDLabTestRequest/getOPDRequestByVisitID/".$visitid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}
	public function getVisitLabOrdersByPid($visitid)
	{
		$service_url = SERVICE_BASE_URL."LabTestRequest/getRequestsByPatientID/".$visitid;
		$curl_request = new ServiceCaller();
		$response = $curl_request->curl_GET_Request($service_url);
		return $response;
	}

	public function jsonSerialize()
	{
		$post_data = array(
			"DueDate" => $this->duedate,
			"OrderdDate" => date('Y-m-d'),
			"TestID" => $this->testid,
			"visitid" => $this->visitid,
			"orderCreateUser" => 1,
			"orderLocation" =>  $this->orderlocation,
			"orderPriority" => $this->priority,
			"orderRemarks" => $this->remarks,
		);
		return $post_data;
	}

}
?>


text:
package com.thoughtworks.go.apiv9.admin.shared.representers.stages.artifacts;

import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.api.representers.ConfigurationPropertyRepresenter;
import com.thoughtworks.go.api.representers.JsonReader;
import com.thoughtworks.go.config.PluggableArtifactConfig;

public class ExternalArtifactConfigRepresenter {

    public static void toJSON(OutputWriter jsonWriter, PluggableArtifactConfig pluggableArtifactConfig) {
        jsonWriter.add("artifact_id", pluggableArtifactConfig.getId());
        jsonWriter.add("store_id", pluggableArtifactConfig.getStoreId());
        jsonWriter.addChildList("configuration", configurationWriter -> ConfigurationPropertyRepresenter.toJSON(configurationWriter, pluggableArtifactConfig.getConfiguration()));
    }

    public static PluggableArtifactConfig fromJSON(JsonReader jsonReader, PluggableArtifactConfig pluggableArtifactConfig) {
        jsonReader.readStringIfPresent("artifact_id", pluggableArtifactConfig::setId);
        jsonReader.readStringIfPresent("store_id", pluggableArtifactConfig::setStoreId);
        pluggableArtifactConfig.addConfigurations(ConfigurationPropertyRepresenter.fromJSONArray(jsonReader, "configuration"));
        return pluggableArtifactConfig;
    }
}


text:
<?php

require_once('config.php');
require_once('common.php');
session_start();

mysql_connect(DB_SERVER,DB_USER,DB_PASS);
@mysql_select_db(DB_NAME) or die( "Unable to select database");

// If id not specified, go to the home page.
if(!isset($_GET['id'])) {
	header('Location: /');
	die();
} else {
	$id = $_GET['id'];
}

// Get the story from the database.
$query = "SELECT * FROM stories WHERE (id = " . $id . ")";
$result = mysql_query($query);
$story = mysql_fetch_assoc($result);

// If the user has asked for a story that doesn't exist, redirect to the homepage.
if ($story == false) {
	header('Location: /');
	die();
}

// Get author's display name
$query = "SELECT * FROM users WHERE (id = " . $story['userid'] . ")";
$result = mysql_query($query);
$displayname = mysql_fetch_assoc($result);

// Get picture's URL
$query = "SELECT * FROM pictures WHERE (id = " . $story['pictureid'] . ")";
$result = mysql_query($query);
$picture = mysql_fetch_assoc($result);

// Get gravatar
$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $displayname['email'] ) ) ) . "?d=identicon&s=50";

// Get adult check
$isadult = adultCheck();

$title = "\"" . $story['title'] . "\" by " . $displayname['displayname'];

include('header.php');
?>

				<a href="<?php echo("/picture/" . $picture['id']); ?>"><img id="insetpicture" src="<?php echo($picture['url']); ?>" title="<?php echo($picture['title']); ?>" />

					<?php foreach(explode(" ", strip_tags($story['title'])) as $key => $line) {
						if (strlen($line) > 30) $story['title'] = str_replace($line, wordwrap($line, 25, "- ", 1), $story['title']);
					}
					echo($story['title']); ?>

<img src="<?php echo $grav_url; ?>" />

					Written by <a href="/user/<?php echo($story['userid']) ?>"><?php echo($displayname['displayname'] . "");
					if ($story['userid'] == $_SESSION['userID']) {
						echo(" (Edit this story)");
					}
					echo("
Posted on " . date("jS F Y", strtotime($story['submitdate'])) . "
");

					if ($story['adult'] > 0) {
						echo("This story contains adult content.
");
					}

					if ($story['stars'] == -1) {
						echo("No votes yet!
");
					} else {
						for ($i=0; $i<$story['stars']; $i++)  echo("");
						for ($i=0; $i<(5-$story['stars']); $i++)  echo("");
					}

if ((isset($_SESSION['userID'])) && ($story['userid'] != $_SESSION['userID'])) {
	// Get user's old vote, if it exists
	$query = "SELECT * FROM votes WHERE (userid = " . $_SESSION['userID'] . ") AND (storyid = " . $story['id'] . ")";
	$result = mysql_query($query);
	$voterow = mysql_fetch_assoc($result);
	if ($voterow == false) {
		$default = "";
	} else {
		$default = $voterow['stars'];
	}

?>

			<form name="voteform" method="post" action="/votecallback.php">
		        My opinion:
				<select name="stars" onchange="this.form.submit()">
					<option <?php if ($default == "") { echo('selected'); } ?>></option>
					<option <?php if ($default == "0") { echo('selected'); } ?>>0</option>
					<option <?php if ($default == "1") { echo('selected'); } ?>>1</option>
					<option <?php if ($default == "2") { echo('selected'); } ?>>2</option>
					<option <?php if ($default == "3") { echo('selected'); } ?>>3</option>
					<option <?php if ($default == "4") { echo('selected'); } ?>>4</option>
					<option <?php if ($default == "5") { echo('selected'); } ?>>5</option>
				</select> stars
				<input type="hidden" name="storyid" value="<?php echo($story['id']); ?>">
		     </form>

<?php } ?>

	<a href="/report.php?storyid=<?php echo($story['id']); ?>">Report this story?

					<?php
					if (($story['adult'] > 0) && ($isadult == "no")) {
						echo("
Sorry, but your date of birth restricts you from viewing adult content.
");
					} else {
						echo("
" . str_replace("\n", "

", $story['text']) . "
");
					}
					 ?>

<?php

// Get comments
$query = "SELECT * FROM comments WHERE (storyid = " . $story['id'] . ")";
$comments = mysql_query($query);

// Only print the comments header if there are some, or if the user is logged in (so we're displaying a comment form).
if ((mysql_num_rows($comments) > 0) || (isset($_SESSION['userID']))) {
    echo("
Comments
");
    if ($story['critique']) {
        echo("
The author has requested critique for this story.  Fire away!
");
    } else {
        echo("
The author has not requested critique for this story.  Please be nice!
");
    }
}

while ($comment = mysql_fetch_assoc($comments)) {

	// Get author's display name
	$query = "SELECT * FROM users WHERE (id = " . $comment['userid'] . ")";
	$result = mysql_query($query);
	$displayname = mysql_fetch_assoc($result);

	// Get gravatar
	$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $displayname['email'] ) ) ) . "?d=identicon&s=50";

?>

<img src="<?php echo $grav_url; ?>" />

					<a href="/user/<?php echo($comment['userid']) ?>"><?php echo($displayname['displayname'] . "");
					echo(" — " . date("g:ia, jS F Y", strtotime($comment['submitdate'])) . "
"); ?>

					<?php echo("
" . str_replace("\n", "

", $comment['text']) . "
"); ?>

<?php
}
if (isset($_SESSION['userID'])) {
?>

					<form name="submitcommentform" method="post" action="/submitcommentcallback.php">
	        			<textarea name="text" type="text" id="text" style="width:400px; height:200px;"></textarea>

						<input type="hidden" name="storyid" value="<?php echo($story['id']); ?>">
						<input type="submit" name="Submit" value="Submit">
	        		</form>

<?php } ?>

<?php

$displayfootertext = true;
include('footer.php');

mysql_close();

?>


text:
package org.apache.beam.sdk.fn.channel;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

import org.apache.beam.model.pipeline.v1.Endpoints;
import org.apache.beam.vendor.grpc.v1p36p0.io.grpc.ManagedChannel;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link ManagedChannelFactory}. */
@RunWith(JUnit4.class)
public class ManagedChannelFactoryTest {
  @Rule public TemporaryFolder tmpFolder = new TemporaryFolder();

  @Test
  public void testDefaultChannel() {
    Endpoints.ApiServiceDescriptor apiServiceDescriptor =
        Endpoints.ApiServiceDescriptor.newBuilder().setUrl("localhost:123").build();
    ManagedChannel channel =
        ManagedChannelFactory.createDefault().forDescriptor(apiServiceDescriptor);
    assertEquals("localhost:123", channel.authority());
    channel.shutdownNow();
  }

  @Test
  public void testEpollHostPortChannel() {
    assumeTrue(SystemUtils.IS_OS_LINUX);
    assertTrue(org.apache.beam.vendor.grpc.v1p36p0.io.netty.channel.epoll.Epoll.isAvailable());
    Endpoints.ApiServiceDescriptor apiServiceDescriptor =
        Endpoints.ApiServiceDescriptor.newBuilder().setUrl("localhost:123").build();
    ManagedChannel channel =
        ManagedChannelFactory.createEpoll().forDescriptor(apiServiceDescriptor);
    assertEquals("localhost:123", channel.authority());
    channel.shutdownNow();
  }

  @Test
  public void testEpollDomainSocketChannel() throws Exception {
    assumeTrue(SystemUtils.IS_OS_LINUX);
    assertTrue(org.apache.beam.vendor.grpc.v1p36p0.io.netty.channel.epoll.Epoll.isAvailable());
    Endpoints.ApiServiceDescriptor apiServiceDescriptor =
        Endpoints.ApiServiceDescriptor.newBuilder()
            .setUrl("unix://" + tmpFolder.newFile().getAbsolutePath())
            .build();
    ManagedChannel channel =
        ManagedChannelFactory.createEpoll().forDescriptor(apiServiceDescriptor);
    assertEquals(apiServiceDescriptor.getUrl().substring("unix://".length()), channel.authority());
    channel.shutdownNow();
  }
}


text:
package dagger.hilt.android;

import static com.google.common.truth.Truth.assertThat;

import android.os.Build;
import androidx.fragment.app.FragmentActivity;
import androidx.test.core.app.ActivityScenario;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import dagger.hilt.android.testing.HiltAndroidRule;
import dagger.hilt.android.testing.HiltAndroidTest;
import dagger.hilt.android.testing.HiltTestApplication;
import javax.inject.Inject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

@HiltAndroidTest
@RunWith(AndroidJUnit4.class)
// Robolectric requires Java9 to run API 29 and above, so use API 28 instead
@Config(sdk = Build.VERSION_CODES.P, application = HiltTestApplication.class)
public class QualifierInKotlinFieldsTest {

  @Rule public final HiltAndroidRule rule = new HiltAndroidRule(this);

  @Test
  public void activityFactory() {
    try (ActivityScenario<TestActivity> scenario = ActivityScenario.launch(TestActivity.class)) {
      scenario.onActivity(
          activity -> {
            assertThat(activity.object.appContext).isNotNull();
            assertThat(activity.object.activityContext).isNotNull();
          });
    }
  }

  // This test activity injects a class that is defined in Kotlin because we want to test the
  // qualifiers in Kotlin fields / properties (generated getters and setter with backing field).
  // Ideally we would write this test in Kotlin, but there is no open fule for writting android
  // local tests in Kotlin.
  @AndroidEntryPoint(FragmentActivity.class)
  public static final class TestActivity extends Hilt_QualifierInKotlinFieldsTest_TestActivity {
    @Inject QualifierInFieldsClass object;
  }
}


text:
package draco18s.decay.client;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.RenderLiving;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;

import draco18s.decay.entities.EntityBlinkDog;

@SideOnly(Side.CLIENT)
public class RenderBlinkDog extends RenderLiving
{
	private static final ResourceLocation textures = new ResourceLocation("decayingworld:textures/mob/blinkdog.png");
    public RenderBlinkDog()
    {
        //super(par1ModelBase, par3);
    	//ModelBase model = new ModelBlinkDog();
        super(new ModelBlinkDog(), 0.5F);
        //this.setRenderPassModel(model);
    }

    protected float getTailRotation(EntityBlinkDog par1EntityWolf, float par2)
    {
        return par1EntityWolf.getTailRotation();
    }

    protected int func_82447_a(EntityBlinkDog par1EntityWolf, int par2, float par3)
    {
        float f1;

        if (par2 == 0 && par1EntityWolf.getWolfShaking())
        {
            f1 = par1EntityWolf.getBrightness(par3) * par1EntityWolf.getShadingWhileShaking(par3);
            this.bindTexture(textures);
            GL11.glColor3f(f1, f1, f1);
            return 1;
        }
        else
        {
            return -1;
        }
    }

    /**
     * Queries whether should render the specified pass or not.
     */
    protected int shouldRenderPass(EntityLiving par1EntityLiving, int par2, float par3)
    {
        return this.func_82447_a((EntityBlinkDog)par1EntityLiving, par2, par3);
    }

    /**
     * Defines what float the third param in setRotationAngles of ModelBase is
     */
    protected float handleRotationFloat(EntityLiving par1EntityLiving, float par2)
    {
        return this.getTailRotation((EntityBlinkDog)par1EntityLiving, par2);
    }

	@Override
	protected ResourceLocation getEntityTexture(Entity entity) {
		return textures;
	}
}


text:
Rails.application.routes.draw do
  mount ConstructorCms::Engine => '/'
end


text:
namespace net {

class AddressList;
class BoundNetLog;
class HostResolverImpl;
class HostResolverProc;
class NetLog;

// This class represents the task of resolving hostnames (or IP address
// literal) to an AddressList object.
//
// HostResolver can handle multiple requests at a time, so when cancelling a
// request the RequestHandle that was returned by Resolve() needs to be
// given.  A simpler alternative for consumers that only have 1 outstanding
// request at a time is to create a SingleRequestHostResolver wrapper around
// HostResolver (which will automatically cancel the single request when it
// goes out of scope).
class HostResolver {
 public:
  // The parameters for doing a Resolve(). A hostname and port are required,
  // the rest are optional (and have reasonable defaults).
  class RequestInfo {
   public:
    explicit RequestInfo(const HostPortPair& host_port_pair);

    const HostPortPair& host_port_pair() const { return host_port_pair_; }
    void set_host_port_pair(const HostPortPair& host_port_pair) {
      host_port_pair_ = host_port_pair;
    }

    int port() const { return host_port_pair_.port(); }
    const std::string& hostname() const { return host_port_pair_.host(); }

    AddressFamily address_family() const { return address_family_; }
    void set_address_family(AddressFamily address_family) {
      address_family_ = address_family;
    }

    HostResolverFlags host_resolver_flags() const {
      return host_resolver_flags_;
    }
    void set_host_resolver_flags(HostResolverFlags host_resolver_flags) {
      host_resolver_flags_ = host_resolver_flags;
    }

    bool allow_cached_response() const { return allow_cached_response_; }
    void set_allow_cached_response(bool b) { allow_cached_response_ = b; }

    bool only_use_cached_response() const { return only_use_cached_response_; }
    void set_only_use_cached_response(bool b) { only_use_cached_response_ = b; }

    bool is_speculative() const { return is_speculative_; }
    void set_is_speculative(bool b) { is_speculative_ = b; }

    RequestPriority priority() const { return priority_; }
    void set_priority(RequestPriority priority) { priority_ = priority; }

    const GURL& referrer() const { return referrer_; }
    void set_referrer(const GURL& referrer) { referrer_ = referrer; }

   private:
    // The hostname to resolve, and the port to use in resulting sockaddrs.
    HostPortPair host_port_pair_;

    // The address family to restrict results to.
    AddressFamily address_family_;

    // Flags to use when resolving this request.
    HostResolverFlags host_resolver_flags_;

    // Whether it is ok to return a result from the host cache.
    bool allow_cached_response_;

    // Whether the response will only use the cache.
    bool only_use_cached_response_;

    // Whether this request was started by the DNS prefetcher.
    bool is_speculative_;

    // The priority for the request.
    RequestPriority priority_;

    // Optional data for consumption by observers. This is the URL of the
    // page that lead us to the navigation, for DNS prefetcher's benefit.
    GURL referrer_;
  };

  // Interface for observing the requests that flow through a HostResolver.
  class Observer {
   public:
    virtual ~Observer() {}

    // Called at the start of HostResolver::Resolve(). |id| is a unique number
    // given to the request, so it can be matched up with a corresponding call
    // to OnFinishResolutionWithStatus() or OnCancelResolution().
    virtual void OnStartResolution(int id, const RequestInfo& info) = 0;

    // Called on completion of request |id|. Note that if the request was
    // cancelled, OnCancelResolution() will be called instead.
    virtual void OnFinishResolutionWithStatus(int id, bool was_resolved,
                                              const RequestInfo& info) = 0;

    // Called when request |id| has been cancelled. A request is "cancelled"
    // if either the HostResolver is destroyed while a resolution is in
    // progress, or HostResolver::CancelRequest() is called.
    virtual void OnCancelResolution(int id, const RequestInfo& info) = 0;
  };

  // Opaque type used to cancel a request.
  typedef void* RequestHandle;

  // This value can be passed into CreateSystemHostResolver as the
  // |max_concurrent_resolves| parameter. It will select a default level of
  // concurrency.
  static const size_t kDefaultParallelism = 0;

  // If any completion callbacks are pending when the resolver is destroyed,
  // the host resolutions are cancelled, and the completion callbacks will not
  // be called.
  virtual ~HostResolver();

  // Resolves the given hostname (or IP address literal), filling out the
  // |addresses| object upon success.  The |info.port| parameter will be set as
  // the sin(6)_port field of the sockaddr_in{6} struct.  Returns OK if
  // successful or an error code upon failure.
  //
  // When callback is null, the operation completes synchronously.
  //
  // When callback is non-null, the operation may be performed asynchronously.
  // If the operation cannnot be completed synchronously, ERR_IO_PENDING will
  // be returned and the real result code will be passed to the completion
  // callback.  Otherwise the result code is returned immediately from this
  // call.
  // If |out_req| is non-NULL, then |*out_req| will be filled with a handle to
  // the async request. This handle is not valid after the request has
  // completed.
  //
  // Profiling information for the request is saved to |net_log| if non-NULL.
  virtual int Resolve(const RequestInfo& info,
                      AddressList* addresses,
                      CompletionCallback* callback,
                      RequestHandle* out_req,
                      const BoundNetLog& net_log) = 0;

  // Cancels the specified request. |req| is the handle returned by Resolve().
  // After a request is cancelled, its completion callback will not be called.
  virtual void CancelRequest(RequestHandle req) = 0;

  // Adds an observer to this resolver. The observer will be notified of the
  // start and completion of all requests (excluding cancellation). |observer|
  // must remain valid for the duration of this HostResolver's lifetime.
  virtual void AddObserver(Observer* observer) = 0;

  // Unregisters an observer previously added by AddObserver().
  virtual void RemoveObserver(Observer* observer) = 0;

  // Sets the default AddressFamily to use when requests have left it
  // unspecified. For example, this could be used to restrict resolution
  // results to AF_INET by passing in ADDRESS_FAMILY_IPV4, or to
  // AF_INET6 by passing in ADDRESS_FAMILY_IPV6.
  virtual void SetDefaultAddressFamily(AddressFamily address_family) {}
  virtual AddressFamily GetDefaultAddressFamily() const;

  // Returns |this| cast to a HostResolverImpl*, or NULL if the subclass
  // is not compatible with HostResolverImpl. Used primarily to expose
  // additional functionality on the about:net-internals page.
  virtual HostResolverImpl* GetAsHostResolverImpl();

  // Does additional cleanup prior to destruction.
  virtual void Shutdown() {}

 protected:
  HostResolver();

 private:
  DISALLOW_COPY_AND_ASSIGN(HostResolver);
};

// This class represents the task of resolving a hostname (or IP address
// literal) to an AddressList object.  It wraps HostResolver to resolve only a
// single hostname at a time and cancels this request when going out of scope.
class SingleRequestHostResolver {
 public:
  // |resolver| must remain valid for the lifetime of |this|.
  explicit SingleRequestHostResolver(HostResolver* resolver);

  // If a completion callback is pending when the resolver is destroyed, the
  // host resolution is cancelled, and the completion callback will not be
  // called.
  ~SingleRequestHostResolver();

  // Resolves the given hostname (or IP address literal), filling out the
  // |addresses| object upon success. See HostResolver::Resolve() for details.
  int Resolve(const HostResolver::RequestInfo& info,
              AddressList* addresses,
              CompletionCallback* callback,
              const BoundNetLog& net_log);

  // Cancels the in-progress request, if any. This prevents the callback
  // from being invoked. Resolve() can be called again after cancelling.
  void Cancel();

 private:
  // Callback for when the request to |resolver_| completes, so we dispatch
  // to the user's callback.
  void OnResolveCompletion(int result);

  // The actual host resolver that will handle the request.
  HostResolver* const resolver_;

  // The current request (if any).
  HostResolver::RequestHandle cur_request_;
  CompletionCallback* cur_request_callback_;

  // Completion callback for when request to |resolver_| completes.
  CompletionCallbackImpl<SingleRequestHostResolver> callback_;

  DISALLOW_COPY_AND_ASSIGN(SingleRequestHostResolver);
};

// Creates a HostResolver implementation using |resolver_proc| as resolver,
// (which if NULL, will default to getaddrinfo() wrapper) that queries the
// underlying system, |max_concurrent_resolves| is how many resolve
// requests will be allowed to run in parallel. Pass
// HostResolver::kDefaultParallelism to choose a default value.
HostResolver* CreateSystemHostResolver(size_t max_concurrent_resolves,
                                       HostResolverProc* resolver_proc,
                                       NetLog* net_log);

}  // namespace net

#endif  // NET_BASE_HOST_RESOLVER_H_


text:
package org.apache.tapestry5.integration.cluster.pages;

import org.apache.tapestry5.integration.cluster.base.BaseSessionDemo;
import org.apache.tapestry5.integration.cluster.data.MutablePojo;

public class PersistedMutablePojoDemo extends BaseSessionDemo<MutablePojo> {

    @Override
    public MutablePojo create(String value) {
        return new MutablePojo(value);
    }
}


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/switch_on"></item>
    <item android:drawable="@drawable/switch_off"></item>
</selector>


text:
var ko = (function (ko) {
    ko.Action = function (duration, actionEase) {
        this.duration = duration;
        this.actionEase = actionEase;
        this.value = 0;
        this.elapsed = 0;
    };
    ko.Action.prototype.init = function (target) {
        this.value = 0;
        this.target = target;
        this.elapsed = 0;
    };
    ko.Action.prototype.update = function (delta) {
        if (!this.duration) {
            // When the duration is zero we just want to perform the action
            // with a value of one
            this.value = 1;
            this.perform();
            return;
        }
        if (this.isComplete()) {
            // We are already done with this action
            return;
        }
        this.elapsed += delta;
        if (this.elapsed > this.duration) {
            this.elapsed = this.duration;
        }
        if (this.actionEase) {
            this.value = this.actionEase(this.elapsed / this.duration);
        } else {
            this.value = Math.max(0, Math.min(1,
                this.elapsed / this.duration));
        }
        this.perform();
    };
    ko.Action.prototype.perform = function () {
    };
    ko.Action.prototype.isComplete = function () {
        if (!this.duration) {
            return true;
        }
        return this.elapsed >= this.duration;
    };
    ko.MoveTo = function (x, y, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.moveTo = { x: x, y: y };
    };
    ko.MoveTo.prototype = Object.create(ko.Action.prototype);
    ko.MoveTo.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.moveFrom = {
            x: target.position.x,
            y: target.position.y
        };
    };
    ko.MoveTo.prototype.perform = function () {
        this.target.position.x = this.moveFrom.x +
            ((this.moveTo.x - this.moveFrom.x) * this.value);
        this.target.position.y = this.moveFrom.y +
            ((this.moveTo.y - this.moveFrom.y) * this.value);
    };
    ko.MoveBy = function (x, y, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.moveBy = { x: x, y: y };
    };
    ko.MoveBy.prototype = Object.create(ko.Action.prototype);
    ko.MoveBy.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.moveFrom = {
            x: target.position.x,
            y: target.position.y
        };
    };
    ko.MoveBy.prototype.perform = function () {
        this.target.position.x = this.moveFrom.x + this.moveBy.x * this.value;
        this.target.position.y = this.moveFrom.y + this.moveBy.y * this.value;
    };
    ko.ScaleTo = function (scaleTo, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.scaleTo = scaleTo;
    };
    ko.ScaleTo.prototype = Object.create(ko.Action.prototype);
    ko.ScaleTo.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.scaleFrom = target.scale;
    };
    ko.ScaleTo.prototype.perform = function () {
        this.target.scale = this.scaleFrom +
            ((this.scaleTo - this.scaleFrom) * this.value);
    };
    ko.ScaleBy = function (scaleBy, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.scaleBy = scaleBy;
    };
    ko.ScaleBy.prototype = Object.create(ko.Action.prototype);
    ko.ScaleBy.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.scaleFrom = target.scale;
    };
    ko.ScaleBy.prototype.perform = function () {
        this.target.scale = this.scaleFrom + this.scaleBy * this.value;
    };
    ko.RotateTo = function (rotateTo, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.rotateTo = rotateTo;
    };
    ko.RotateTo.prototype = Object.create(ko.Action.prototype);
    ko.RotateTo.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.rotateFrom = target.rotation;
    };
    ko.RotateTo.prototype.perform = function () {
        this.target.rotation = this.rotateFrom +
            ((this.rotateTo - this.rotateFrom) * this.value);
    };
    ko.RotateBy = function (rotateBy, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.rotateBy = rotateBy;
    };
    ko.RotateBy.prototype = Object.create(ko.Action.prototype);
    ko.RotateBy.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.rotateFrom = target.rotation;
    };
    ko.RotateBy.prototype.perform = function () {
        this.target.rotation = this.rotateFrom + this.rotateBy * this.value;
    };
    ko.FadeTo = function (fadeTo, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.fadeTo = fadeTo;
    };
    ko.FadeTo.prototype = Object.create(ko.Action.prototype);
    ko.FadeTo.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.fadeFrom = target.opacity;
    };
    ko.FadeTo.prototype.perform = function () {
        this.target.opacity = this.fadeFrom +
            ((this.fadeTo - this.fadeFrom) * this.value);
    };
    ko.FadeBy = function (fadeBy, duration, actionEase) {
        ko.Action.call(this, duration, actionEase);
        this.fadeBy = fadeBy;
    };
    ko.FadeBy.prototype = Object.create(ko.Action.prototype);
    ko.FadeBy.prototype.init = function (target) {
        ko.Action.prototype.init.call(this, target);
        this.fadeFrom = target.opacity;
    };
    ko.FadeBy.prototype.perform = function () {
        this.target.opacity = this.fadeFrom + this.fadeBy * this.value;
    };
    ko.Wait = function (duration) {
        ko.Action.call(this, duration);
    };
    ko.Wait.prototype = Object.create(ko.Action.prototype);
    ko.Call = function (func, args) {
        ko.Action.call(this, 0);
        this.func = func;
        this.args = args;
    };
    ko.Call.prototype = Object.create(ko.Action.prototype);
    ko.Call.prototype.perform = function () {
        if (!this.func) {
            return;
        }
        this.func(this.args);
    };
    // Ease functions based on code from http://www.cocos2d-iphone.org/
    ko.actionEase = {
        backIn: function (t) {
            var overshoot = 1.70158;
            return t * t * ((overshoot + 1) * t - overshoot);
        },
        backOut: function (t) {
            var overshoot = 1.70158;
            t = t - 1;
            return t * t * ((overshoot + 1) * t + overshoot) + 1;
        },
        backInOut: function (t) {
            var overshoot = 1.70158 * 1.525;
            t = t * 2;
            if (t < 1) {
                return (t * t * ((overshoot + 1) * t - overshoot)) / 2;
            } else {
                t = t - 2;
                return (t * t * ((overshoot + 1) * t + overshoot)) / 2 + 1;
            }
        },
        sineIn: function (t) {
            return -1 * Math.cos(t * Math.PI / 2) + 1;
        },
        sineOut: function (t) {
            return Math.sin(t * (Math.PI / 2));
        },
        sineInOut: function (t) {
            return -0.5 * (Math.cos(Math.PI * t) - 1);
        }
    };
    return ko;
})(ko || {});


text:
.class Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;
.super Ljava/lang/Object;
.source "IdleConnectionHandler.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/apache/http/impl/conn/IdleConnectionHandler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "TimeValues"
.end annotation

# instance fields
.field private final timeAdded:J

.field private final timeExpires:J

# direct methods
.method constructor <init>(JJLjava/util/concurrent/TimeUnit;)V
    .locals 2
    .param p1, "now"    # J
    .param p3, "validDuration"    # J
    .param p5, "validUnit"    # Ljava/util/concurrent/TimeUnit;

    .prologue
    .line 181
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 182
    iput-wide p1, p0, Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;->timeAdded:J

    .line 183
    const-wide/16 v0, 0x0

    cmp-long v0, p3, v0

    if-lez v0, :cond_0

    .line 184
    invoke-virtual {p5, p3, p4}, Ljava/util/concurrent/TimeUnit;->toMillis(J)J

    move-result-wide v0

    add-long/2addr v0, p1

    iput-wide v0, p0, Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;->timeExpires:J

    .line 188
    :goto_0
    return-void

    .line 186
    :cond_0
    const-wide v0, 0x7fffffffffffffffL

    iput-wide v0, p0, Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;->timeExpires:J

    goto :goto_0
.end method

.method static synthetic access$000(Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;)J
    .locals 2
    .param p0, "x0"    # Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;

    .prologue
    .line 172
    iget-wide v0, p0, Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;->timeExpires:J

    return-wide v0
.end method

.method static synthetic access$100(Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;)J
    .locals 2
    .param p0, "x0"    # Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;

    .prologue
    .line 172
    iget-wide v0, p0, Lorg/apache/http/impl/conn/IdleConnectionHandler$TimeValues;->timeAdded:J

    return-wide v0
.end method


text:
import re, os, os.path
import webracer.utils
from wolis import utils
from wolis.test_case import WolisTestCase

class SphinxConfigTest(WolisTestCase):
    def test_obtain_config(self):
        self.login('morpheus', 'morpheus')
        self.acp_login('morpheus', 'morpheus')

        start_url = '/adm/index.php'
        self.get_with_sid(start_url)
        self.assert_successish()

        assert 'Board statistics' in self.response.body

        url = self.response.urljoin(self.link_href_by_text('Search settings'))
        assert 'i=acp_search' in url
        assert 'mode=settings' in url
        self.get(url)
        self.assert_successish()

        assert 'Here you can define what search backend will be used' in self.response.body
        assert 'Sphinx config file' in self.response.body

        form = self.response.form()
        elements = form.elements.mutable
        elements.set_value('config[fulltext_sphinx_data_path]', self.conf.sphinx_data_path + '/')
        # change port to something non-default
        elements.set_value('config[fulltext_sphinx_port]', str(self.conf.sphinx_searchd_port))
        self.post(form.computed_action, elements.params.list)
        self.assert_successish()

        assert 'Configuration updated successfully.' in self.response.body

        self.get(url)
        self.assert_successish()

        doc = self.response.lxml_etree
        # wtfs:
        # 1. unclosed span in sphinx config file line
        # 2. textarea has no name, no id, no class
        # 3. textarea contents is not html-escaped, but contains angle brackets
        element = webracer.utils.xpath_first_check(doc,
            '//label[@for="fulltext_sphinx_config_file"]/ancestor::dl//textarea')
        config_text = element.text
        #form = self.response.form()
        #config_text = form.params.dict['config[fulltext_sphinx_config_file]']

        original_pid = r'pid_file = %s' % os.path.join(self.conf.sphinx_data_path, 'searchd.pid')
        assert original_pid in config_text
        replaced_pid = r'pid_file = %s' % self.conf.sphinx_pidfile_path
        config_text = config_text.replace(original_pid, replaced_pid)

        original_log = os.path.join(self.conf.sphinx_data_path, 'log')
        assert original_log in config_text
        config_text = config_text.replace(original_log, self.conf.sphinx_log_path)

        cmd = self.conf.sphinx_cmd_prefix or []
        help_text = utils.run(cmd + ['searchd', '-h'], return_stdout=True)
        match = re.match('Sphinx (\d+(?:\.\d+)*)', help_text)
        assert match, "Sphinx version not found in help text:\n" + help
        sphinx_version = match.group(1)
        print("Detected sphinx version: %s" % sphinx_version)
        sphinx_version = map(int, sphinx_version.split('.'))

        if sphinx_version[0] < 3:
            # 0.9.9 shipping with debian squeeze
            directives = ['compat_sphinxql_magics', 'binlog_path']
            for directive in directives:
                config_text = re.compile(r'^(\s*)(%s)\b' % directive, re.M).sub(r'\1#\2', config_text)

        utils.mkdir_p(self.conf.sphinx_root)
        with open(self.conf.sphinx_config_path, 'w') as f:
            f.write(config_text)

        match = re.search(r'source source_phpbb_(\w+)_main', config_text)
        assert match
        sphinx_id = match.group(1)
        with open(self.conf.sphinx_id_path, 'w') as f:
            f.write(sphinx_id)

        if self.conf.sphinx_cmd_prefix:
            cmd = self.conf.sphinx_cmd_prefix
            utils.run(cmd + ['rm', '-rf', self.conf.sphinx_data_path, self.conf.sphinx_log_path], no_check=True)
        else:
            import shutil
            if os.path.exists(self.conf.sphinx_data_path):
                shutil.rmtree(self.conf.sphinx_data_path)
            if os.path.exists(self.conf.sphinx_log_path):
                shutil.rmtree(self.conf.sphinx_log_path)

        utils.mkdir_p(self.conf.sphinx_data_path)
        utils.mkdir_p(self.conf.sphinx_log_path)

        if self.conf.sphinx_cmd_prefix:
            os.chmod(self.conf.sphinx_data_path, 0o777)
            os.chmod(self.conf.sphinx_log_path, 0o777)
            # for pid file
            os.chmod(self.conf.sphinx_root, 0o777)

if __name__ == '__main__':
    import unittest
    unittest.main()


text:
.class Lcom/android/server/pm/PackageManagerService$FileInstallArgs$1;
.super Lcom/android/internal/os/IParcelFileDescriptorFactory$Stub;
.source "PackageManagerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/pm/PackageManagerService$FileInstallArgs;->copyApk(Lcom/android/internal/app/IMediaContainerService;Z)I
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/server/pm/PackageManagerService$FileInstallArgs;

# direct methods
.method constructor <init>(Lcom/android/server/pm/PackageManagerService$FileInstallArgs;)V
    .locals 0

    .prologue
    .line 10324
    iput-object p1, p0, Lcom/android/server/pm/PackageManagerService$FileInstallArgs$1;->this$1:Lcom/android/server/pm/PackageManagerService$FileInstallArgs;

    invoke-direct {p0}, Lcom/android/internal/os/IParcelFileDescriptorFactory$Stub;-><init>()V

    return-void
.end method

# virtual methods
.method public open(Ljava/lang/String;I)Landroid/os/ParcelFileDescriptor;
    .locals 6
    .param p1, "name"    # Ljava/lang/String;
    .param p2, "mode"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    .line 10327
    invoke-static {p1}, Landroid/os/FileUtils;->isValidExtFilename(Ljava/lang/String;)Z

    move-result v3

    if-nez v3, :cond_0

    .line 10328
    new-instance v3, Ljava/lang/IllegalArgumentException;

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Invalid filename: "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-direct {v3, v4}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v3

    .line 10331
    :cond_0
    :try_start_0
    new-instance v2, Ljava/io/File;

    iget-object v3, p0, Lcom/android/server/pm/PackageManagerService$FileInstallArgs$1;->this$1:Lcom/android/server/pm/PackageManagerService$FileInstallArgs;

    # getter for: Lcom/android/server/pm/PackageManagerService$FileInstallArgs;->codeFile:Ljava/io/File;
    invoke-static {v3}, Lcom/android/server/pm/PackageManagerService$FileInstallArgs;->access$3600(Lcom/android/server/pm/PackageManagerService$FileInstallArgs;)Ljava/io/File;

    move-result-object v3

    invoke-direct {v2, v3, p1}, Ljava/io/File;-><init>(Ljava/io/File;Ljava/lang/String;)V

    .line 10332
    .local v2, "file":Ljava/io/File;
    invoke-virtual {v2}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v3

    sget v4, Landroid/system/OsConstants;->O_RDWR:I

    sget v5, Landroid/system/OsConstants;->O_CREAT:I

    or-int/2addr v4, v5

    const/16 v5, 0x1a4

    invoke-static {v3, v4, v5}, Landroid/system/Os;->open(Ljava/lang/String;II)Ljava/io/FileDescriptor;

    move-result-object v1

    .line 10334
    .local v1, "fd":Ljava/io/FileDescriptor;
    invoke-virtual {v2}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v3

    const/16 v4, 0x1a4

    invoke-static {v3, v4}, Landroid/system/Os;->chmod(Ljava/lang/String;I)V

    .line 10335
    new-instance v3, Landroid/os/ParcelFileDescriptor;

    invoke-direct {v3, v1}, Landroid/os/ParcelFileDescriptor;-><init>(Ljava/io/FileDescriptor;)V
    :try_end_0
    .catch Landroid/system/ErrnoException; {:try_start_0 .. :try_end_0} :catch_0

    return-object v3

    .line 10336
    .end local v1    # "fd":Ljava/io/FileDescriptor;
    .end local v2    # "file":Ljava/io/File;
    :catch_0
    move-exception v0

    .line 10337
    .local v0, "e":Landroid/system/ErrnoException;
    new-instance v3, Landroid/os/RemoteException;

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Failed to open: "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v0}, Landroid/system/ErrnoException;->getMessage()Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-direct {v3, v4}, Landroid/os/RemoteException;-><init>(Ljava/lang/String;)V

    throw v3
.end method


text:
//
//  AVAssetTrack+ACY_UIImageOrientation.h
//  Pods
//
//  Created by Arthur Liu on 2017/05/26.
//
//

#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

@interface AVAssetTrack (ACY_UIImageOrientation)

- (CGSize)acy_displaySize;
- (UIImageOrientation)acy_imageOrientation;

- (CGAffineTransform)acy_transformByFrame:(CGRect)frame;

/**
 Return a correct rect for cropping method.

 @param contentsRect Same meaning of layer.contentsRect. So the value in it is with [0, 1].
 @return A CGRect value which will be used in the crop method.
 */
- (CGRect)acy_cropRectangleByContentsRect:(CGRect)contentsRect;

@end