text:
A remote control for the dokku program on your server.

## Usage

## Credits

The initial structure of this module was generated by [Jumpstart](https://github.com/meryn/jumpstart), using the [Jumpstart Black Coffee](https://github.com/meryn/jumpstart-black-coffee) template.

## License

dokku-remote is released under the [MIT License](http://opensource.org/licenses/MIT).
Copyright (c) 2013 Meryn Stol

redpajama_set_name: RedPajamaGithub


text:
Just a test application which needs the following commands to run:

npm i
npm run start

For test therea few testcases to be tested with:

npm run test


text:
/*
 * Taken from http://www.glassechidna.com.au/2009/devblogs/s3tc-dxt1dxt5-texture-decompression/
 */

// --------------------------------------------------------------------------------
// S3TC DXT1 / DXT5 Texture Decompression Routines
// Author: Benjamin Dobell - http://www.glassechidna.com.au
//
// Feel free to use these methods in any open-source, freeware or commercial
// projects. It's not necessary to credit me however I would be grateful if you
// chose to do so. I'll also be very interested to hear what projects make use of
// this code. Feel free to drop me a line via the contact form on the Glass Echidna
// website.
//
// NOTE: The code was written for a little endian system where sizeof(long) == 4.
// --------------------------------------------------------------------------------

/**
 * unsigned long PackRGBA(): Helper method that packs RGBA channels into a single 4 byte pixel.
 *
 * unsigned char r: red channel.
 * unsigned char g: green channel.
 * unsigned char b: blue channel.
 * unsigned char a: alpha channel.
 */
unsigned long PackRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a) {
	return ((r << 24) | (g << 16) | (b << 8) | a);
}

/**
 * void DecompressBlockDXT5(): Decompresses one block of a DXT5 texture and stores the resulting pixels at the appropriate offset in 'image'.
 *
 * unsigned long x:						x-coordinate of the first pixel in the block.
 * unsigned long y:						y-coordinate of the first pixel in the block.
 * unsigned long width: 				width of the texture being decompressed.
 * unsigned long height:				height of the texture being decompressed.
 * const unsigned char *blockStorage:	pointer to the block to decompress.
 * unsigned long *image:				pointer to image where the decompressed pixel data should be stored.
 */
void DecompressBlockDXT5(unsigned long x, unsigned long y, unsigned long width, const unsigned char *blockStorage, unsigned long *image) {
	unsigned char alpha0 = *reinterpret_cast<const unsigned char *>(blockStorage);
	unsigned char alpha1 = *reinterpret_cast<const unsigned char *>(blockStorage + 1);

	const unsigned char *bits = blockStorage + 2;
	unsigned long alphaCode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24);
	unsigned short alphaCode2 = bits[0] | (bits[1] << 8);

	unsigned short color0 = *reinterpret_cast<const unsigned short *>(blockStorage + 8);
	unsigned short color1 = *reinterpret_cast<const unsigned short *>(blockStorage + 10);

	unsigned long temp;

	temp = (color0 >> 11) * 255 + 16;
	unsigned char r0 = (unsigned char)((temp/32 + temp)/32);
	temp = ((color0 & 0x07E0) >> 5) * 255 + 32;
	unsigned char g0 = (unsigned char)((temp/64 + temp)/64);
	temp = (color0 & 0x001F) * 255 + 16;
	unsigned char b0 = (unsigned char)((temp/32 + temp)/32);

	temp = (color1 >> 11) * 255 + 16;
	unsigned char r1 = (unsigned char)((temp/32 + temp)/32);
	temp = ((color1 & 0x07E0) >> 5) * 255 + 32;
	unsigned char g1 = (unsigned char)((temp/64 + temp)/64);
	temp = (color1 & 0x001F) * 255 + 16;
	unsigned char b1 = (unsigned char)((temp/32 + temp)/32);

	unsigned long code = *reinterpret_cast<const unsigned long *>(blockStorage + 12);

	for (int j=0; j < 4; j++) {
		for (int i=0; i < 4; i++) {
			int alphaCodeIndex = 3*(4*j+i);
			int alphaCode;

			if (alphaCodeIndex <= 12) {
				alphaCode = (alphaCode2 >> alphaCodeIndex) & 0x07;
			} else if (alphaCodeIndex == 15) {
				alphaCode = (alphaCode2 >> 15) | ((alphaCode1 << 1) & 0x06);
			} else { // alphaCodeIndex >= 18 && alphaCodeIndex <= 45
				alphaCode = (alphaCode1 >> (alphaCodeIndex - 16)) & 0x07;
			}

			unsigned char finalAlpha;
			if (alphaCode == 0) {
				finalAlpha = alpha0;
			} else if (alphaCode == 1) {
				finalAlpha = alpha1;
			} else {
				if (alpha0 > alpha1) {
					finalAlpha = ((8-alphaCode)*alpha0 + (alphaCode-1)*alpha1)/7;
				} else {
					if (alphaCode == 6) {
						finalAlpha = 0;
					} else if (alphaCode == 7) {
						finalAlpha = 255;
					} else {
						finalAlpha = ((6-alphaCode)*alpha0 + (alphaCode-1)*alpha1)/5;
					}
				}
			}

			unsigned char colorCode = (code >> 2*(4*j+i)) & 0x03;

			unsigned long finalColor;
			switch (colorCode) {
				case 0:
					finalColor = PackRGBA(r0, g0, b0, finalAlpha);
					break;
				case 1:
					finalColor = PackRGBA(r1, g1, b1, finalAlpha);
					break;
				case 2:
					finalColor = PackRGBA((2*r0+r1)/3, (2*g0+g1)/3, (2*b0+b1)/3, finalAlpha);
					break;
				case 3:
					finalColor = PackRGBA((r0+2*r1)/3, (g0+2*g1)/3, (b0+2*b1)/3, finalAlpha);
					break;
			}

			if (x + i < width) image[(y + j)*width + (x + i)] = finalColor;
		}
	}
}

/**
 * void BlockDecompressImageDXT5(): Decompresses all the blocks of a DXT5 compressed texture and stores the resulting pixels in 'image'.
 *
 * unsigned long width:               Texture width.
 * unsigned long height:              Texture height.
 * const unsigned char *blockStorage: pointer to compressed DXT5 blocks.
 * unsigned long *image:              pointer to the image where the decompressed pixels will be stored.
 */

void BlockDecompressImageDXT5(unsigned long width, unsigned long height, const unsigned char *blockStorage, unsigned long *image)
{
	unsigned long blockCountX = (width + 3) / 4;
	unsigned long blockCountY = (height + 3) / 4;
	unsigned long blockWidth = (width < 4) ? width : 4;
	unsigned long blockHeight = (height < 4) ? height : 4;

	for (unsigned long j = 0; j < blockCountY; j++) {
		for (unsigned long i = 0; i < blockCountX; i++) DecompressBlockDXT5(i*4, j*4, width, blockStorage + i * 16, image);
		blockStorage += blockCountX * 16;
	}
}


text:
$ less sonnets.txt
^F
^F
^F
^B
^B
^B
q

#Exercise 2: Search for the string "All" (case-sensitive). Go forward a few occurrences, then back a few occurrences. Then go to the beginning of the file and count the occurrences by searching forward until you hit the end. Compare your count to the result of running grep All sonnets.txt | wc.
/All
n
n
n
N
N
N

#Exercise 3: Using less and / ("slash"), find the sonnet that begins with the line "Let me not". Are there any other occurrences of this string in the Sonnets?
No

#Extra credit: Listen to the sonnet in both modern and original pronunciation. Which version's rhyme scheme is better?
The original, of course.

#Exercise 4: Because man uses less, we are now in a position to search man pages interactively. By searching for the string "sort" in the man page for ls, discover the option to sort files by size. What is the command to display the long form of files sorted so the largest files appear at the bottom?
$ ls -Srl


text:
package dan.dit.whatsthat.testsubject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.View;

import com.github.johnpersano.supertoasts.SuperToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import dan.dit.whatsthat.BuildConfig;
import dan.dit.whatsthat.R;
import dan.dit.whatsthat.achievement.Achievement;
import dan.dit.whatsthat.achievement.AchievementManager;
import dan.dit.whatsthat.achievement.AchievementProperties;
import dan.dit.whatsthat.riddle.RiddleInitializer;
import dan.dit.whatsthat.riddle.achievement.holders.MiscAchievementHolder;
import dan.dit.whatsthat.riddle.achievement.holders.TestSubjectAchievementHolder;
import dan.dit.whatsthat.riddle.achievement.holders.TypeAchievementHolder;
import dan.dit.whatsthat.riddle.types.PracticalRiddleType;
import dan.dit.whatsthat.testsubject.intro.Intro;
import dan.dit.whatsthat.testsubject.shopping.ShopArticleHolder;
import dan.dit.whatsthat.testsubject.shopping.sortiment.ShopArticleRiddleHints;
import dan.dit.whatsthat.testsubject.shopping.sortiment.SortimentHolder;
import dan.dit.whatsthat.util.dependencies.Dependable;
import dan.dit.whatsthat.util.dependencies.Dependency;
import dan.dit.whatsthat.util.dependencies.MinValueDependency;
import dan.dit.whatsthat.util.general.DelayedQueueProcessor;
import dan.dit.whatsthat.util.wallet.Wallet;
import dan.dit.whatsthat.util.wallet.WalletEntry;

/**
 * Created by daniel on 11.04.15.
 */
public class TestSubject {
    private static final TestSubject INSTANCE = new TestSubject();
    public static final String EMAIL_ON_ERROR = "whatsthat.contact@gmail.com";
    public static final String EMAIL_FEEDBACK = "whatsthat.feedback@gmail.com";
    private static final String TEST_SUBJECT_PREFERENCES_FILE = "dan.dit.whatsthat.testsubject_preferences";
    private static final String TEST_SUBJECT_PREF_GENDER = "key_testsubject_gender";
    public static final int DEFAULT_SKIPABLE_GAMES = 5;

    public static final int GENDER_NOT_CHOSEN = -1;
    // used for array indices
    public static final int GENDER_MALE = 0; // genders as int, not boolean .. you never know, male = 0 chosen by fair dice role, take that feminists
    public static final int GENDER_FEMALE = 1;
    public static final int GENDER_WHATEVER = 2;
    public static final int GENDER_ALIEN = 3; // :o
    public static final int GENDERS_COUNT = 4; // amount of valid genders
    public static final String SHW_KEY_MAX_AVAILABLE_RIDDLE_TYPES = "shw_key_can_choose_new_riddle";
    private static final int AVAILABLE_RIDDLES_AT_GAME_START = 1; // one additional riddle type is granted per level up (also on level 0)

    private boolean mInitialized;

    private SharedPreferences mPreferences;
    private int mGender = GENDER_NOT_CHOSEN;

    private Context mApplicationContext;
    private TestSubjectAchievementHolder mAchievementHolder;
    private Purse mPurse;
    private DelayedQueueProcessor<TestSubjectToast> mGeneralToastProcessor;
    private DelayedQueueProcessor<Achievement> mAchievementToastProcessor;
    private ShopArticleHolder mShopArticleHolder;
    private int mCurrLevel;
    private TestSubjectLevel[] mLevels;
    private TestSubjectRiddleTypeController mTypesController;

    private TestSubject() {
    }

    public static synchronized TestSubject initialize(Context context) {
        if (isInitialized()) {
            return INSTANCE;
        }
        INSTANCE.mApplicationContext = context.getApplicationContext();
        INSTANCE.initAchievementManager();
        INSTANCE.initPreferences();
        INSTANCE.initLevels();
        INSTANCE.mInitialized = true;
        INSTANCE.mAchievementHolder = new TestSubjectAchievementHolder(AchievementManager.getInstance());
        INSTANCE.mAchievementHolder.addDependencies();
        INSTANCE.mShopArticleHolder.makeDependencies();
        INSTANCE.mAchievementHolder.initAchievements();
        return INSTANCE;
    }

    public int getGender() {
        return mGender;
    }

    public void setGender(int gender) {
        mGender = gender;
        mPreferences.edit().putInt(TEST_SUBJECT_PREF_GENDER, mGender).apply();
    }

    @SuppressLint("CommitPrefEdits")
    public void saveIntro(Intro intro) {
        if (intro == null) {
            return;
        }
        intro.save(mPreferences.edit(), mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_TESTSUBJECT_LEVEL));
    }

    public Intro makeIntro(View introView) {
        int level = mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_TESTSUBJECT_LEVEL);
        TestSubjectLevel currLevel = mLevels[level];
        Intro intro = Intro.makeIntro(introView, currLevel);
        intro.load(mPreferences, level);
        return currLevel.makeIntro(intro);
    }

    public int getCurrentLevel() {
        return mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_TESTSUBJECT_LEVEL, TestSubjectLevel.LEVEL_NONE);
    }

    public int getMaximumLevel() {
        return mLevels.length - 1; // since level numbers start with zero
    }

    public Dependable getLevelDependency() {
        return mPurse.mShopWallet.assureEntry(Purse.SHW_KEY_TESTSUBJECT_LEVEL);
    }

    public void initToasts() {
        mGeneralToastProcessor = new DelayedQueueProcessor<>(new DelayedQueueProcessor.Callback<TestSubjectToast>() {
            @Override
            public long process(@NonNull TestSubjectToast toProcess) {
                showToast(toProcess);
                return toProcess.mDuration;
            }
        });
        mAchievementToastProcessor = new DelayedQueueProcessor<>(new DelayedQueueProcessor.Callback<Achievement>() {
            @Override
            public long process(@NonNull Achievement toProcess) {
                TestSubjectToast achievementToast = makeAchievementToast(toProcess);
                showToast(achievementToast);
                return achievementToast == null ? 0L : achievementToast.mDuration;
            }
        });
    }

    private void showToast(TestSubjectToast toast) {
        if (toast != null) {
            SuperToast superToast = toast.makeSuperToast(mApplicationContext);
            if (superToast != null) {
                superToast.show();
            }
        }
    }

    private TestSubjectToast makeAchievementToast(Achievement achievement) {
        if (mApplicationContext == null) {
            return null;
        }
        TestSubjectToast toast = new TestSubjectToast(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 5, achievement.getIconResId(), 0, SuperToast.Duration.LONG);
        toast.mIconPosition = SuperToast.IconPosition.LEFT;
        toast.mAnimations = SuperToast.Animations.FLYIN;
        toast.mBackground = R.drawable.achieved_background;
        toast.mTextColor = Color.BLACK;
        Resources res = mApplicationContext.getResources();
        toast.mText = res.getString(R.string.achievement_achieved) + " " + achievement.getName(res);
        return toast;
    }

    public static boolean isInitialized() {
        return INSTANCE.mInitialized;
    }

    private void initAchievementManager() {
        AchievementManager.initialize(mApplicationContext);
        AchievementManager.getInstance().addAchievementChangedListener(new AchievementManager.OnAchievementChangedListener() {
            @Override
            public void onDataEvent(AchievementManager.AchievementChangeEvent changeEvent) {
                switch (changeEvent.getChangedHint()) {
                    case AchievementManager.CHANGED_TO_ACHIEVED_AND_UNCLAIMED:
                        TestSubject.this.postAchievementAchieved(changeEvent.getAchievement());
                        break;
                    case AchievementManager.CHANGED_GOT_CLAIMED:
                        TestSubject.this.addAchievementScore(changeEvent.getAchievement()
                                .getScoreReward());
                        break;
                }
            }
        });
    }

    private void initPreferences() {
        mPreferences = mApplicationContext.getSharedPreferences(TEST_SUBJECT_PREFERENCES_FILE, Context.MODE_PRIVATE);
        mPurse = new Purse(mApplicationContext);
        mShopArticleHolder = new SortimentHolder(mApplicationContext, new ForeignPurse(mPurse));
        mGender = mPreferences.getInt(TEST_SUBJECT_PREF_GENDER, GENDER_NOT_CHOSEN);
        mTypesController = new TestSubjectRiddleTypeController(mPreferences);
    }

    public int getNextLevelUpCost() {
        if (mCurrLevel >= mLevels.length -1) {
            return -1; // already at max level
        }
        double fraction = mLevels[mCurrLevel + 1].getLevelUpAchievementScoreFraction();

        int maxAchievementScore = mAchievementHolder.getExpectableTestSubjectScore(mCurrLevel);
        int alreadySpent = mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_SPENT_SCORE_ON_LEVEL_UP);
        int cost =  (int) (maxAchievementScore * fraction) - alreadySpent;
        if (cost < 0) {
            return 0;
        }
        // now round to some decent value
        final int roundingPrecision = 5;
        return cost + roundingPrecision - (cost % roundingPrecision);
    }

    public synchronized boolean purchaseLevelUp() {
        return isLevelUpAvailable() && mPurse.purchaseLevelUp(getNextLevelUpCost())
                && levelUp();
    }

    public synchronized boolean isLevelUpAvailable() {
        if (mCurrLevel >= mLevels.length -1) {
            return false; // already at max level
        }
        return mCurrLevel == TestSubjectLevel.LEVEL_NONE || !canChooseNewRiddle();
    }

    /**
     * Increases the TestSubject level by one.
     * @return This is almost always true. An exception is if there is no more level available.
     */
    public boolean levelUp() {
        // every condition that will imply this method to return false also needs to imply that
        // isLevelUpAvailable also returns false. This method is only public to make available
        // for cheats.
        if (mCurrLevel >= mLevels.length -1) {
            return false; // already at max level
        }
        mPurse.mShopWallet.editEntry(SHW_KEY_MAX_AVAILABLE_RIDDLE_TYPES, AVAILABLE_RIDDLES_AT_GAME_START).add(1);
        mPurse.mShopWallet.editEntry(Purse.SHW_KEY_TESTSUBJECT_LEVEL).add(1);
        mCurrLevel = mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_TESTSUBJECT_LEVEL);
        TestSubjectLevel currLevel = mLevels[mCurrLevel];
        currLevel.onLeveledUp();
        currLevel.applyLevel(mApplicationContext.getResources());
        return true;
    }

    private void initLevels() {
        mLevels = TestSubjectLevel.makeAll(this);
        WalletEntry levelEntry = mPurse.mShopWallet.assureEntry(Purse.SHW_KEY_TESTSUBJECT_LEVEL, TestSubjectLevel.LEVEL_NONE);
        mCurrLevel = levelEntry.getValue();
        if (mCurrLevel == TestSubjectLevel.LEVEL_NONE) {
            levelUp();
        } else {
            mLevels[mCurrLevel].applyLevel(mApplicationContext.getResources());
        }
    }

    public static TestSubject getInstance() {
        if (!INSTANCE.mInitialized) {
            throw new IllegalStateException("Subject not initialized!");
        }
        return INSTANCE;
    }

    public void postToast(TestSubjectToast toast, long delay) {
        if (mGeneralToastProcessor == null || toast == null) {
            if (mGeneralToastProcessor == null) {
                Log.e("HomeStuff", "Trying to post toast. No handler initialized for testsubject.");
            }
            return;
        }
        mGeneralToastProcessor.append(toast, delay);
        mGeneralToastProcessor.start();
    }

    public void postAchievementAchieved(Achievement achievement) {
        mAchievementToastProcessor.append(achievement, 200L);
        mAchievementToastProcessor.start();
        mAchievementHolder.getMiscData().updateMappedValue(MiscAchievementHolder.KEY_ACHIEVEMENTS_EARNED_COUNT, achievement.getId());
    }

    public boolean addNewType(PracticalRiddleType type) {
        if (!mTypesController.addNewType(type)) {
            return false;
        }
        mPurse.setAvailableRiddleHintsAtStartCount(type);
        mTypesController.saveTypes();
        return true;
    }

    /**
     * Returns a copy of the list of all currently available TestSubjectRiddleTypes.
     * @return A new list containing the riddle types.
     */
    public List<TestSubjectRiddleType> getAvailableTypes() {
        return new ArrayList<>(mTypesController.getAll());
    }

    public boolean canSkip() {
        return mPurse.mShopWallet.assureEntry(Purse.SHW_KEY_SKIPABLE_GAMES, DEFAULT_SKIPABLE_GAMES).getValue()
                > RiddleInitializer.INSTANCE.getRiddleManager().getUnsolvedRiddleCount();
    }

    public void ensureSkipableGames(int amount) {
        int current = mPurse.mShopWallet.getEntryValue(Purse.SHW_KEY_SKIPABLE_GAMES,
                DEFAULT_SKIPABLE_GAMES);
        if (current < amount) {
            mPurse.mShopWallet.editEntry(Purse.SHW_KEY_SKIPABLE_GAMES, DEFAULT_SKIPABLE_GAMES)
                    .set(amount);
        }
    }

    public boolean canChooseNewRiddle() {
        return mPurse.mShopWallet.getEntryValue(SHW_KEY_MAX_AVAILABLE_RIDDLE_TYPES,
                AVAILABLE_RIDDLES_AT_GAME_START) > mTypesController.getCount()
                && mTypesController.getCount() < PracticalRiddleType.ALL_PLAYABLE_TYPES.size();
    }

    public synchronized boolean chooseNewRiddle(PracticalRiddleType type) {
        if (mTypesController.isTypeAvailable(type) || !canChooseNewRiddle()) {
            return false;
        }
        if (addNewType(type)) {
            Log.d("Riddle", "Added and saved new type: " + type);
            return true;
        }
        return false;
    }

    public void addSolvedRiddleScore(int score) {
        mPurse.mScoreWallet.editEntry(Purse.SW_KEY_SOLVED_RIDDLE_SCORE).add(score);
        if (BuildConfig.DEBUG) {
            WalletEntry entry = mPurse.mScoreWallet.assureEntry(Purse.SW_KEY_SOLVED_RIDDLE_SCORE);
            Log.d("HomeStuff", "Adding " + score + " to wallet, new riddle score: " + entry.getValue());
        }
    }

    public void addAchievementScore(int score) {
        mPurse.mScoreWallet.editEntry(Purse.SW_KEY_ACHIEVEMENT_SCORE).add(score);
        Log.d("HomeStuff", "Adding " + score + " to wallet, new achievement score: " + mPurse.mScoreWallet.assureEntry(Purse.SW_KEY_ACHIEVEMENT_SCORE).getValue());

    }

    public TestSubjectAchievementHolder getAchievementHolder() {
        return mAchievementHolder;
    }

    public int getAchievementScore() {
        return mPurse.getAchievementScore();
    }

    public Dependency makeAchievementDependency(PracticalRiddleType type, int number) {
        TypeAchievementHolder typeAchievements = mAchievementHolder.getTypeAchievementHolder(type);
        if (typeAchievements != null) {
            Achievement dep = typeAchievements.getByNumber(number);
            if (dep != null) {
                return new MinValueDependency(dep, dep.getMaxValue());
            }
        }
        return null;
    }

    public Dependency makeClaimedAchievementDependency(PracticalRiddleType type, int number) {
        TypeAchievementHolder typeAchievementHolder = mAchievementHolder.getTypeAchievementHolder(type);
        if (typeAchievementHolder != null) {
            Achievement dep = typeAchievementHolder.getByNumber(number);
            if (dep != null) {
                return new DependencyHolder.ClaimedAchievementDependency(dep);
            }
        }
        return null;
    }

    public int getCurrentRiddleHintNumber(PracticalRiddleType type) {
        return mPurse.getCurrentRiddleHintNumber(type);
    }

    public void increaseRiddleHintsDisplayed(PracticalRiddleType type) {
        int newNumber = mPurse.increaseCurrentRiddleHintNumber(type);
        mAchievementHolder.getMiscData().putValue(ShopArticleRiddleHints.makeKey(type), (long) (newNumber - 1), AchievementProperties.UPDATE_POLICY_ALWAYS);
    }

    public boolean hasAvailableHint(PracticalRiddleType type) {
        return hasAvailableHint(type, mPurse.getCurrentRiddleHintNumber(type));
    }

    public boolean hasAvailableHint(PracticalRiddleType type, int hintNumber) {
        return hintNumber < mPurse.getAvailableRiddleHintsCount(type);
    }

    public boolean hasFeature(String featureKey) {
        return mPurse.mShopWallet.getEntryValue(featureKey) != WalletEntry.FALSE;
    }

    public boolean hasToggleableFeature(String featureKey) {
        return mPurse.hasToggleableFeature(featureKey);
    }

    public Dependency makeProductPurchasedDependency(String articleKey, int productIndex) {
        return new DependencyHolder.ProductPurchasedDependency(mShopArticleHolder.getArticle
                (articleKey), productIndex);
    }

    public Dependency makeFeatureAvailableDependency(String articleKey, int requiredFeatureValue) {
        return new DependencyHolder.FeatureAvailableDependency(mShopArticleHolder.getArticle
                (articleKey), requiredFeatureValue);
    }

    public static void sortTypes(List<PracticalRiddleType> types) {
        Collections.sort(types, TestSubjectRiddleTypeController.TYPE_COMPARATOR);
    }

    public boolean purchaseNextHintForFree(PracticalRiddleType type) {
        ForeignPurse purse = mShopArticleHolder.getPurse();
        return purse.purchaseHint(type, 0);
    }

    public int getRiddleSolvedResIds() {
        return mLevels[mCurrLevel].mRiddleSolvedCandy;
    }

    public int getImageResId() {
        return mLevels[mCurrLevel].getImageResourceId();
    }

    public int getCurrentScore() {
        return mPurse.getCurrentScore();
    }

    public void registerScoreChangedListener(Wallet.OnEntryChangedListener listener) {
        mPurse.mScoreWallet.addChangedListener(listener);
    }

    public void removeScoreChangedListener(Wallet.OnEntryChangedListener listener) {
        mPurse.mScoreWallet.removeChangedListener(listener);
    }

    public int getShopValue(String key) {
        return mPurse.mShopWallet.getEntryValue(key);
    }

    public TestSubjectRiddleTypeController getTypesController() {
        return mTypesController;
    }

    private final Dependable mTestSubjectRiddleTypeCountDependable = new Dependable() {

        @Override
        public CharSequence getName(Resources res) {
            return res.getString(R.string.dependable_testsubject_riddle_type_count);
        }

        @Override
        public int getValue() {
            return mTypesController.getCount();
        }
    };
    public Dependable getTestSubjectRiddleTypeCountDependency() {
            return mTestSubjectRiddleTypeCountDependable;
    }

    private Map<PracticalRiddleType, Dependency> mTypeDependencies = new HashMap<>();
    public Dependency getRiddleTypeDependency(PracticalRiddleType type) {
        Dependency dep = mTypeDependencies.get(type);
        if (dep == null) {
            dep = new DependencyHolder.RiddleTypeDependency(type, this);
            mTypeDependencies.put(type, dep);
        }
        return dep;
    }

    public ShopArticleHolder getShopSortiment() {
        return mShopArticleHolder;
    }

}


text:
/* Automatically generated nanopb header */
/* Generated by nanopb-0.3.7-dev */

#ifndef PB_GRPC_LB_V1_LOAD_BALANCER_PB_H_INCLUDED
#define PB_GRPC_LB_V1_LOAD_BALANCER_PB_H_INCLUDED
#include "third_party/nanopb/pb.h"
/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* Struct definitions */
typedef struct _grpc_lb_v1_ClientStats {
    bool has_total_requests;
    int64_t total_requests;
    bool has_client_rpc_errors;
    int64_t client_rpc_errors;
    bool has_dropped_requests;
    int64_t dropped_requests;
/* @@protoc_insertion_point(struct:grpc_lb_v1_ClientStats) */
} grpc_lb_v1_ClientStats;

typedef struct _grpc_lb_v1_Duration {
    bool has_seconds;
    int64_t seconds;
    bool has_nanos;
    int32_t nanos;
/* @@protoc_insertion_point(struct:grpc_lb_v1_Duration) */
} grpc_lb_v1_Duration;

typedef struct _grpc_lb_v1_InitialLoadBalanceRequest {
    bool has_name;
    char name[128];
/* @@protoc_insertion_point(struct:grpc_lb_v1_InitialLoadBalanceRequest) */
} grpc_lb_v1_InitialLoadBalanceRequest;

typedef PB_BYTES_ARRAY_T(16) grpc_lb_v1_Server_ip_address_t;
typedef struct _grpc_lb_v1_Server {
    bool has_ip_address;
    grpc_lb_v1_Server_ip_address_t ip_address;
    bool has_port;
    int32_t port;
    bool has_load_balance_token;
    char load_balance_token[65];
    bool has_drop_request;
    bool drop_request;
/* @@protoc_insertion_point(struct:grpc_lb_v1_Server) */
} grpc_lb_v1_Server;

typedef struct _grpc_lb_v1_InitialLoadBalanceResponse {
    bool has_load_balancer_delegate;
    char load_balancer_delegate[64];
    bool has_client_stats_report_interval;
    grpc_lb_v1_Duration client_stats_report_interval;
/* @@protoc_insertion_point(struct:grpc_lb_v1_InitialLoadBalanceResponse) */
} grpc_lb_v1_InitialLoadBalanceResponse;

typedef struct _grpc_lb_v1_LoadBalanceRequest {
    bool has_initial_request;
    grpc_lb_v1_InitialLoadBalanceRequest initial_request;
    bool has_client_stats;
    grpc_lb_v1_ClientStats client_stats;
/* @@protoc_insertion_point(struct:grpc_lb_v1_LoadBalanceRequest) */
} grpc_lb_v1_LoadBalanceRequest;

typedef struct _grpc_lb_v1_ServerList {
    pb_callback_t servers;
    bool has_expiration_interval;
    grpc_lb_v1_Duration expiration_interval;
/* @@protoc_insertion_point(struct:grpc_lb_v1_ServerList) */
} grpc_lb_v1_ServerList;

typedef struct _grpc_lb_v1_LoadBalanceResponse {
    bool has_initial_response;
    grpc_lb_v1_InitialLoadBalanceResponse initial_response;
    bool has_server_list;
    grpc_lb_v1_ServerList server_list;
/* @@protoc_insertion_point(struct:grpc_lb_v1_LoadBalanceResponse) */
} grpc_lb_v1_LoadBalanceResponse;

/* Default values for struct fields */

/* Initializer values for message structs */
#define grpc_lb_v1_Duration_init_default         {false, 0, false, 0}
#define grpc_lb_v1_LoadBalanceRequest_init_default {false, grpc_lb_v1_InitialLoadBalanceRequest_init_default, false, grpc_lb_v1_ClientStats_init_default}
#define grpc_lb_v1_InitialLoadBalanceRequest_init_default {false, ""}
#define grpc_lb_v1_ClientStats_init_default      {false, 0, false, 0, false, 0}
#define grpc_lb_v1_LoadBalanceResponse_init_default {false, grpc_lb_v1_InitialLoadBalanceResponse_init_default, false, grpc_lb_v1_ServerList_init_default}
#define grpc_lb_v1_InitialLoadBalanceResponse_init_default {false, "", false, grpc_lb_v1_Duration_init_default}
#define grpc_lb_v1_ServerList_init_default       {{{NULL}, NULL}, false, grpc_lb_v1_Duration_init_default}
#define grpc_lb_v1_Server_init_default           {false, {0, {0}}, false, 0, false, "", false, 0}
#define grpc_lb_v1_Duration_init_zero            {false, 0, false, 0}
#define grpc_lb_v1_LoadBalanceRequest_init_zero  {false, grpc_lb_v1_InitialLoadBalanceRequest_init_zero, false, grpc_lb_v1_ClientStats_init_zero}
#define grpc_lb_v1_InitialLoadBalanceRequest_init_zero {false, ""}
#define grpc_lb_v1_ClientStats_init_zero         {false, 0, false, 0, false, 0}
#define grpc_lb_v1_LoadBalanceResponse_init_zero {false, grpc_lb_v1_InitialLoadBalanceResponse_init_zero, false, grpc_lb_v1_ServerList_init_zero}
#define grpc_lb_v1_InitialLoadBalanceResponse_init_zero {false, "", false, grpc_lb_v1_Duration_init_zero}
#define grpc_lb_v1_ServerList_init_zero          {{{NULL}, NULL}, false, grpc_lb_v1_Duration_init_zero}
#define grpc_lb_v1_Server_init_zero              {false, {0, {0}}, false, 0, false, "", false, 0}

/* Field tags (for use in manual encoding/decoding) */
#define grpc_lb_v1_ClientStats_total_requests_tag 1
#define grpc_lb_v1_ClientStats_client_rpc_errors_tag 2
#define grpc_lb_v1_ClientStats_dropped_requests_tag 3
#define grpc_lb_v1_Duration_seconds_tag          1
#define grpc_lb_v1_Duration_nanos_tag            2
#define grpc_lb_v1_InitialLoadBalanceRequest_name_tag 1
#define grpc_lb_v1_Server_ip_address_tag         1
#define grpc_lb_v1_Server_port_tag               2
#define grpc_lb_v1_Server_load_balance_token_tag 3
#define grpc_lb_v1_Server_drop_request_tag       4
#define grpc_lb_v1_InitialLoadBalanceResponse_load_balancer_delegate_tag 1
#define grpc_lb_v1_InitialLoadBalanceResponse_client_stats_report_interval_tag 2
#define grpc_lb_v1_LoadBalanceRequest_initial_request_tag 1
#define grpc_lb_v1_LoadBalanceRequest_client_stats_tag 2
#define grpc_lb_v1_ServerList_servers_tag        1
#define grpc_lb_v1_ServerList_expiration_interval_tag 3
#define grpc_lb_v1_LoadBalanceResponse_initial_response_tag 1
#define grpc_lb_v1_LoadBalanceResponse_server_list_tag 2

/* Struct field encoding specification for nanopb */
extern const pb_field_t grpc_lb_v1_Duration_fields[3];
extern const pb_field_t grpc_lb_v1_LoadBalanceRequest_fields[3];
extern const pb_field_t grpc_lb_v1_InitialLoadBalanceRequest_fields[2];
extern const pb_field_t grpc_lb_v1_ClientStats_fields[4];
extern const pb_field_t grpc_lb_v1_LoadBalanceResponse_fields[3];
extern const pb_field_t grpc_lb_v1_InitialLoadBalanceResponse_fields[3];
extern const pb_field_t grpc_lb_v1_ServerList_fields[3];
extern const pb_field_t grpc_lb_v1_Server_fields[5];

/* Maximum encoded size of messages (where known) */
#define grpc_lb_v1_Duration_size                 22
#define grpc_lb_v1_LoadBalanceRequest_size       169
#define grpc_lb_v1_InitialLoadBalanceRequest_size 131
#define grpc_lb_v1_ClientStats_size              33
#define grpc_lb_v1_LoadBalanceResponse_size      (98 + grpc_lb_v1_ServerList_size)
#define grpc_lb_v1_InitialLoadBalanceResponse_size 90
/* grpc_lb_v1_ServerList_size depends on runtime parameters */
#define grpc_lb_v1_Server_size                   98

/* Message IDs (where set with "msgid" option) */
#ifdef PB_MSGID

#define LOAD_BALANCER_MESSAGES \

#endif

#ifdef __cplusplus
} /* extern "C" */
#endif
/* @@protoc_insertion_point(eof) */

#endif


text:
#ifndef EGGJOINTPOINTER_H
#define EGGJOINTPOINTER_H

#include "pandatoolbase.h"
#include "eggBackPointer.h"
#include "eggGroup.h"
#include "luse.h"

class EggCharacterDb;

/**
 * This is a base class for EggJointNodePointer and EggMatrixTablePointer.  It
 * stores a back pointer to either a <Joint> entry or an xform <Table> data,
 * and thus presents an interface that returns 1-n matrices, one for each
 * frame.  (<Joint> entries, for model files, appear the same as one-frame
 * animations.)
 */
class EggJointPointer : public EggBackPointer {
public:
  virtual int get_num_frames() const=0;
  virtual LMatrix4d get_frame(int n) const=0;
  virtual void set_frame(int n, const LMatrix4d &mat)=0;
  virtual bool add_frame(const LMatrix4d &mat);

  virtual void do_finish_reparent(EggJointPointer *new_parent)=0;
  virtual void move_vertices_to(EggJointPointer *new_joint);

  virtual bool do_rebuild(EggCharacterDb &db);

  virtual void optimize();
  virtual void expose(EggGroup::DCSType dcs_type);
  virtual void zero_channels(const string &components);
  virtual void quantize_channels(const string &components, double quantum);
  virtual void apply_default_pose(EggJointPointer *source_joint, int frame);

  virtual EggJointPointer *make_new_joint(const string &name)=0;

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    EggBackPointer::init_type();
    register_type(_type_handle, "EggJointPointer",
                  EggBackPointer::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#include "eggJointPointer.I"

#endif


text:
class City < ActiveRecord::Base

  belongs_to :province
  has_many :districts, dependent: :destroy

  def short_name
    @short_name ||= name.gsub(/市|自治州|地区|特别行政区/,'')
  end

  def brothers
    @brothers ||= City.where("province_id = #{province_id}")
  end

end


text:
from google.cloud import ids_v1

def sample_list_endpoints():
    # Create a client
    client = ids_v1.IDSClient()

    # Initialize request argument(s)
    request = ids_v1.ListEndpointsRequest(
        parent="parent_value",
    )

    # Make the request
    page_result = client.list_endpoints(request=request)

    # Handle the response
    for response in page_result:
        print(response)

# [END ids_v1_generated_IDS_ListEndpoints_sync]


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

<title>UIterable (kludje-core 0.8 API)</title>
<meta name="date" content="2016-09-13">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

uk.kludje.fn.lang

Interface UIterable<T>

All Superinterfaces:

java.lang.Iterable<T>

Functional Interface:

This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface
 @Generated(value="uk.kludje.annotation.processor.UncheckedFunctionalInterfaceProcessor")
public interface UIterable<T>
extends java.lang.Iterable<T>

TLDR; IMPLEMENT java.util.Iterator<T> $iterator() throws Throwable USING A LAMBDA; INVOKE java.util.Iterator<T> iterator().

 A functional interface for handling checked exceptions.
 See parent type for interface intent.

 java.util.Iterator<T> iterator() invokes java.util.Iterator<T> $iterator()
 and throws anything thrown by java.util.Iterator<T> $iterator().

 General example using java.lang.Runnable that reduces 11 lines to a single line.
 Call someMethodThatThrowsException in throwsNothing:

 public void someMethodThatThrowsException() throws IOException {
   // I/O functionality
 }

 public void throwsNothing(Runnable r) {
   r.run();
 }

 Before:

 public void yourMethod() throws IOException {
   try {
     throwsNothing(() -> {
       try {
         someMethodThatThrowsException();
       } catch (IOException e) {
         throw new SomeWrapperException(e);
       }
     });
   } catch(SomeWrapperException w) {
     throw (IOException) w.getCause();
   }
 }

 After:

 public void yourMethod() throws IOException {
   throwsNothing((URunnable) this::someMethodThatThrowsException);
 }

 Method public static <T> UIterable<T> asUIterable(UIterable<T> t)
 provides a convenience method for manufacturing types as an alternative to casting.

Method Summary

All Methods Static Methods Instance Methods Abstract Methods Default Methods

Modifier and Type
Method and Description

java.util.Iterator<T>
$iterator()

static <T> UIterable<T>
asUIterable(UIterable<T> t)

default java.util.Iterator<T>
iterator()

Methods inherited from interface java.lang.Iterable

forEach, spliterator

Method Detail

iterator

default java.util.Iterator<T> iterator()

Specified by:

iterator in interface java.lang.Iterable<T>

$iterator

java.util.Iterator<T> $iterator()
                         throws java.lang.Throwable

Throws:

java.lang.Throwable

asUIterable

static <T> UIterable<T> asUIterable(UIterable<T> t)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace PragmaRX\Sdk\Core\Exceptions;

use Exception;

class TokenMismatch extends Exception {

}


text:
package org.sleuthkit.autopsy.datamodel;

import java.awt.Component;
import java.util.logging.Level;

import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.JOptionPane;
import org.openide.LifecycleManager;
import org.openide.modules.ModuleInstall;
import org.sleuthkit.datamodel.SleuthkitJNI;

/**
 * Installer checks that the JNI library is working when the module is loaded.
 */
public class Installer extends ModuleInstall {

    private static Installer instance;

    public synchronized static Installer getDefault() {
        if (instance == null) {
            instance = new Installer();
        }
        return instance;
    }

    private Installer() {
        super();
    }

    @Override
    public void validate() throws IllegalStateException {
        /*
         * The NetBeans API specifies that a module should throw an IllegalStateException
         * if it can't be initalized, but NetBeans doesn't handle that behaviour
         * well (it just disables the module, and all dependant modules, on the
         * current and all subsequent application launches). Hence, we deal with
         * it manually.
         *
         */

        // Check that the the Sleuth Kit JNI is working by getting the Sleuth Kit version number
        Logger logger = Logger.getLogger(Installer.class.getName());
        try {
            String skVersion = SleuthkitJNI.getVersion();

            if (skVersion == null) {
                throw new Exception(NbBundle.getMessage(this.getClass(), "Installer.exception.tskVerStringNull.msg"));
            } else if (skVersion.length() == 0) {
                throw new Exception(NbBundle.getMessage(this.getClass(), "Installer.exception.taskVerStringBang.msg"));
            } else {
                logger.log(Level.CONFIG, "Sleuth Kit Version: {0}", skVersion); //NON-NLS
            }

        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error calling Sleuth Kit library (test call failed)", e); //NON-NLS

            // Normal error box log handler won't be loaded yet, so show error here.
            final Component parentComponent = null; // Use default window frame.
            final String message = NbBundle.getMessage(this.getClass(), "Installer.tskLibErr.msg", e.toString());
            final String title = NbBundle.getMessage(this.getClass(), "Installer.tskLibErr.err");
            final int messageType = JOptionPane.ERROR_MESSAGE;

            JOptionPane.showMessageDialog(
                    parentComponent,
                    message,
                    title,
                    messageType);

            // exit after user exits the error dialog box
            LifecycleManager.getDefault().exit();
        }

    }
}


text:
package com.github.swissquote.carnotzet.core.docker.registry;

import java.util.Arrays;
import java.util.StringJoiner;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;

public class ImageRef {

	private static final String DEFAULT_REGISTRY = "docker.io";
	private static final String DEFAULT_REGISTRY_URL = "https://index.docker.io/v1/";
	private static final String DEFAULT_TAG = "latest";

	private final String registryUrl;
	private final String registry;
	private final String image;
	private final String tag;

	public ImageRef(final String image) {
		final int lastAt = image.lastIndexOf('@');
		final int lastColon = image.lastIndexOf(':');
		if (lastAt >= 0) {
			this.image = image;
			this.tag = null;
		} else if (lastColon < 0) {
			this.image = image;
			this.tag = null;
		} else {
			final String tag = image.substring(lastColon + 1);
			if (tag.indexOf('/') < 0) {
				this.image = image.substring(0, lastColon);
				this.tag = tag;
			} else {
				this.image = image;
				this.tag = null;
			}
		}
		final String[] parts = image.split("/", 2);
		if (parts.length > 1 && isRegistry(parts[0])) {
			this.registry = parts[0];
			this.registryUrl = parseRegistryUrl(parts[0]);
		} else {
			this.registry = DEFAULT_REGISTRY;
			this.registryUrl = DEFAULT_REGISTRY_URL;
		}
	}

	private static boolean isRegistry(String part) {
		return part.contains(".");
	}

	public String getImage() {
		return image;
	}

	// The image tag, or null if not set.
	public String getTag() {
		if (tag == null) {
			return DEFAULT_TAG;
		}
		return tag;
	}

	// Hostname/ip address and port of the registry.
	public String getRegistryName() {
		return registry;
	}

	public String getRegistryUrl() {
		return registryUrl;
	}

	@Override
	public String toString() {
		return MoreObjects.toStringHelper(this)
				.add("registry", registry)
				.add("image", image)
				.add("tag", tag)
				.toString();
	}

	// registry server address given first part of image.
	@VisibleForTesting
	static String parseRegistryUrl(final String url) {
		if ("docker.io".equals(url) || "index.docker.io".equals(url)) {
			return DEFAULT_REGISTRY_URL;
		} else if (url.matches("(^|(\\w+)\\.)gcr\\.io$") || "gcr.kubernetes.io".equals(url)) {
			// GCR uses https
			return "https://" + url;
		} else if ("quay.io".equals(url)) {
			// Quay doesn't use any protocol in credentials file
			return "quay.io";
		} else if (!url.contains("http://") && !url.contains("https://")) {
			// Assume https
			return "https://" + url;
		} else {
			return url;
		}
	}

	public String getImageName() {
		String[] splitted = image.split("/");

		StringJoiner joiner = new StringJoiner("/");
		Arrays.stream(splitted)
				.filter(token -> token.indexOf(".") < 0)
				.forEach(token -> joiner.add(token));

		return joiner.toString();
	}
}


text:
class Follow < ActiveRecord::Base
  belongs_to :followed, class_name: 'User'
  belongs_to :follower, class_name: 'User'

  validates :follower_id, uniqueness: {scope: :followed_id}

  validate :cant_follow_self
  def cant_follow_self
    if follower_id == followed_id
      errors.add(:base, 'You cannot follow yourself')
    end
  end

  after_create do
    User.increment_counter 'following_count', self.follower_id
    User.increment_counter 'followers_count_hack', self.followed_id
  end

  before_destroy do
    User.decrement_counter 'following_count', self.follower_id
    User.decrement_counter 'followers_count_hack', self.followed_id
  end
end


text:
package org.apache.wink.test.filter.specificurl;

import java.io.IOException;

import junit.framework.TestCase;

import org.apache.commons.httpclient.HttpException;
import org.apache.wink.client.ClientResponse;
import org.apache.wink.client.RestClient;
import org.apache.wink.test.integration.ServerEnvironmentInfo;

public class WinkFilterSpecificURLPatternTest extends TestCase {

    public String getBaseURI() {
        return ServerEnvironmentInfo.getBaseURI();
    }

    protected RestClient client;

    public void setUp() {
        client = new RestClient();
    }

    public void testGetBook() throws HttpException, IOException {
        ClientResponse response = client.resource(getBaseURI() + "/book/book1").get();
        assertEquals(200, response.getStatusCode());
        assertTrue(response.getEntity(String.class), response.getEntity(String.class)
            .contains("book resource hit"));
    }
}


text:
var raspberrypi = require('../lib/raspberrypi.js');

raspberrypi.displayImage(__dirname + "/data/raspberry.jpg", 10, function(retval) {
  console.log(retval);
});


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

define(['dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/_base/array',
  'dojo/_base/html',
  'dojo/topic',
  'dojo/on',
  'dojo/aspect',
  'dojo/keys',
  'dojo/Deferred',
  'esri/dijit/InfoWindow',
  "esri/dijit/PopupMobile",
  'esri/InfoTemplate',
  'esri/request',
  'esri/geometry/Extent',
  'esri/geometry/Point',
  'require',
  './utils',
  './dijit/LoadingShelter',
  'jimu/LayerInfos/LayerInfos',
  './MapUrlParamsHandler',
  './AppStateManager'
], function(declare, lang, array, html, topic, on, aspect, keys, Deferred, InfoWindow,
  PopupMobile, InfoTemplate, esriRequest, Extent, Point, require,
  jimuUtils, LoadingShelter, LayerInfos, MapUrlParamsHandler,
  AppStateManager) {
  var instance = null,
    clazz = declare(null, {
      appConfig: null,
      mapDivId: '',
      map: null,
      previousInfoWindow: null,
      mobileInfoWindow: null,
      isMobileInfoWindow: false,

      layerInfosObj: null,

      constructor: function( /*Object*/ options, mapDivId) {
        this.appConfig = options.appConfig;
        this.urlParams = options.urlParams;
        this.mapDivId = mapDivId;
        this.id = mapDivId;
        this.appStateManager = AppStateManager.getInstance(this.urlParams);
        topic.subscribe("appConfigChanged", lang.hitch(this, this.onAppConfigChanged));
        topic.subscribe("changeMapPosition", lang.hitch(this, this.onChangeMapPosition));
        topic.subscribe("syncExtent", lang.hitch(this, this.onSyncExtent));

        on(window, 'resize', lang.hitch(this, this.onWindowResize));
        on(window, 'beforeunload', lang.hitch(this, this.onBeforeUnload));
      },

      showMap: function() {
        // console.timeEnd('before map');
        this._showMap(this.appConfig);
      },

      _showMap: function(appConfig) {
        // console.timeEnd('before map');
        console.time('Load Map');
        this.loading = new LoadingShelter();
        this.loading.placeAt(this.mapDivId);
        this.loading.startup();
        //for now, we can't create both 2d and 3d map
        if (appConfig.map['3D']) {
          if (appConfig.map.itemId) {
            this._show3DWebScene(appConfig);
          } else {
            this._show3DLayersMap(appConfig);
          }
        } else {
          if (appConfig.map.itemId) {
            this._show2DWebMap(appConfig);
          } else {
            console.log('No webmap found. Please set map.itemId in config.json.');
          }
        }
      },

      onBeforeUnload: function() {
        this.appStateManager.saveWabAppState(this.map, this.layerInfosObj);
      },

      onWindowResize: function() {
        if (this.map && this.map.resize) {
          this.map.resize();
          this.resetInfoWindow(false);
        }
      },

      getMapInfoWindow: function(){
        return {
          mobile: this._mapMobileInfoWindow,
          bigScreen: this._mapInfoWindow
        };
      },

      resetInfoWindow: function(isNewMap) {
        if(isNewMap){
          this._mapInfoWindow = this.map.infoWindow;
          if(this._mapMobileInfoWindow){
            this._mapMobileInfoWindow.destroy();
          }
          this._mapMobileInfoWindow =
          new PopupMobile(null, html.create("div", null, null, this.map.root));
          this.isMobileInfoWindow = false;
        }
        if (window.appInfo.isRunInMobile && !this.isMobileInfoWindow) {
          this.map.infoWindow.hide();
          this.map.setInfoWindow(this._mapMobileInfoWindow);
          this.isMobileInfoWindow = true;
        } else if (!window.appInfo.isRunInMobile && this.isMobileInfoWindow) {
          this.map.infoWindow.hide();
          this.map.setInfoWindow(this._mapInfoWindow);
          this.isMobileInfoWindow = false;
        }
      },

      onChangeMapPosition: function(position) {
        var pos = lang.clone(this.mapPosition);
        lang.mixin(pos, position);
        this.setMapPosition(pos);
      },

      setMapPosition: function(position){
        this.mapPosition = position;

        var posStyle = jimuUtils.getPositionStyle(position);
        html.setStyle(this.mapDivId, posStyle);
        if (this.map && this.map.resize) {
          this.map.resize();
        }
      },

      getMapPosition: function(){
        return this.mapPosition;
      },

      onSyncExtent: function(map){
        if(this.map){
          var extJson = map.extent;
          var ext = new Extent(extJson);
          this.map.setExtent(ext);
        }
      },

      _visitConfigMapLayers: function(appConfig, cb) {
        array.forEach(appConfig.map.basemaps, function(layerConfig, i) {
          layerConfig.isOperationalLayer = false;
          cb(layerConfig, i);
        }, this);

        array.forEach(appConfig.map.operationallayers, function(layerConfig, i) {
          layerConfig.isOperationalLayer = true;
          cb(layerConfig, i);
        }, this);
      },

      _show3DLayersMap: function(appConfig) {
        require(['esri3d/Map'], lang.hitch(this, function(Map) {
          var initCamera = appConfig.map.mapOptions.camera,
            map;
          map = new Map(this.mapDivId, {
            camera: initCamera
          });
          this._visitConfigMapLayers(appConfig, lang.hitch(this, function(layerConfig) {
            this.createLayer(map, '3D', layerConfig);
          }));
          map.usePlugin = Map.usePlugin;
          this._publishMapEvent(map);
        }));
      },

      _show3DWebScene: function(appConfig) {
        this._getWebsceneData(appConfig.map.itemId).then(lang.hitch(this, function(data) {
          require(['esri3d/Map'], lang.hitch(this, function(Map) {
            var map = new Map(this.mapDivId, appConfig.map.mapOptions);

            array.forEach(data.itemData.operationalLayers, function(layerConfig) {
              this.createLayer(map, '3D', layerConfig);
            }, this);

            array.forEach(data.itemData.baseMap.baseMapLayers, function(layerConfig) {
              layerConfig.type = "tile";
              this.createLayer(map, '3D', layerConfig);
            }, this);

            array.forEach(data.itemData.baseMap.elevationLayers, function(layerConfig) {
              layerConfig.type = "elevation";
              this.createLayer(map, '3D', layerConfig);
            }, this);

            map.toc = data.itemData.toc;
            map.bookmarks = data.itemData.bookmarks;
            map.tours = data.itemData.tours;
          }));
        }));
      },

      _publishMapEvent: function(map) {
        //add this property for debug purpose
        window._viewerMap = map;
        if (this.loading) {
          this.loading.destroy();
        }

        MapUrlParamsHandler.postProcessUrlParams(this.urlParams, map);

        console.timeEnd('Load Map');
        if (this.map) {
          this.map = map;
          this.resetInfoWindow(true);
          console.log('map changed.');
          topic.publish('mapChanged', this.map);
        } else {
          this.map = map;
          this.resetInfoWindow(true);
          topic.publish('mapLoaded', this.map);
        }
      },

      _getWebsceneData: function(itemId) {
        return esriRequest({
          url: 'http://184.169.133.166/sharing/rest/content/items/' + itemId + '/data',
          handleAs: "json"
        });
      },

      _show2DWebMap: function(appConfig) {
        //should use appConfig instead of this.appConfig, because appConfig is new.
        // if (appConfig.portalUrl) {
        //   var url = portalUrlUtils.getStandardPortalUrl(appConfig.portalUrl);
        //   agolUtils.arcgisUrl = url + "/sharing/content/items/";
        // }
        if(!appConfig.map.mapOptions){
          appConfig.map.mapOptions = {};
        }
        var mapOptions = this._processMapOptions(appConfig.map.mapOptions) || {};
        mapOptions.isZoomSlider = false;

        var webMapPortalUrl = appConfig.map.portalUrl;
        var webMapItemId = appConfig.map.itemId;
        var webMapOptions = {
          mapOptions: mapOptions,
          bingMapsKey: appConfig.bingMapsKey,
          usePopupManager: true
        };

        var mapDeferred = jimuUtils.createWebMap(webMapPortalUrl, webMapItemId,
          this.mapDivId, webMapOptions);

        mapDeferred.then(lang.hitch(this, function(response) {
          var map = response.map;

          //hide the default zoom slider
          map.hideZoomSlider();

          // set default size of infoWindow.
          map.infoWindow.resize(270, 316);
          //var extent;
          map.itemId = appConfig.map.itemId;
          map.itemInfo = response.itemInfo;
          map.webMapResponse = response;
          // enable snapping
          var options = {
            snapKey: keys.copyKey
          };
          map.enableSnapping(options);

          html.setStyle(map.root, 'zIndex', 0);

          map._initialExtent = map.extent;

          //URL parameters that affect map extent
          var urlKeys = ['extent', 'center', 'marker', 'find', 'query', 'scale', 'level'];
          var useAppState = true;
          array.forEach(urlKeys, function(k){
            if(k in this.urlParams){
              useAppState = false;
            }
          }, this);

          if(useAppState){
            this._applyAppState(map).then(lang.hitch(this, function() {
              this._publishMapEvent(map);
            }));
          }else{
            this._publishMapEvent(map);
          }
        }), lang.hitch(this, function() {
          if (this.loading) {
            this.loading.destroy();
          }
          topic.publish('mapCreatedFailed');
        }));
      },

      _applyAppState: function(map) {
        var def = new Deferred();

        this.appStateManager.getWabAppState()
        .then(lang.hitch(this, function(stateData) {
          var layerOptions = stateData.layers;
          LayerInfos.getInstance(map, map.itemInfo, {
            layerOptions: layerOptions || null
          }).then(lang.hitch(this, function(layerInfosObj) {
            this.layerInfosObj = layerInfosObj;
            if (stateData.extent) {
              return map.setExtent(stateData.extent);
            }
          })).always(function() {
            def.resolve();
          });
        }));

        return def;
      },

      _processMapOptions: function(mapOptions) {
        if (!mapOptions) {
          return;
        }

        if(!mapOptions.lods){
          delete mapOptions.lods;
        }
        if(mapOptions.lods && mapOptions.lods.length === 0){
          delete mapOptions.lods;
        }

        var ret = lang.clone(mapOptions);
        if (ret.extent) {
          ret.extent = new Extent(ret.extent);
        }
        if (ret.center && !lang.isArrayLike(ret.center)) {
          ret.center = new Point(ret.center);
        }
        if (ret.infoWindow) {
          ret.infoWindow = new InfoWindow(ret.infoWindow, html.create('div', {}, this.mapDivId));
        }

        return ret;
      },

      createLayer: function(map, maptype, layerConfig) {
        var layMap = {
          '2D_tiled': 'esri/layers/ArcGISTiledMapServiceLayer',
          '2D_dynamic': 'esri/layers/ArcGISDynamicMapServiceLayer',
          '2D_image': 'esri/layers/ArcGISImageServiceLayer',
          '2D_feature': 'esri/layers/FeatureLayer',
          '2D_rss': 'esri/layers/GeoRSSLayer',
          '2D_kml': 'esri/layers/KMLLayer',
          '2D_webTiled': 'esri/layers/WebTiledLayer',
          '2D_wms': 'esri/layers/WMSLayer',
          '2D_wmts': 'esri/layers/WMTSLayer',
          '3D_tiled': 'esri3d/layers/ArcGISTiledMapServiceLayer',
          '3D_dynamic': 'esri3d/layers/ArcGISDynamicMapServiceLayer',
          '3D_image': 'esri3d/layers/ArcGISImageServiceLayer',
          '3D_feature': 'esri3d/layers/FeatureLayer',
          '3D_elevation': 'esri3d/layers/ArcGISElevationServiceLayer',
          '3D_3dmodle': 'esri3d/layers/SceneLayer'
        };

        require([layMap[maptype + '_' + layerConfig.type]], lang.hitch(this, function(layerClass) {
          var layer, infoTemplate, options = {},
            keyProperties = ['label', 'url', 'type', 'icon', 'infoTemplate', 'isOperationalLayer'];
          for (var p in layerConfig) {
            if (keyProperties.indexOf(p) < 0) {
              options[p] = layerConfig[p];
            }
          }
          if (layerConfig.infoTemplate) {
            infoTemplate = new InfoTemplate(layerConfig.infoTemplate.title,
              layerConfig.infoTemplate.content);
            options.infoTemplate = infoTemplate;

            layer = new layerClass(layerConfig.url, options);

            if (layerConfig.infoTemplate.width && layerConfig.infoTemplate.height) {
              aspect.after(layer, 'onClick', lang.hitch(this, function() {
                map.infoWindow.resize(layerConfig.infoTemplate.width,
                  layerConfig.infoTemplate.height);
              }), true);
            }
          } else {
            layer = new layerClass(layerConfig.url, options);
          }

          layer.isOperationalLayer = layerConfig.isOperationalLayer;
          layer.label = layerConfig.label;
          layer.icon = layerConfig.icon;
          map.addLayer(layer);
        }));
      },

      onAppConfigChanged: function(appConfig, reason, changedJson) {
        // jshint unused:false
        this.appConfig = appConfig;
        if(reason === 'mapChange'){
          this._recreateMap(appConfig);
        }
        else if(reason === 'mapOptionsChange'){
          if(changedJson.lods){
            this._recreateMap(appConfig);
          }
        }
      },

      _recreateMap: function(appConfig){
        if(this.map){
          topic.publish('beforeMapDestory', this.map);
          this.map.destroy();
        }
        this._showMap(appConfig);
      },

      disableWebMapPopup: function() {
        this.map.setInfoWindowOnClick(false);
      },

      enableWebMapPopup: function() {
        this.map.setInfoWindowOnClick(true);
      }

    });

  clazz.getInstance = function(options, mapDivId) {
    if (instance === null) {
      instance = new clazz(options, mapDivId);
    }
    return instance;
  };

  return clazz;
});


text:
package org.headlessintrace.client.filter;

import org.headlessintrace.client.model.ITraceEvent;

/**
 * An "Include" style filter, as opposed to an "exclude" style filter.
 * @author erikostermueller
 *
 */
public class IncludeThisEventFilterExt implements ITraceFilterExt {
	ITraceEvent m_criteria = null;
	public IncludeThisEventFilterExt() {

	}
	public IncludeThisEventFilterExt(ITraceEvent val) {
		setFilterCriteria(val);
	}
	//@Override
	public void setFilterCriteria(ITraceEvent criteria) {
		m_criteria = criteria;
	}
	@Override
	public boolean matches(ITraceEvent traceData) {
		return matches(m_criteria,traceData);
	}
	protected boolean matches(ITraceEvent a, ITraceEvent b) {
		if (a==null || b==null)
			return false;

		if (a.getEventType()==b.getEventType()
				&& a.getClassName().equals(b.getClassName())
				&& a.getMethodName().equals(b.getMethodName())
				) {
					return true;
				}
			return false;

	}
}


text:
var localStrategy = require('passport-local').Strategy;

var User = require('../app/models/user.js');

module.exports = function (passport) {
    // =========================================================================
   // passport session setup ==================================================
   // =========================================================================
   // required for persistent login sessions
   // passport needs ability to serialize and unserialize users out of session

   passport.serializeUser(function (user, done) {
       done(null, user.id);
   });

   passport.deserializeUser(function (id, done) {
       User.findById(id, function (err, user) {
           done(err, user);
       })
   });

   passport.use('local-signup', new localStrategy({
       // by default, local strategy uses username and password, we will override with email
       usernameField: 'email',
       passwordField: 'password',
       passReqToCallback: true // allows us to pass back the entire request to the callback
   }, function (req, email, password, done) {
       //async
       //User.findOne wont fire unless data is sent back
       process.nextTick(function () {
           // find a user whose email is the same as the forms email
           // we are checking to see if the user trying to login already exists
           User.findOne({'local.email': email}, function (err, user) {
               if (err) {
                   return done(err);
               }

               //check to see if there is already a user with that email
               if (user) {
                   return done(null, false, req.flash('signupMessage', 'That email has already been taken.'));
               } else {
                   var newUser = new User();
                   newUser.email = email;
                   newUser.password = newUser.generateHash(password);
                   newUser.userType = 'user';
                   newUser.name = req.body.name;
                   newUser.team = null;
                   newUser.systemMessages = [];
                   newUser.personalMessages = [];

                   newUser.save(function (err) {
                       if (err) {
                           throw err;
                       }

                       return done(null, newUser);
                   });
               }
           });
       })
   }));

   passport.use('local-login', new localStrategy({
       usernameField: 'email',
       passwordField: 'password',
       passReqToCallback: true
   },
    function (req, email, password, done) {
        User.findOne({'email': email}, function (err, user) {
            if (err) {
                return done(err);
            }

            if (!user) {
                return done(null, false, req.flash('loginMessage', 'No user found.'));
            }

            if (!user.validatePassword(password)) {
                return done(null, false, req.flash('loginMessage', 'Wrong password.'));
            }
            return done(null, user);
        });
    }))
}


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

AFFILIATION

DESCRIPTION

CONFIGURATION

NOTES

SEE ALSO

AUTHOR

COPYRIGHT

NAME

Perl::Critic::Policy::Subroutines::ProhibitExplicitReturnUndef - Return failure with bare return instead of return undef.

AFFILIATION

This Policy is part of the core Perl::Critic distribution.

DESCRIPTION

Returning undef upon failure from a subroutine is pretty common. But if the subroutine is called in list context, an explicit return undef;
 statement will return a one-element list containing (undef). Now if that list is subsequently put in a boolean context to test for failure, then it evaluates to true. But you probably wanted it to be false.

  sub read_file {
      my $file = shift;
      -f $file || return undef;  #file doesn't exist!

      #Continue reading file...
  }

  #and later...

  if ( my @data = read_file($filename) ){

      # if $filename doesn't exist,
      # @data will be (undef),
      # but I'll still be in here!

      process(@data);
  }
  else{

      # This is my error handling code.
      # I probably want to be in here
      # if $filname doesn't exist.

      die "$filename not found";
  }

The solution is to just use a bare return statement whenever you want to return failure. In list context, Perl will then give you an empty list (which is false), and undef in scalar context (which is also false).

  sub read_file {
      my $file = shift;
      -f $file || return;  #DWIM!

      #Continue reading file...
  }

CONFIGURATION

This Policy is not configurable except for the standard options.

NOTES

You can fool this policy pretty easily by hiding undef in a boolean expression. But don't bother trying. In fact, using return values to indicate failure is pretty poor technique anyway. Consider using die or croak with eval, or the Error module for a much more robust exception-handling model. Conway has a real nice discussion on error handling in chapter 13 of PBP.

SEE ALSO

There's a discussion of the appropriateness of this policy at http://perlmonks.org/index.pl?node_id=741847.

AUTHOR

Jeffrey Ryan Thalhammer <jeff@imaginative-software.com>

COPYRIGHT

Copyright (c) 2005-2011 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.


text:
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/aer.h>
#include <linux/completion.h>
#include <linux/workqueue.h>
#include <linux/delay.h>
#include "adf_accel_devices.h"
#include "adf_common_drv.h"

static struct workqueue_struct *device_reset_wq;

static pci_ers_result_t adf_error_detected(struct pci_dev *pdev,
					   pci_channel_state_t state)
{
	struct adf_accel_dev *accel_dev = adf_devmgr_pci_to_accel_dev(pdev);

	dev_info(&pdev->dev, "Acceleration driver hardware error detected.\n");
	if (!accel_dev) {
		dev_err(&pdev->dev, "Can't find acceleration device\n");
		return PCI_ERS_RESULT_DISCONNECT;
	}

	if (state == pci_channel_io_perm_failure) {
		dev_err(&pdev->dev, "Can't recover from device error\n");
		return PCI_ERS_RESULT_DISCONNECT;
	}

	return PCI_ERS_RESULT_NEED_RESET;
}

/* reset dev data */
struct adf_reset_dev_data {
	int mode;
	struct adf_accel_dev *accel_dev;
	struct completion compl;
	struct work_struct reset_work;
};

void adf_dev_restore(struct adf_accel_dev *accel_dev)
{
	struct pci_dev *pdev = accel_to_pci_dev(accel_dev);
	struct pci_dev *parent = pdev->bus->self;
	uint16_t bridge_ctl = 0;

	if (accel_dev->is_vf)
		return;

	dev_info(&GET_DEV(accel_dev), "Resetting device qat_dev%d\n",
		 accel_dev->accel_id);

	if (!parent)
		parent = pdev;

	if (!pci_wait_for_pending_transaction(pdev))
		dev_info(&GET_DEV(accel_dev),
			 "Transaction still in progress. Proceeding\n");

	pci_read_config_word(parent, PCI_BRIDGE_CONTROL, &bridge_ctl);
	bridge_ctl |= PCI_BRIDGE_CTL_BUS_RESET;
	pci_write_config_word(parent, PCI_BRIDGE_CONTROL, bridge_ctl);
	msleep(100);
	bridge_ctl &= ~PCI_BRIDGE_CTL_BUS_RESET;
	pci_write_config_word(parent, PCI_BRIDGE_CONTROL, bridge_ctl);
	msleep(100);
	pci_restore_state(pdev);
	pci_save_state(pdev);
}

static void adf_device_reset_worker(struct work_struct *work)
{
	struct adf_reset_dev_data *reset_data =
		  container_of(work, struct adf_reset_dev_data, reset_work);
	struct adf_accel_dev *accel_dev = reset_data->accel_dev;

	adf_dev_restarting_notify(accel_dev);
	adf_dev_stop(accel_dev);
	adf_dev_shutdown(accel_dev);
	if (adf_dev_init(accel_dev) || adf_dev_start(accel_dev)) {
		/* The device hanged and we can't restart it so stop here */
		dev_err(&GET_DEV(accel_dev), "Restart device failed\n");
		kfree(reset_data);
		WARN(1, "QAT: device restart failed. Device is unusable\n");
		return;
	}
	adf_dev_restarted_notify(accel_dev);
	clear_bit(ADF_STATUS_RESTARTING, &accel_dev->status);

	/* The dev is back alive. Notify the caller if in sync mode */
	if (reset_data->mode == ADF_DEV_RESET_SYNC)
		complete(&reset_data->compl);
	else
		kfree(reset_data);
}

static int adf_dev_aer_schedule_reset(struct adf_accel_dev *accel_dev,
				      enum adf_dev_reset_mode mode)
{
	struct adf_reset_dev_data *reset_data;

	if (!adf_dev_started(accel_dev) ||
	    test_bit(ADF_STATUS_RESTARTING, &accel_dev->status))
		return 0;

	set_bit(ADF_STATUS_RESTARTING, &accel_dev->status);
	reset_data = kzalloc(sizeof(*reset_data), GFP_ATOMIC);
	if (!reset_data)
		return -ENOMEM;
	reset_data->accel_dev = accel_dev;
	init_completion(&reset_data->compl);
	reset_data->mode = mode;
	INIT_WORK(&reset_data->reset_work, adf_device_reset_worker);
	queue_work(device_reset_wq, &reset_data->reset_work);

	/* If in sync mode wait for the result */
	if (mode == ADF_DEV_RESET_SYNC) {
		int ret = 0;
		/* Maximum device reset time is 10 seconds */
		unsigned long wait_jiffies = msecs_to_jiffies(10000);
		unsigned long timeout = wait_for_completion_timeout(
				   &reset_data->compl, wait_jiffies);
		if (!timeout) {
			dev_err(&GET_DEV(accel_dev),
				"Reset device timeout expired\n");
			ret = -EFAULT;
		}
		kfree(reset_data);
		return ret;
	}
	return 0;
}

static pci_ers_result_t adf_slot_reset(struct pci_dev *pdev)
{
	struct adf_accel_dev *accel_dev = adf_devmgr_pci_to_accel_dev(pdev);

	if (!accel_dev) {
		pr_err("QAT: Can't find acceleration device\n");
		return PCI_ERS_RESULT_DISCONNECT;
	}
	pci_cleanup_aer_uncorrect_error_status(pdev);
	if (adf_dev_aer_schedule_reset(accel_dev, ADF_DEV_RESET_SYNC))
		return PCI_ERS_RESULT_DISCONNECT;

	return PCI_ERS_RESULT_RECOVERED;
}

static void adf_resume(struct pci_dev *pdev)
{
	dev_info(&pdev->dev, "Acceleration driver reset completed\n");
	dev_info(&pdev->dev, "Device is up and runnig\n");
}

static const struct pci_error_handlers adf_err_handler = {
	.error_detected = adf_error_detected,
	.slot_reset = adf_slot_reset,
	.resume = adf_resume,
};

/**
 * adf_enable_aer() - Enable Advance Error Reporting for acceleration device
 * @accel_dev:  Pointer to acceleration device.
 * @adf:        PCI device driver owning the given acceleration device.
 *
 * Function enables PCI Advance Error Reporting for the
 * QAT acceleration device accel_dev.
 * To be used by QAT device specific drivers.
 *
 * Return: 0 on success, error code otherwise.
 */
int adf_enable_aer(struct adf_accel_dev *accel_dev, struct pci_driver *adf)
{
	struct pci_dev *pdev = accel_to_pci_dev(accel_dev);

	adf->err_handler = &adf_err_handler;
	pci_enable_pcie_error_reporting(pdev);
	return 0;
}
EXPORT_SYMBOL_GPL(adf_enable_aer);

/**
 * adf_disable_aer() - Enable Advance Error Reporting for acceleration device
 * @accel_dev:  Pointer to acceleration device.
 *
 * Function disables PCI Advance Error Reporting for the
 * QAT acceleration device accel_dev.
 * To be used by QAT device specific drivers.
 *
 * Return: void
 */
void adf_disable_aer(struct adf_accel_dev *accel_dev)
{
	struct pci_dev *pdev = accel_to_pci_dev(accel_dev);

	pci_disable_pcie_error_reporting(pdev);
}
EXPORT_SYMBOL_GPL(adf_disable_aer);

int adf_init_aer(void)
{
	device_reset_wq = create_workqueue("qat_device_reset_wq");
	return !device_reset_wq ? -EFAULT : 0;
}

void adf_exit_aer(void)
{
	if (device_reset_wq)
		destroy_workqueue(device_reset_wq);
	device_reset_wq = NULL;
}