text:
package morethanhidden.MTHCore.util;

import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.block.model.ItemOverrideList;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.client.model.IPerspectiveAwareModel;
import net.minecraftforge.common.model.TRSRTransformation;
import org.apache.commons.lang3.tuple.Pair;

import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import java.util.List;

//Takes a blockmodel and applies the standard-block-perspective for third_person to it
public class BlockItemModelWrapper implements IPerspectiveAwareModel, IBakedModel {

    // copied from the forge variants V1 default-block transform
    public static final Matrix4f THIRD_PERSON_BLOCK_TRANSFORM = new TRSRTransformation(
            new Vector3f(0, 1.5f / 16, -2.75f / 16), // translation
            TRSRTransformation.quatFromXYZDegrees(new Vector3f(10, -45, 170)), // rotation
            new Vector3f(0.375f, 0.375f, 0.375f), // scale
            null).getMatrix();

    private final IBakedModel parent;

    public BlockItemModelWrapper(IBakedModel parent) {
        this.parent = parent;
    }

    @Override
    public Pair<? extends IBakedModel, Matrix4f> handlePerspective(ItemCameraTransforms.TransformType cameraTransformType) {
        Matrix4f matrix = null;
        // fix transformation in hand
        if (cameraTransformType == ItemCameraTransforms.TransformType.THIRD_PERSON_RIGHT_HAND) {
            matrix = THIRD_PERSON_BLOCK_TRANSFORM;
        }

        return Pair.of(this, matrix);
    }

    @Override
    public List<BakedQuad> getQuads(IBlockState state, EnumFacing side, long rand) {
        return parent.getQuads(state, side, rand);
    }

    @Override
    public boolean isAmbientOcclusion() {
        return parent.isAmbientOcclusion();
    }

    @Override
    public boolean isGui3d() {
        return parent.isGui3d();
    }

    @Override
    public boolean isBuiltInRenderer() {
        return parent.isBuiltInRenderer();
    }

    @Override
    public TextureAtlasSprite getParticleTexture() {
        return parent.getParticleTexture();
    }

    @Override
    public ItemCameraTransforms getItemCameraTransforms() {
        return parent.getItemCameraTransforms();
    }

    @Override
    public ItemOverrideList getOverrides() {
        return parent.getOverrides();
    }
}


text:
drop index TGPK_IDX;
drop index TRANSCRIGENE_GENE_ID;
drop index TG_TI_INDEX;

--EXIT;

redpajama_set_name: RedPajamaGithub


text:
import util from 'util';
import logger from './logger';

/**
 * 404 HTTP Error
 */
export function NotFound(desc) {
  Error.call(this);

  this.status = 404;
  this.description = desc;
}

util.inherits(NotFound, Error);

/**
 * 500 HTTP Error
 */
export function InternalServerError(desc) {
  Error.call(this);

  this.status = 500;
  this.description = desc;
}

util.inherits(InternalServerError, Error);

/**
 * 400 HTTP Error
 */
export function BadRequest(desc) {
  Error.call(this);

  this.status = 400;
  this.description = desc;
}

util.inherits(BadRequest, Error);

/**
 * 401 HTTP Error
 */
export function Unauthorized(desc) {
  Error.call(this);

  this.status = 401;
  this.description = desc;
}

util.inherits(Unauthorized, Error);

/**
 * 403 HTTP Error
 */
export function Forbidden(desc) {
  Error.call(this);

  this.status = 403;
  this.description = desc;
}

util.inherits(Forbidden, Error);

/**
 * Application Error Handler
 */
export function handler(error, req, res, next) {
  let err;

  // if there is a status, it is a known error
  if (error.status) {
    err = error;

  // otherwise, make a new error
  } else {
    err = new InternalServerError(error);
  }

  logger.error(error);

  // send the error back to the client
  res.status(err.status).json(err);
}


text:
<?php namespace common\components\base\storage;

use common\components\helpers\FileHelper;

/**
 * @property string $url
 * @property string $relativePath
 * @property string $storeRoot
 *
 * Class StorageItem
 * @package common\components\base\storage
 */
class StorageItem extends \SplFileInfo
{
    protected $storeRoot;
    protected $relativePath;

    public function __construct(\SplFileInfo $fileInfo)
    {
        parent::__construct($fileInfo);
        $path = FileHelper::join($this->getPath(), $this->getFilename());

        /* @var \common\components\base\storage\Storage $storage */
        $storage = \Yii::$app->get('storage');

        if (strpos($path, $storage->getRootPath()) === 0) {
            $relativePath = substr($path, strlen($storage->getRootPath()));
            $this->storeRoot = FileHelper::shift($relativePath);
            if (!Storage::hasRootPath($this->storeRoot)) {
                throw new \InvalidArgumentException("Undefined storage root: `{$this->storeRoot}`");
            }
            $this->relativePath = $relativePath;
        } else {
            throw new \InvalidArgumentException("This file is not in the storage: `{$path}`");
        }
    }

    public function getUrl()
    {
        return Storage::buildUrl($this->storeRoot, $this->relativePath);
    }

    public function getRelativePath()
    {
        return $this->relativePath;
    }

    public function getStoreRoot()
    {
        return $this->storeRoot;
    }

}


text:
package com.amazingmvprules.domain.interactors;

import com.amazingmvprules.domain.model.Genre;
import com.amazingmvprules.domain.repository.GenreReposity;
import com.amazingmvprules.domain.service.GenreService;
import com.amazingmvprules.domain.util.DebugUtil;
import com.bluelinelabs.logansquare.LoganSquare;
import com.github.ppamorim.threadexecutor.Interactor;
import com.github.ppamorim.threadexecutor.InteractorExecutor;
import com.github.ppamorim.threadexecutor.MainThread;
import java.io.InputStream;
import java.util.ArrayList;
import javax.inject.Inject;
import okhttp3.OkHttpClient;

public class HomeInteractorImpl extends BaseImpl implements Interactor, HomeInteractor {

  private OkHttpClient okHttpClient;
  private final InteractorExecutor interactorExecutor;
  private final MainThread mainThread;
  private Callback callback;

  @Inject HomeInteractorImpl(InteractorExecutor interactorExecutor, MainThread mainThread,
      OkHttpClient okHttpClient) {
    this.interactorExecutor = interactorExecutor;
    this.mainThread = mainThread;
    this.okHttpClient = okHttpClient;
  }

  @Override public void execute(Callback callback) {
    validateArguments(callback);
    this.callback = callback;
    this.interactorExecutor.run(this);
  }

  @Override public void run() {
    try {
      Object result = new GenreService(okHttpClient).requestGenres();
      if (result instanceof InputStream) {
        handleArrayOfItems((ArrayList<Genre>) LoganSquare.parseList(
            (InputStream) result, Genre.class));
      }
    } catch (Exception e) {
      if (DebugUtil.DEBUG) {
        e.printStackTrace();
      }
      notifyNoConnection(0);
      if (!loadFromRepository()) {
        notifyConnectionError();
      }
    }
  }

  private void handleArrayOfItems(ArrayList<Genre> genres) {
    if (genres.size() > 0) {
      GenreReposity.handleGenres(genres);
      notifyConnectionSuccess(genres);
    } else if (!loadFromRepository()) {
      notifyEmpty();
    }
  }

  /**
   * Try to retrieve the information from
   * the database.
   *
   * @return it has success on query
   */
  private boolean loadFromRepository() {
    ArrayList<Genre> genres = (ArrayList<Genre>) GenreReposity.queryGenres();
    if (genres != null && genres.size() > 0) {
      notifyConnectionSuccess(genres);
      return true;
    }
    return false;
  }

  private void notifyConnectionSuccess(final ArrayList<Genre> subGenres) {
    mainThread.post(new Runnable() {
      @Override public void run() {
        callback.onGenresLoaded(subGenres);
      }
    });
  }

  private void notifyEmpty() {
    mainThread.post(new Runnable() {
      @Override public void run() {
        callback.onGenresEmpty();
      }
    });
  }

  private void notifyConnectionError() {
    mainThread.post(new Runnable() {
      @Override public void run() {
        callback.onErrorLoad();
      }
    });
  }

  private void notifyNoConnection(final int reason) {
    mainThread.post(new Runnable() {
      @Override public void run() {
        callback.onNoConnection(reason);
      }
    });
  }

}


text:
package org.commonjava.indy.revisions;

import static org.apache.commons.lang3.StringUtils.join;
import static org.commonjava.indy.audit.ChangeSummary.SYSTEM_USER;
import static org.commonjava.indy.subsys.git.GitManager.COMMIT_CHANGELOG_ENTRIES;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;

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

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.commonjava.indy.action.IndyLifecycleEventManager;
import org.commonjava.indy.audit.ChangeSummary;
import org.commonjava.indy.revisions.conf.RevisionsConfig;
import org.commonjava.indy.revisions.testutil.TestProvider;
import org.commonjava.indy.subsys.datafile.DataFile;
import org.commonjava.indy.subsys.datafile.DataFileManager;
import org.commonjava.indy.subsys.datafile.change.DataFileEvent;
import org.commonjava.indy.test.utils.WeldJUnit4Runner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;

@RunWith( WeldJUnit4Runner.class )
public class RevisionsManagerTest
{

    @Rule
    public TemporaryFolder temp = new TemporaryFolder();

    @Inject
    private RevisionsManager revManager;

    @Inject
    private RevisionsConfig config;

    @Inject
    private DataFileManager dfManager;

    @Inject
    private DataFileTestEventListener listener;

    @Inject
    private IndyLifecycleEventManager lcEvents;

    @Before
    public void setup()
    {
        TestProvider.setTemporaryFolder( temp );
        config.setEnabled( true );
    }

    @Test
    public void commitTwoDifferentFilesAndRetrieveChangelogForOneOfThem()
        throws Exception
    {
        lcEvents.fireStarted();
        final DataFile f1 = dfManager.getDataFile( "test/foo.txt" );
        f1.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for first file." ) );

        final DataFile f2 = dfManager.getDataFile( "test/bar.txt" );
        f2.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for second file." ) );

        revManager.commitDataUpdates();

        f2.writeString( "this is another test", "UTF-8", new ChangeSummary( "test-user", "test (2) for second file." ) );

        final List<DataFileEvent> events = listener.waitForEvents( 3 );
        System.out.println( "Got events:\n  " + join( events, "\n  " ) );

        revManager.commitDataUpdates();
        final List<ChangeSummary> changeLog = revManager.getDataChangeLog( f2.getPath(), 0, -1 );
        assertThat( changeLog, notNullValue() );
        assertThat( changeLog.size(), equalTo( 2 ) );
    }

    @Test
    public void commitOneFileTwice_NoChangeSecondTime_RetrieveOneChangelog()
        throws Exception
    {
        lcEvents.fireStarted();
        revManager.setup();

        final DataFile f1 = dfManager.getDataFile( "test/foo.txt" );
        f1.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for first write of file." ) );

        List<DataFileEvent> events = listener.waitForEvents( 1 );
        System.out.println( "Got events:\n  " + join( events, "\n  " ) );

        f1.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for second write of file." ) );

        events = listener.waitForEvents( 1 );
        System.out.println( "Got events:\n  " + join( events, "\n  " ) );

        revManager.commitDataUpdates();
        final List<ChangeSummary> changeLog = revManager.getDataChangeLog( f1.getPath(), 0, -1 );
        assertThat( changeLog, notNullValue() );
        assertThat( changeLog.size(), equalTo( 1 ) );

        assertThat( changeLog.get( 0 )
                             .getSummary()
                             .contains( "test for first write of file." ), equalTo( true ) );
    }

    @Test
    public void commitOneFileTwice_ChangedBeforeServerStart_FirstChangelogAppearsOnServerStart()
        throws Exception
    {
        revManager.setup();

        final DataFile f1 = dfManager.getDataFile( "test/foo.txt" );
        f1.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for first write of file." ) );

        List<DataFileEvent> events = listener.waitForEvents( 1 );
        System.out.println( "Got events:\n  " + join( events, "\n  " ) );

        f1.writeString( "this is another test", "UTF-8", new ChangeSummary( "test-user",
                                                                            "test for second write of file." ) );

        events = listener.waitForEvents( 1 );

        System.out.println( "Got events:\n  " + join( events, "\n  " ) );

        revManager.commitDataUpdates();
        List<ChangeSummary> changeLog = revManager.getDataChangeLog( f1.getPath(), 0, -1 );
        assertThat( changeLog, notNullValue() );
        assertThat( changeLog.size(), equalTo( 0 ) );

        lcEvents.fireStarted();

        revManager.commitDataUpdates();
        changeLog = revManager.getDataChangeLog( f1.getPath(), 0, -1 );
        assertThat( changeLog, notNullValue() );
        assertThat( changeLog.size(), equalTo( 1 ) );

        assertThat( changeLog.get( 0 )
                             .getSummary()
                             .contains( RevisionsManager.CATCHUP_CHANGELOG_MODIFIED ), equalTo( true ) );
    }

    @Test
    public void commitTwoDifferentFilesAndRetrieveChangelogForOneOfThem_LimitToOldestEvent()
        throws Exception
    {
        lcEvents.fireStarted();
        final DataFile f1 = dfManager.getDataFile( "test/foo.txt" );
        f1.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", "test for first file." ) );

        final DataFile f2 = dfManager.getDataFile( "test/bar.txt" );
        final String testSummary = "test for second file.";
        f2.writeString( "this is a test", "UTF-8", new ChangeSummary( "test-user", testSummary ) );
        f2.writeString( "this is another test", "UTF-8", new ChangeSummary( "test-user", "test (2) for second file." ) );

        listener.waitForEvents( 3 );

        revManager.commitDataUpdates();
        final List<ChangeSummary> changeLog = revManager.getDataChangeLog( f2.getPath(), 0, 1 );
        assertThat( changeLog, notNullValue() );
        assertThat( changeLog.size(), equalTo( 1 ) );

        final ChangeSummary summary = changeLog.get( 0 );
        assertThat( summary.getSummary()
                           .contains( testSummary ), equalTo( true ) );
    }

    @ApplicationScoped
    public static class DataFileTestEventListener
    {
        private final List<DataFileEvent> events = new ArrayList<>();

        public synchronized void event( @Observes final DataFileEvent event )
        {
            events.add( event );
            notifyAll();
        }

        public synchronized List<DataFileEvent> waitForEvents( final int size )
        {
            while ( events.size() < size )
            {
                try
                {
                    wait();
                }
                catch ( final InterruptedException e )
                {
                    return Collections.emptyList();
                }
            }

            final List<DataFileEvent> result = new ArrayList<>( events );
            events.clear();
            return result;
        }
    }

}


text:
@interface AroundHelper ()
//AroundMainModel.h数组
@property (nonatomic, strong)NSMutableArray *mutableArray;
@property (nonatomic, strong) AroundMainModel *model;
//存放景点的all
@property (nonatomic, strong)NSMutableArray *allScien;

//存放小景点列表

@property (nonatomic, strong)NSMutableArray *littleScine;

@end

@implementation AroundHelper

 //取得目的城市 和 景点列表 和 tags
- (void)requestWithCityName:(NSString *)name finish:(void (^)(NSArray * array))result{

    NSString *urlString = AROUNDCITY(name);
    NSString *codeUrl = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"%@",codeUrl);//有值
    // 异步 async
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _mutableArray = [NSMutableArray array];
        [manager GET:codeUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
          //  NSLog(@"%@",responseObject);

            NSDictionary *dic = responseObject[@"data"];

            NSArray *arr = dic[@"provinces"];
            NSDictionary *subdic = [arr firstObject];

            //城市名 可能需要到

            //NSString *cityName = subdic[@"province"];
            //给对象赋值 为了筛选url拼接
            //[model setValue:cityName forKey:@"province"];

            NSArray *subArr = subdic[@"cities"];

            for (NSDictionary *diction in subArr) {
                 AroundMainModel *model = [AroundMainModel new];
                [model setValuesForKeysWithDictionary:diction];
                [_mutableArray addObject:model];
            }

 //           NSLog(@"-------------%@",_mutableArray);
//            for (AroundMainModel *m in _mutableArray) {
//                NSLog(@"%@",m);
//            }
            dispatch_async(dispatch_get_main_queue(), ^{

        result(_mutableArray);

    });

        } failure:^(NSURLSessionDataTask *task, NSError *error) {

        }];

    });
}

//所有景点数据
- (void)requsetAllScenicsWithCityName:(NSString *)name finish:(void(^)(NSArray *scenic))result{

    NSString *url = AllScenic(name);

    NSString *codeUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   NSLog(@"all%@",codeUrl);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _allScien = [NSMutableArray array];
        [manager GET:codeUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *dic = responseObject[@"data"];
            NSArray *array = dic[@"items"];
            for (NSDictionary *d in array) {
                AroundKindModel *model = [AroundKindModel new];
                [model setValuesForKeysWithDictionary:d];
                [_allScien addObject:model];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                result(_allScien);

            });

        } failure:^(NSURLSessionDataTask *task, NSError *error) {

        }];

    });

}

//列表小景点请求数据
- (void)requestLittleScenicWithCithName:(NSString *)cityName scenicName:(NSString *)scenicName finish:(void (^)(NSArray * array))result{

    NSString *url = littleScenicURL(scenicName, cityName);

    NSString *codeUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
   // NSLog(@"little%@",codeUrl);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _littleScine = [NSMutableArray array];
        [manager GET:codeUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSDictionary *dic = responseObject[@"data"];
            NSArray *array = dic[@"items"];
            for (NSDictionary *d in array) {
                AroundKindModel *model = [AroundKindModel new];
                [model setValuesForKeysWithDictionary:d];
                [_allScien addObject:model];
            }

            dispatch_async(dispatch_get_main_queue(), ^{
                result(_littleScine);

            });

        } failure:^(NSURLSessionDataTask *task, NSError *error) {

        }];

    });

}

//当目的城市为全部使筛选  cityName 是定位时的城市

- (void)chooseScenicWithTagName:(NSString *)tagName cityName:(NSString *)cityName finish:(void (^)(NSArray * array))result{

    NSString *url = chooseAllCity(tagName, cityName);

    NSString *codeUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

   // NSLog(@"%@",codeUrl);

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSMutableArray *array = [NSMutableArray array];
    [manager GET:codeUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {

        NSDictionary *dic = responseObject[@"data"];
        NSArray *arr = dic[@"items"];
        for (NSDictionary *d in arr) {
            AroundKindModel *model = [AroundKindModel new];
            [model setValuesForKeysWithDictionary:d];
            [_allScien addObject:model];
        }

        dispatch_async(dispatch_get_main_queue(), ^{

            result(array);
        });

    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];

}

@end


text:
package jnode.store;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.*;

/**
 * @author Manjago (kirill@temnenkov.com)
 */
public final class XMLSerializer {

    private XMLSerializer() {
    }

    public static void write(Object f, String filename) throws FileNotFoundException {
        XMLEncoder encoder =
                new XMLEncoder(
                        new BufferedOutputStream(
                                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }

    public static Object read(String filename) throws FileNotFoundException {
        XMLDecoder decoder =
                new XMLDecoder(new BufferedInputStream(
                        new FileInputStream(filename)));
        Object o = decoder.readObject();
        decoder.close();
        return o;
    }
}


text:
////////////////////////////////////////////////////////////////////////////
//
//  This file is part of DueFlash
//
//  Copyright (c) 2013 Pansenti, LLC
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to use,
//  copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
//  Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
//  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
//  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
//  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "DueFlash.h"

DueFlash::DueFlash()
{
  uint32_t retCode;

  /* Initialize flash: 6 wait states for flash writing. */

  retCode = flash_init(FLASH_ACCESS_MODE_128, 6);
  if (retCode != FLASH_RC_OK) {
    _FLASH_DEBUG("Flash init failed\n");
  }
}

boolean DueFlash::write(uint32_t *flashStart, uint32_t *data, uint32_t dataLength)
{
  uint32_t retCode;
  uint32_t byteLength = dataLength * sizeof(uint32_t);

  if ((uint32_t)flashStart < IFLASH1_ADDR) {
    _FLASH_DEBUG("Flash write address too low\n");
    return false;
  }

  if ((uint32_t)flashStart >= (IFLASH1_ADDR + IFLASH1_SIZE)) {
    _FLASH_DEBUG("Flash write address too high\n");
    return false;
  }

  if (((uint32_t)flashStart & 3) != 0) {
      _FLASH_DEBUG("Flash start address must be on four byte boundary\n");
      return false;
  }

  // Unlock page

  retCode = flash_unlock((uint32_t)flashStart, (uint32_t)flashStart + byteLength - 1, 0, 0);
  if (retCode != FLASH_RC_OK) {
    _FLASH_DEBUG("Failed to unlock flash for write\n");
    return false;
  }

  // write data

  retCode = flash_write((uint32_t)flashStart, data, byteLength, 1);

  if (retCode != FLASH_RC_OK) {
    _FLASH_DEBUG("Flash write failed\n");
    return false;
  }

  // Lock page

  retCode = flash_lock((uint32_t)flashStart, (uint32_t)flashStart + byteLength - 1, 0, 0);
  if (retCode != FLASH_RC_OK) {
    _FLASH_DEBUG("Failed to lock flash page\n");
    return false;
  }
  return true;
}


text:
var gulp = require("gulp");
var uglifycss = require("gulp-uglifycss");
var sass = require("gulp-concat");

gulp.task('scss', function (){
	// what files do i want to look for
	gulp.src("src/scss/app.scss")
	.pipe(sass())
	.pipe(uglifycss({
      "maxLineLen": 80,
      "uglyComments": true
    .pipe(gulp.dest('.dist/css'))
    }))
	// where should i put the renamed file(s)
	.pipe(gulp.dest('./dist/'));

});

gulp.task ('default', function(){
 console.log('hello');
});

// Watch Files For Changes
gulp.task('watch', function() {
    gulp.watch('src/scss/*.scss', ['scss']);
});

	// Default Task


text:
'use strict';

const DiffArea = require('../diff-area');
const jsgraphs = require('js-graph-algorithms');

const hasOverlap = (cluster1, cluster2) => {
    if (cluster1.left > cluster2.right || cluster2.left > cluster1.right) {
        return false;
    }

    if (cluster1.bottom < cluster2.top || cluster2.bottom < cluster1.top) {
        return false;
    }

    return true;
};

const getConnectedComponents = (clusters) => {
    const graph = new jsgraphs.Graph(clusters.length);

    clusters.forEach((c1, i) => {
        clusters.forEach((c2, j) => {
            if (i !== j && hasOverlap(c1.area, c2.area)) {
                graph.addEdge(i, j);
            }
        });
    });

    return new jsgraphs.ConnectedComponents(graph);
};

exports.join = (clusters) => {
    const connectedComponents = getConnectedComponents(clusters);

    return connectedComponents.id.reduce((acc, clusterId, i) => {
        const {left, top, right, bottom} = clusters[i].area;
        if (!acc[clusterId]) {
            acc[clusterId] = DiffArea.create();
        }

        acc[clusterId]
            .update(left, top)
            .update(right, bottom);

        return acc;
    }, []);
};


text:
"""@package Data
Methods for IoT Analytics component type catalog
"""
from globals import *
from utils import *
import requests
import time

class ComponentCatalog:
    def __init__(self, acct=None):
        self.acct = acct

    def add_comp_type(self):
        pass
    def get_comp_types(self):
        pass
    def get_comp_type(self):
        pass
    def update_comp_type(self):
        pass


text:
<?php
/*
Plugin Name: YouTube SimpleGallery
Plugin URI: http://wpwizard.net/plugins/youtube-simplegallery/
Description: A YouTube Gallery Plugin, that lets you add a gallery of videos to any Page or Post. How to use.
Author: Stian Andreassen
Author URI: http://www.wpwizard.net
Version: 2.0.6
*/

global $youtube_gallery_verson, $youtube_gallery_count, $youtube_gallery_ID, $youtube_gallery_url;
$youtube_gallery_version = '2.0.6';
$youtube_gallery_count = 0;
$youtube_gallery_ID = 0;
$youtube_gallery_url = plugins_url('/', __FILE__);

// ADD SETTINGS LINK ON PLUGIN PAGE
function youtubegallery_settings_link($links, $file) {
	static $this_plugin;
	if (!$this_plugin) $this_plugin = plugin_basename(__FILE__);

	if ($file == $this_plugin){
		$settings_link = ''.__('Settings').'';
		array_unshift($links, $settings_link);
	}
	return $links;
}
add_filter('plugin_action_links', 'youtubegallery_settings_link', 10, 2 );

// SHOW OPTIONS
include('inc/options.php');

// ADMIN NOTICES
include('inc/notices.php');

// GET ONLY URL IF AUTO EMBED IS ON
function yotube_gallery_getAttribute($attrib, $tag){
  //get attribute from html tag
  $re = '/'.$attrib.'=["\']?([^"\' ]*)["\' ]/is';
  preg_match($re, $tag, $match);
  if($match){
    return urldecode($match[1]);
  }else {
    return false;
  }
}

// GET YOUTUBE VIDEO ID
function yotube_gallery_getYouTubeIdFromURL($url) {
	$pattern = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i';
	preg_match($pattern, $url, $matches);
	return isset($matches[1]) ? $matches[1] : false;
}

// GET YOUTUBE VIDEO DATA
function yotube_gallery_getYouTubeDataFromID($vID) {
	$videodata = wp_remote_fopen('http://gdata.youtube.com/feeds/api/videos/'.trim($vID));
	if($videodata=='Video not found') {
		return 'error';
	}
	else {
		$videodata = new SimpleXMLElement($videodata);
		return $videodata;
	}
}

// GET VIMEO VIDEO DATA
function yotube_gallery_getVimeoDataFromID($vID) {
	$videodata = wp_remote_fopen('http://vimeo.com/api/v2/video/'.trim($vID).'.json');
	if($videodata==$vID.' not found.') {
		return 'error';
	}
	else {
		$videodata = reset(json_decode($videodata, true));
		return $videodata;
	}
}

// SHORTCODE FOR GALLERY
include('inc/shortcode.php');

// MULTI WIDGETS
include('inc/admin-widgets.php');

// ON INSTALL PLUGIN
function youtubegallery_install(){
	add_option('youtube_gallery_option',
		array(
			'thumbwidth' => '135',
			'cols' => '4',
			'autotitles' => 'fetch',
			'title' => 'below',
			'pb' => 'usepb',
			'jq' => 'usejq',
			'css' => 'usecss',
			'titlecss' => "text-align: center;\nfont-size: 1em;\nfont-style: italic;",

			'width' => '640',
			'height' => '370',
			'start' => 'autoplay',
			'hd' => 'usehd',
			'related' => 'dontshow',
			'thickbox' => 'thickbox',
		)
	);
}

// ON UNINSTALL PLUGIN
function youtubegallery_uninstall(){
	delete_option('youtube_gallery_option');
}

// ADD SCRIPTS TO ADMIN
function yotube_gallery_load_custom_wp_admin() {
global $youtube_gallery_url;
	wp_enqueue_script('jquery');
	wp_enqueue_script('jquery-ui-accordion');
	wp_enqueue_script('youtube_simplegallery', $youtube_gallery_url.'youtube_simplegallery.js', null, null, true);
	wp_enqueue_style('youtube_simplegallery_admin', $youtube_gallery_url.'admin.css');
}
add_action( 'admin_enqueue_scripts', 'yotube_gallery_load_custom_wp_admin' );

// LOAD CSS IN FRONTEND
function youtube_gallery_load_css() {
	global $youtube_gallery_url;
	$youtubeoptions = get_option('youtube_gallery_option');
	// USE CSS?
	if($youtubeoptions['css'] == 'usecss')
		wp_enqueue_style('youtube-simplegallery', $youtube_gallery_url.'youtube_simplegallery.css');
}
add_action( 'wp_enqueue_scripts', 'youtube_gallery_load_css' );

// INIT
function yotube_gallery_init() {
	session_start();
}
add_action('init', 'yotube_gallery_init');

// SESSION FOR DYNAMIC STYLES, OUTPUT IN FOOTER
function youtube_gallery_shortcode_styles() {
	echo ''."\r\n";
	session_destroy();
}
add_action('wp_footer', 'youtube_gallery_shortcode_styles');

// HOOK IT UP TO WORDPRESS
register_activation_hook(__FILE__,'youtubegallery_install');
register_deactivation_hook(__FILE__,'youtubegallery_uninstall');
add_filter("plugin_action_links_$plugin", 'youtubegallery_settings_link' );

?>


text:
package io.primeval.saga.controller;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import io.primeval.component.annotation.properties.ComponentProperty;
import io.primeval.component.annotation.properties.EnsureProvideService;
import io.primeval.saga.SagaConstants;

/**
 * Declares a controller.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ComponentProperty(SagaConstants.SAGA_CONTROLLER)
@EnsureProvideService
public @interface Controller {
}


text:
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six

# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
  import builtins as __builtin__
  long = int
elif six.PY2:
  import __builtin__

class openconfig_gribi(PybindBase):
  """
  This class was auto-generated by the PythonClass plugin for PYANG
  from YANG module openconfig-gribi - based on the path /openconfig-gribi. Each member element of
  the container is represented as a class variable - with a specific
  YANG type.

  YANG Description: This module defines a set of exdtensions that provide gRIBI (the gRPC
RIB Interface) specific extensions to the OpenConfig data models.
Specifically, the parameters for the configuration of the service, and
configuration and state are added.

The gRIBI protobufs and documentation are published at
https://github.com/openconfig/gribi.
  """
  _pyangbind_elements = {}


text:
REDMASH
==========

This file is being merged with timesearch. https://github.com/voussoir/reddit/tree/master/Prawtimestamps


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.ConnectionDirection;
import com.microsoft.graph.models.SecurityNetworkProtocol;
import com.microsoft.graph.models.ConnectionStatus;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Network Connection.
 */
public class NetworkConnection implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Application Name.
     * Name of the application managing the network connection (for example, Facebook or SMTP).
     */
    @SerializedName(value = "applicationName", alternate = {"ApplicationName"})
    @Expose
	@Nullable
    public String applicationName;

    /**
     * The Destination Address.
     * Destination IP address (of the network connection).
     */
    @SerializedName(value = "destinationAddress", alternate = {"DestinationAddress"})
    @Expose
	@Nullable
    public String destinationAddress;

    /**
     * The Destination Domain.
     * Destination domain portion of the destination URL. (for example 'www.contoso.com').
     */
    @SerializedName(value = "destinationDomain", alternate = {"DestinationDomain"})
    @Expose
	@Nullable
    public String destinationDomain;

    /**
     * The Destination Location.
     * Location (by IP address mapping) associated with the destination of a network connection.
     */
    @SerializedName(value = "destinationLocation", alternate = {"DestinationLocation"})
    @Expose
	@Nullable
    public String destinationLocation;

    /**
     * The Destination Port.
     * Destination port (of the network connection).
     */
    @SerializedName(value = "destinationPort", alternate = {"DestinationPort"})
    @Expose
	@Nullable
    public String destinationPort;

    /**
     * The Destination Url.
     * Network connection URL/URI string - excluding parameters. (for example 'www.contoso.com/products/default.html')
     */
    @SerializedName(value = "destinationUrl", alternate = {"DestinationUrl"})
    @Expose
	@Nullable
    public String destinationUrl;

    /**
     * The Direction.
     * Network connection direction. Possible values are: unknown, inbound, outbound.
     */
    @SerializedName(value = "direction", alternate = {"Direction"})
    @Expose
	@Nullable
    public ConnectionDirection direction;

    /**
     * The Domain Registered Date Time.
     * Date when the destination domain was registered. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z
     */
    @SerializedName(value = "domainRegisteredDateTime", alternate = {"DomainRegisteredDateTime"})
    @Expose
	@Nullable
    public java.time.OffsetDateTime domainRegisteredDateTime;

    /**
     * The Local Dns Name.
     * The local DNS name resolution as it appears in the host's local DNS cache (for example, in case the 'hosts' file was tampered with).
     */
    @SerializedName(value = "localDnsName", alternate = {"LocalDnsName"})
    @Expose
	@Nullable
    public String localDnsName;

    /**
     * The Nat Destination Address.
     * Network Address Translation destination IP address.
     */
    @SerializedName(value = "natDestinationAddress", alternate = {"NatDestinationAddress"})
    @Expose
	@Nullable
    public String natDestinationAddress;

    /**
     * The Nat Destination Port.
     * Network Address Translation destination port.
     */
    @SerializedName(value = "natDestinationPort", alternate = {"NatDestinationPort"})
    @Expose
	@Nullable
    public String natDestinationPort;

    /**
     * The Nat Source Address.
     * Network Address Translation source IP address.
     */
    @SerializedName(value = "natSourceAddress", alternate = {"NatSourceAddress"})
    @Expose
	@Nullable
    public String natSourceAddress;

    /**
     * The Nat Source Port.
     * Network Address Translation source port.
     */
    @SerializedName(value = "natSourcePort", alternate = {"NatSourcePort"})
    @Expose
	@Nullable
    public String natSourcePort;

    /**
     * The Protocol.
     * Network protocol. Possible values are: unknown, ip, icmp, igmp, ggp, ipv4, tcp, pup, udp, idp, ipv6, ipv6RoutingHeader, ipv6FragmentHeader, ipSecEncapsulatingSecurityPayload, ipSecAuthenticationHeader, icmpV6, ipv6NoNextHeader, ipv6DestinationOptions, nd, raw, ipx, spx, spxII.
     */
    @SerializedName(value = "protocol", alternate = {"Protocol"})
    @Expose
	@Nullable
    public SecurityNetworkProtocol protocol;

    /**
     * The Risk Score.
     * Provider generated/calculated risk score of the network connection. Recommended value range of 0-1, which equates to a percentage.
     */
    @SerializedName(value = "riskScore", alternate = {"RiskScore"})
    @Expose
	@Nullable
    public String riskScore;

    /**
     * The Source Address.
     * Source (i.e. origin) IP address (of the network connection).
     */
    @SerializedName(value = "sourceAddress", alternate = {"SourceAddress"})
    @Expose
	@Nullable
    public String sourceAddress;

    /**
     * The Source Location.
     * Location (by IP address mapping) associated with the source of a network connection.
     */
    @SerializedName(value = "sourceLocation", alternate = {"SourceLocation"})
    @Expose
	@Nullable
    public String sourceLocation;

    /**
     * The Source Port.
     * Source (i.e. origin) IP port (of the network connection).
     */
    @SerializedName(value = "sourcePort", alternate = {"SourcePort"})
    @Expose
	@Nullable
    public String sourcePort;

    /**
     * The Status.
     * Network connection status. Possible values are: unknown, attempted, succeeded, blocked, failed.
     */
    @SerializedName(value = "status", alternate = {"Status"})
    @Expose
	@Nullable
    public ConnectionStatus status;

    /**
     * The Url Parameters.
     * Parameters (suffix) of the destination URL.
     */
    @SerializedName(value = "urlParameters", alternate = {"UrlParameters"})
    @Expose
	@Nullable
    public String urlParameters;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
void* alMalloc(size_t size, int alignment) {
	const size_t pSize = sizeof(void*), a = alignment - 1;
	void *raw = malloc(size + a + pSize);
	void *aligned = (void*)(((size_t)raw + pSize + a) & ~a);
	*(void**)((size_t)aligned - pSize) = raw;
	return aligned;
}

// platform independent alignned memory de-allocation (see also alMalloc)
void alFree(void* aligned) {
	void* raw = *(void**)((char*)aligned - sizeof(void*));
	free(raw);
}


text:
Executable	{executable}

Version	{version}

    Features

      {?is_64bit}(64-bit){:else}(32-bit){/is_64bit}
      {?have_ucs4}(with UCS-4){:else}(with UCS-2){/have_ucs4}
      {?have_readline}(with readline support){:else}(no readline support){/have_readline}

Thread count	{active_thread_count}

  {#gc}
  {#obj_count}

Object count	{obj_count}

  {:else}

Object count	(unavailable)

  {/obj_count}

GC enabled	{is_enabled}

GC thresholds	{thresholds}

GC generations	{counts}

  {:else}

Object count	(failed to load GC info)

  {/gc}

Recursion limit	{recursion_limit}

Check interval	{check_interval}


text:
<?php
/**
* Framework engine class.
* @path /engine/core/engine.php
*
* @name    Nodes Studio    @version 2.0.1.9
* @author  Aleksandr Vorkunov  <developing@nodes-tech.ru>
* @license http://www.apache.org/licenses/LICENSE-2.0
*
* @example  engine::timezone_list();
*/
class engine{
//------------------------------------------------------------------------------
/**
* Includes a file from engine/core/../<function_name>.php and
* execute <function_name>($arguments[0], $arguments[1], ...);
*
* @param string $name <function_name>
* @param array $arguments Array of arguments.
* @return mixed Returns result of targeted function or die with error.
*
* @example
*  engine::print_paypal_form($site, 10, "/account/finance");
*
*/
public static function __callStatic($name, $arguments) {
    array_push($_SERVER["CONSOLE"], "engine::".$name);
    $exec = function_exists($name);
    if(!$exec && !empty($_SERVER["CORE_PATH"])){
        if(is_file('engine/core/'.$_SERVER["CORE_PATH"].'/'.$name.'.php')){
            require_once('engine/core/'.$_SERVER["CORE_PATH"].'/'.$name.'.php');
            $exec = 1;
        }
    }
    if(!$exec && is_file('engine/core/function/'.$name.'.php')){
        require_once('engine/core/function/'.$name.'.php');
        $exec = 1;
    }
    if(!$exec){
        $skip = array('.', '..', 'function', $_SERVER["CORE_PATH"]);
        $files = scandir('engine/core/');
        foreach($files as $file) {
            if(!in_array($file, $skip)){
                if(is_file('engine/core/'.$file.'/'.$name.'.php')){
                    require_once('engine/core/'.$file.'/'.$name.'.php');
                    $exec = 1;
                    break;
                }
            }
        }
    }
    if($exec){
        $count = count($arguments);
        if(!$count){
            return $name();
        }else if($count==1){
            return $name($arguments[0]);
        }else if($count==2){
            return $name(
                    $arguments[0],
                    $arguments[1]
                    );
        }else if($count==3){
            return $name(
                    $arguments[0],
                    $arguments[1],
                    $arguments[2]
                    );
        }else if($count==4){
            return $name(
                    $arguments[0],
                    $arguments[1],
                    $arguments[2],
                    $arguments[3]
                    );
        }else if($count==5){
            return $name(
                    $arguments[0],
                    $arguments[1],
                    $arguments[2],
                    $arguments[3],
                    $arguments[4]
                    );
        }else if($count==6){
            return $name(
                    $arguments[0],
                    $arguments[1],
                    $arguments[2],
                    $arguments[3],
                    $arguments[4],
                    $arguments[5]
                    );
        }else if($count==7){
            return $name(
                    $arguments[0],
                    $arguments[1],
                    $arguments[2],
                    $arguments[3],
                    $arguments[4],
                    $arguments[5],
                    $arguments[6]
                    );
        }
    }else self::error();
}
//------------------------------------------------------------------------------
/**
* Register error in a DB and print error page.
*
* @param string $error_code HTTP code of error.
* @usage  engine::error(401);
*/
static function error($error_code='0'){
    array_push($_SERVER["CONSOLE"], "engine::error(".$error_code.")");
    if($error_code != 0) $_GET[$error_code] = 1;
    if(!isset($_GET["204"]) && !isset($_GET["504"])){
        $_SERVER["SCRIPT_URI"] = str_replace($_SERVER["PROTOCOL"]."://","\$h", $_SERVER["SCRIPT_URI"]);
        while($_SERVER["SCRIPT_URI"][strlen($_SERVER["SCRIPT_URI"])-1]=="/"){
            $_SERVER["SCRIPT_URI"] = mb_substr($_SERVER["SCRIPT_URI"], 0, strlen($_SERVER["SCRIPT_URI"])-1);
        }$_SERVER["SCRIPT_URI"] = str_replace("\$h", $_SERVER["PROTOCOL"]."://", $_SERVER["SCRIPT_URI"]);
        if(empty($_SERVER["SCRIPT_URI"])) $_SERVER["SCRIPT_URI"]="/";
        $get = $session = $post = '';
        $get = print_r($_GET, 1);
        $post = print_r($_POST, 1);
        $session = print_r($_SESSION, 1);
        $get = engine::escape_string($get);
        $post = engine::escape_string($post);
        $session = engine::escape_string($session);
        $query = 'DELETE FROM `nodes_cache` WHERE `url` = "'.$_SERVER["SCRIPT_URI"].'" '
                . 'AND `lang` = "'.$_SESSION["Lang"].'"';
        engine::mysql($query);
        $query = 'SELECT * FROM `nodes_error` WHERE '
                . '`url` = "'.$_SERVER["SCRIPT_URI"].'" AND '
                . '`lang` = "'.$_SESSION["Lang"].'" AND '
                . '`ip` = "'.$_SERVER["REMOTE_ADDR"].'" AND '
                . '`get` = "'.$get.'" AND '
                . '`post` = "'.$post.'" AND '
                . '`session` = "'.$session.'"';
        $res = engine::mysql($query);
        $data = mysqli_fetch_array($res);
        if(empty($data)){
            $query = 'INSERT INTO `nodes_error`(`url`, `lang`, `date`, `ip`, `get`, `post`, `session`, `count`) '
            . 'VALUES("'.$_SERVER["SCRIPT_URI"].'", '
                    . '"'.$_SESSION["Lang"].'", '
                    . '"'.date("U").'", '
                    . '"'.$_SERVER["REMOTE_ADDR"].'", '
                    . '"'.$get.'", '
                    . '"'.$post.'", '
                    . '"'.$session.'", '
                    . '"1")';
        }else{
           $query = 'UPDATE `nodes_error` SET `date` = "'.date("U").'", `count` = "'.($data["count"]+1).'" WHERE `id` = "'.$data["id"].'"';
        }
        self::mysql($query);
    }
    if(empty($_POST["jQuery"])){ echo '<!DOCTYPE html>

    <title>Error</title><meta charset="UTF-8" />
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    ';
        require_once("engine/code/error.php");
        echo '';
    }else{
        require_once("engine/code/error.php");
    }
    $query = 'SELECT `value` FROM `nodes_config` WHERE `name` = "debug"';
    $res = self::mysql($query);
    $data = mysqli_fetch_array($res);
    if($data[0]){
        echo "


text:
/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { MODULES_ANALYTICS_4 } from './constants';
import accounts from './accounts';
import api from './api';
import baseModuleStore from './base';
import properties from './properties';
import tags from './tags';
import webdatastreams from './webdatastreams';
import { createSnapshotStore } from '../../../googlesitekit/data/create-snapshot-store';

const store = Data.combineStores(
	accounts,
	api,
	baseModuleStore,
	createSnapshotStore( MODULES_ANALYTICS_4 ),
	properties,
	tags,
	webdatastreams
);

export const initialState = store.initialState;
export const actions = store.actions;
export const controls = store.controls;
export const reducer = store.reducer;
export const resolvers = store.resolvers;
export const selectors = store.selectors;

export const registerStore = ( registry ) => {
	registry.registerStore( MODULES_ANALYTICS_4, store );
};

export default store;


text:
package server

import (
	"fmt"
	"io"
	"net"
	"os"
	"strings"

	"contrib.go.opencensus.io/exporter/prometheus"
	ot "github.com/opentracing/opentracing-go"
	oprometheus "github.com/prometheus/client_golang/prometheus"
	"go.opencensus.io/plugin/ocgrpc"
	"go.opencensus.io/stats/view"
	"google.golang.org/grpc"
	"k8s.io/apimachinery/pkg/runtime/schema"

	mixerpb "istio.io/api/mixer/v1"
	"istio.io/istio/mixer/pkg/adapter"
	"istio.io/istio/mixer/pkg/api"
	"istio.io/istio/mixer/pkg/checkcache"
	"istio.io/istio/mixer/pkg/config"
	"istio.io/istio/mixer/pkg/config/crd"
	"istio.io/istio/mixer/pkg/config/store"
	"istio.io/istio/mixer/pkg/loadshedding"
	"istio.io/istio/mixer/pkg/runtime"
	runtimeconfig "istio.io/istio/mixer/pkg/runtime/config"
	"istio.io/istio/mixer/pkg/runtime/dispatcher"
	"istio.io/istio/mixer/pkg/template"
	"istio.io/istio/pkg/tracing"
	"istio.io/pkg/ctrlz"
	"istio.io/pkg/log"
	"istio.io/pkg/pool"
	"istio.io/pkg/probe"
)

// Server is an in-memory Mixer service.

type Server struct {
	shutdown  chan error
	server    *grpc.Server
	gp        *pool.GoroutinePool
	adapterGP *pool.GoroutinePool
	listener  net.Listener
	monitor   *monitor
	tracer    io.Closer

	checkCache *checkcache.Cache
	dispatcher dispatcher.Dispatcher
	controlZ   *ctrlz.Server

	// probes
	livenessProbe  probe.Controller
	readinessProbe probe.Controller
	*probe.Probe
	configStore store.Store
}

type listenFunc func(network string, address string) (net.Listener, error)

// replaceable set of functions for fault injection
type patchTable struct {
	newRuntime func(s store.Store, templates map[string]*template.Info, adapters map[string]*adapter.Info,
		defaultConfigNamespace string, executorPool *pool.GoroutinePool,
		handlerPool *pool.GoroutinePool, enableTracing bool) *runtime.Runtime
	configTracing func(serviceName string, options *tracing.Options) (io.Closer, error)
	startMonitor  func(port uint16, enableProfiling bool, lf listenFunc) (*monitor, error)
	listen        listenFunc
	configLog     func(options *log.Options) error
	runtimeListen func(runtime *runtime.Runtime) error
	remove        func(name string) error

	// monitoring-related setup
	newOpenCensusExporter   func() (view.Exporter, error)
	registerOpenCensusViews func(...*view.View) error
}

// New instantiates a fully functional Mixer server, ready for traffic.
func New(a *Args) (*Server, error) {
	return newServer(a, newPatchTable())
}

func newPatchTable() *patchTable {
	return &patchTable{
		newRuntime:    runtime.New,
		configTracing: tracing.Configure,
		startMonitor:  startMonitor,
		listen:        net.Listen,
		configLog:     log.Configure,
		runtimeListen: func(rt *runtime.Runtime) error { return rt.StartListening() },
		remove:        os.Remove,
		newOpenCensusExporter: func() (view.Exporter, error) {
			return prometheus.NewExporter(prometheus.Options{Registry: oprometheus.DefaultRegisterer.(*oprometheus.Registry)})
		},
		registerOpenCensusViews: view.Register,
	}
}

func newServer(a *Args, p *patchTable) (server *Server, err error) {
	if err := a.validate(); err != nil {
		return nil, err
	}

	if err := p.configLog(a.LoggingOptions); err != nil {
		return nil, err
	}

	s := &Server{}

	defer func() {
		// If return with error, need to close the server.
		if err != nil {
			_ = s.Close()
		}
	}()

	s.gp = pool.NewGoroutinePool(a.APIWorkerPoolSize, a.SingleThreaded)
	s.gp.AddWorkers(a.APIWorkerPoolSize)

	s.adapterGP = pool.NewGoroutinePool(a.AdapterWorkerPoolSize, a.SingleThreaded)
	s.adapterGP.AddWorkers(a.AdapterWorkerPoolSize)

	tmplRepo := template.NewRepository(a.Templates)
	adapterMap := config.AdapterInfoMap(a.Adapters, tmplRepo.SupportsTemplate)

	s.Probe = probe.NewProbe()
	if a.LivenessProbeOptions.IsValid() {
		s.livenessProbe = probe.NewFileController(a.LivenessProbeOptions)
		s.RegisterProbe(s.livenessProbe, "server")
		s.livenessProbe.Start()
	}

	// construct the gRPC options

	var grpcOptions []grpc.ServerOption
	grpcOptions = append(grpcOptions, grpc.MaxConcurrentStreams(uint32(a.MaxConcurrentStreams)), grpc.MaxRecvMsgSize(int(a.MaxMessageSize)))

	if a.TracingOptions.TracingEnabled() {
		s.tracer, err = p.configTracing("istio-mixer", a.TracingOptions)
		if err != nil {
			return nil, fmt.Errorf("unable to setup tracing")
		}
		grpcOptions = append(grpcOptions, grpc.UnaryInterceptor(TracingServerInterceptor(ot.GlobalTracer())))
	}

	// get the network stuff setup
	network, address := extractNetAddress(a.APIPort, a.APIAddress)

	if network == "unix" {
		// remove Unix socket before use.
		if err = p.remove(address); err != nil && !os.IsNotExist(err) {
			// Anything other than "file not found" is an error.
			return nil, fmt.Errorf("unable to remove unix://%s: %v", address, err)
		}
	}

	if s.listener, err = p.listen(network, address); err != nil {
		return nil, fmt.Errorf("unable to listen: %v", err)
	}

	st := a.ConfigStore
	if st == nil {
		configStoreURL := a.ConfigStoreURL
		if configStoreURL == "" {
			configStoreURL = "k8s://"
		}

		reg := store.NewRegistry(config.StoreInventory()...)
		groupVersion := &schema.GroupVersion{Group: crd.ConfigAPIGroup, Version: crd.ConfigAPIVersion}
		if st, err = reg.NewStore(configStoreURL, groupVersion, a.CredentialOptions, runtimeconfig.CriticalKinds()); err != nil {
			return nil, fmt.Errorf("unable to connect to the configuration server: %v", err)
		}
	}

	templateMap := make(map[string]*template.Info, len(a.Templates))
	for k, v := range a.Templates {
		t := v // Make a local copy, otherwise we end up capturing the location of the last entry
		templateMap[k] = &t
	}

	var configAdapterMap map[string]*adapter.Info
	if a.UseAdapterCRDs {
		configAdapterMap = adapterMap
	}
	var configTemplateMap map[string]*template.Info
	if a.UseTemplateCRDs {
		configTemplateMap = templateMap
	}

	kinds := runtimeconfig.KindMap(configAdapterMap, configTemplateMap)

	if err := st.Init(kinds); err != nil {
		return nil, fmt.Errorf("unable to initialize config store: %v", err)
	}

	// block wait for the config store to sync
	log.Info("Awaiting for config store sync...")
	if err := st.WaitForSynced(a.ConfigWaitTimeout); err != nil {
		return nil, err
	}
	s.configStore = st
	log.Info("Starting runtime config watch...")
	rt := p.newRuntime(st, templateMap, adapterMap, a.ConfigDefaultNamespace,
		s.gp, s.adapterGP, a.TracingOptions.TracingEnabled())

	if err = p.runtimeListen(rt); err != nil {
		return nil, fmt.Errorf("unable to listen: %v", err)
	}

	s.dispatcher = rt.Dispatcher()

	// see issue https://github.com/istio/istio/issues/9596
	a.NumCheckCacheEntries = 0

	if a.NumCheckCacheEntries > 0 {
		s.checkCache = checkcache.New(a.NumCheckCacheEntries)
	}

	// get the grpc server wired up
	grpc.EnableTracing = a.EnableGRPCTracing

	exporter, err := p.newOpenCensusExporter()
	if err != nil {
		return nil, fmt.Errorf("could not build opencensus exporter: %v", err)
	}
	view.RegisterExporter(exporter)

	// Register the views to collect server request count.
	if err := p.registerOpenCensusViews(ocgrpc.DefaultServerViews...); err != nil {
		return nil, fmt.Errorf("could not register default server views: %v", err)
	}

	throttler := loadshedding.NewThrottler(a.LoadSheddingOptions)
	if eval := throttler.Evaluator(loadshedding.GRPCLatencyEvaluatorName); eval != nil {
		grpcOptions = append(grpcOptions, grpc.StatsHandler(newMultiStatsHandler(&ocgrpc.ServerHandler{}, eval.(*loadshedding.GRPCLatencyEvaluator))))
	} else {
		grpcOptions = append(grpcOptions, grpc.StatsHandler(&ocgrpc.ServerHandler{}))
	}

	s.server = grpc.NewServer(grpcOptions...)
	mixerpb.RegisterMixerServer(s.server, api.NewGRPCServer(s.dispatcher, s.gp, s.checkCache, throttler))

	if a.ReadinessProbeOptions.IsValid() {
		s.readinessProbe = probe.NewFileController(a.ReadinessProbeOptions)
		rt.RegisterProbe(s.readinessProbe, "dispatcher")
		st.RegisterProbe(s.readinessProbe, "store")
		s.readinessProbe.Start()
	}

	log.Info("Starting monitor server...")
	if s.monitor, err = p.startMonitor(a.MonitoringPort, a.EnableProfiling, p.listen); err != nil {
		return nil, fmt.Errorf("unable to setup monitoring: %v", err)
	}

	s.controlZ, _ = ctrlz.Run(a.IntrospectionOptions, nil)

	return s, nil
}

func extractNetAddress(apiPort uint16, apiAddress string) (string, string) {
	if apiAddress != "" {
		idx := strings.Index(apiAddress, "://")
		if idx < 0 {
			return "tcp", apiAddress
		}

		return apiAddress[:idx], apiAddress[idx+3:]
	}

	return "tcp", fmt.Sprintf(":%d", apiPort)
}

// Run enables Mixer to start receiving gRPC requests on its main API port.
func (s *Server) Run() {
	s.shutdown = make(chan error, 1)
	s.SetAvailable(nil)
	go func() {
		// go to work...
		err := s.server.Serve(s.listener)

		// notify closer we're done
		s.shutdown <- err
	}()
}

// Wait waits for the server to exit.
func (s *Server) Wait() error {
	if s.shutdown == nil {
		return fmt.Errorf("server not running")
	}

	err := <-s.shutdown
	s.shutdown = nil
	return err
}

// Close cleans up resources used by the server.
func (s *Server) Close() error {
	log.Info("Close server")

	if s.shutdown != nil {
		s.server.GracefulStop()
		_ = s.Wait()
	}

	if s.controlZ != nil {
		s.controlZ.Close()
	}

	if s.configStore != nil {
		s.configStore.Stop()
		s.configStore = nil
	}

	if s.checkCache != nil {
		_ = s.checkCache.Close()
	}

	if s.listener != nil {
		_ = s.listener.Close()
	}

	if s.tracer != nil {
		_ = s.tracer.Close()
	}

	if s.monitor != nil {
		_ = s.monitor.Close()
	}

	if s.gp != nil {
		_ = s.gp.Close()
	}

	if s.adapterGP != nil {
		_ = s.adapterGP.Close()
	}

	if s.livenessProbe != nil {
		_ = s.livenessProbe.Close()
	}

	if s.readinessProbe != nil {
		_ = s.readinessProbe.Close()
	}

	// final attempt to purge buffered logs
	_ = log.Sync()

	return nil
}

// Addr returns the address of the server's API port, where gRPC requests can be sent.
func (s *Server) Addr() net.Addr {
	return s.listener.Addr()
}

// Dispatcher returns the dispatcher that was created during server creation. This should only
// be used for testing purposes only.
func (s *Server) Dispatcher() dispatcher.Dispatcher {
	return s.dispatcher
}


text:
package org.uva.sea.ql.gui.questionaire;

import org.uva.sea.ql.ast.Identifier;
import org.uva.sea.ql.ast.TypeVisitor;
import org.uva.sea.ql.ast.type.BooleanType;
import org.uva.sea.ql.ast.type.IntegerType;
import org.uva.sea.ql.ast.type.MissingType;
import org.uva.sea.ql.ast.type.StringType;
import org.uva.sea.ql.gui.widget.BooleanWidget;
import org.uva.sea.ql.gui.widget.Widget;
import org.uva.sea.ql.gui.widget.IntegerWidget;
import org.uva.sea.ql.gui.widget.StringWidget;

public class TypeToWidget implements TypeVisitor<Widget> {

	private final Identifier identifier;
	private final State state;

	public TypeToWidget(Identifier identifier, State state){
		this.identifier = identifier;
		this.state = state;
	}

	public Widget visit(IntegerType type) {
		return new IntegerWidget(identifier, state);
	}

	public Widget visit(StringType type) {
		return new StringWidget(identifier, state);
	}

	public Widget visit(BooleanType booleanType) {
		return new BooleanWidget(identifier,state);
	}

	public Widget visit(MissingType missingType) {
		throw new UnsupportedOperationException();
	}

}


text:
<?php namespace Mauna\Repo\Building;

use Mauna\Repo\RepoAbstract;
use Mauna\Repo\RepoInterface;

class EloquentBuilding extends RepoAbstract implements RepoInterface, BuildingInterface {

    public function __construct(Model $building)
    {
        $this->model = $building;
    }
}


text:
namespace Whathecode.Interop
{
	/// <summary>
	///   Common error codes used throughout win32.
	/// </summary>
	/// <author>Steven Jeuris</author>
	public enum ErrorCode
	{
		/// <summary>
		///   The operation completed successfully.
		/// </summary>
		Success = 0x0000,
		/// <summary>
		///   The system cannot find the file specified.
		/// </summary>
		FileNotFound = 0x0002,
		/// <summary>
		///   The system cannot find the path specified.
		/// </summary>
		PathNotFound = 0x0003,
		/// <summary>
		///   Access is denied.
		/// </summary>
		AccessDenied = 0x0005,
		/// <summary>
		///   The handle is invalid.
		/// </summary>
		InvalidHandle = 0x0006,
		/// <summary>
		///   Not enough storage is available to process this command.
		/// </summary>
		OutOfMemory = 0x0008,
		/// <summary>
		///   The process cannot access the file because it is being used by another process.
		/// </summary>
		SharingViolation = 0x0020,
		/// <summary>
		///   The parameter is incorrect.
		/// </summary>
		InvalidParameter = 0x0057,
		/// <summary>
		///   This function is not supported on this system.
		/// </summary>
		CallNotImplemented = 0x0078,
		/// <summary>
		///   More data is available.
		/// </summary>
		MoreData = 0x00EA,
		/// <summary>
		///   Attempt to access invalid address.
		/// </summary>
		InvalidAddress = 0x01E7,
		/// <summary>
		///   No application is associated with the specified file for this operation.
		/// </summary>
		NoAssociation = 0x0483,
		/// <summary>
		///   An error occurred in sending the command to the application.
		/// </summary>
		DdeFail = 0x0484,
		/// <summary>
		///   One of the library files needed to run this application cannot be found.
		/// </summary>
		DllNotFound = 0x0485,
		/// <summary>
		///   The operation was canceled by the user.
		/// </summary>
		Cancelled = 0x04C7,
		/// <summary>
		///   This operation returned because the time-out period expired.
		/// </summary>
		Timeout = 0x05B4
	}
}


text:
module Dawn
  module Kb
    # Automatically created with rake on 2014-07-04
    class OSVDB_108530
      include DependencyCheck

      def initialize
        message = "kajam Gem for Ruby contains a flaw in /dataset/lib/dataset/database/postgresql.rb that is triggered when handling metacharacters. This may allow a remote attacker to execute arbitrary commands."
        super({
          :name=> "OSVDB-108530",
          :cvss=>"",
          :osvdb=>"108530",
          :release_date => Date.new(2014, 6, 30),
          :cwe=>"",
          :owasp=>"A9",
          :applies=>["rack", "sinatra", "padrino", "rails"],
          :kind=>Dawn::KnowledgeBase::DEPENDENCY_CHECK,
          :message=>message,
          :mitigation=>"We are not currently aware of a solution for this vulnerability. Keep track on kajam gem updates",
          :aux_links=>["http://www.vapid.dhs.org/advisories/kajam-1.0.3.rc2-2nd-vuln.html"]
        })
        self.safe_dependencies = [{:name=>"kajam", :version=>['1.0.3.rc3']}]

      end
    end
  end
end


text:
using Elastic.Clients.Elasticsearch.Fluent;
using Elastic.Clients.Elasticsearch.Serialization;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;

#nullable restore
namespace Elastic.Clients.Elasticsearch;
public sealed partial class NodeShard
{
	[JsonInclude]
	[JsonPropertyName("allocation_id")]
	public Dictionary<string, Elastic.Clients.Elasticsearch.Id>? AllocationId { get; init; }

	[JsonInclude]
	[JsonPropertyName("index")]
	public string Index { get; init; }

	[JsonInclude]
	[JsonPropertyName("node")]
	public string? Node { get; init; }

	[JsonInclude]
	[JsonPropertyName("primary")]
	public bool Primary { get; init; }

	[JsonInclude]
	[JsonPropertyName("recovery_source")]
	public Dictionary<string, Elastic.Clients.Elasticsearch.Id>? RecoverySource { get; init; }

	[JsonInclude]
	[JsonPropertyName("relocating_node")]
	public string? RelocatingNode { get; init; }

	[JsonInclude]
	[JsonPropertyName("shard")]
	public int Shard { get; init; }

	[JsonInclude]
	[JsonPropertyName("state")]
	public Elastic.Clients.Elasticsearch.IndexManagement.ShardRoutingState State { get; init; }

	[JsonInclude]
	[JsonPropertyName("unassigned_info")]
	public Elastic.Clients.Elasticsearch.Cluster.UnassignedInformation? UnassignedInfo { get; init; }
}


text:
class constants
{
public:
    static const char * KExamine;
    static const char * KMapListOption;
    static const char * KMapUntagOption;
    static const char * KMapTagOption;
    static const char * KMapGoMarkedOption;
    static const char * KMapGoTaggedOption;
    static const char * KLookAtHeader;
    static const char * KWhatToInteractWithHeader;
    static const char * KPersonDoesNotExist;
    static const char * KThingDoesNotExist;
    static const char * KPortalDescription;
    static const int KStartingLocationX;
    static const int KStartingLocationY;
    static const int KStartingLocationZ;
    static const char * KStartsGlowing;
    static const char * KStopsGlowing;
    static const int KRoomTickInterval;
    static const int KPersonTickInterval;
};

#endif // CONSTANTS_H


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\models\ProjectNotes */
/* @var $form yii\widgets\ActiveForm */
?>

<?php
$model->typeId = 3;
?>

    <?php $form = ActiveForm::begin(['id' => $model->formName(), 'enableClientValidation'=>false, 'enableAjaxValidation'=>true,

]); ?>
    <?= $form->field($model, 'typeId')->dropDownList( $model->getTypeList(3) ) ?>

    <?= $form->field($model, 'note')->textarea(['rows' => '6', 'maxlength' => 255, 'style' => 'resize:none']) ?>

        <?= Html::submitButton('Create', ['class' => 'btn btn-primary', 'id' => 'create-note']) ?>

    <?php ActiveForm::end(); ?>

<?php
    $this->registerJs(
    '$("#create-note").click(function(){
    var $note = $("#projectassembliesfilesnotes-note").val();
        if($note.length > 0){
             $("#modal-window").modal("hide");
        }

    });'
    );
?>


text:
import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {setProps} from '../../support/jest-helpers';
import {BaseCollapse, Collapse, AltCollapse} from '../../../src/react/collapse';
import {Collapsible} from '../../../src/react/collapsible';

describe('BaseCollapse', () => {
  let subject;

  beforeEach(() => {
    jest.spyOn(Collapsible.prototype, 'render');
    subject = ReactDOM.render((
      <BaseCollapse header="ima header">

Child

      </BaseCollapse>
    ), root);
  });

  it('creates a collapsed panel', () => {
    expect('.pui-collapse-panel-title').toHaveText('ima header');
    expect(Collapsible).toHaveBeenRenderedWithProps(
      jasmine.objectContaining({expanded: false}));
    expect('.pui-collapse-panel-body').toHaveText('Child');
  });

  describe('opening and closing', () => {
    beforeEach(() => {
      $('.pui-collapse-panel-title a').simulate('click');
    });

    it('updates the props of the bsPanel', () => {
      expect(Collapsible).toHaveBeenRenderedWithProps(
        jasmine.objectContaining({expanded: true}));
      $('.pui-collapse-panel-title a').simulate('click');
      expect(Collapsible).toHaveBeenRenderedWithProps(
        jasmine.objectContaining({expanded: false}));
    });
  });

  describe('when the divider property is set to true', () => {
    beforeEach(() => {
      subject::setProps({divider: true});
    });

    it('renders a divider on top of the panel body', () => {
      expect('.pui-collapse').toHaveClass('pui-collapse-divider');
    });
  });

  describe('when the defaultExpanded property is set to true', () => {
    beforeEach(() => {
      ReactDOM.unmountComponentAtNode(root);
      ReactDOM.render((
        <BaseCollapse header="ima header" defaultExpanded={true}>

Child

        </BaseCollapse>
      ), root);
    });

    it('starts out expanded', () => {
      expect(Collapsible).toHaveBeenRenderedWithProps(
        jasmine.objectContaining({expanded: true}));
    });
  });
});

describe('Collapse', () => {
  beforeEach(() => {
    ReactDOM.render(
      <Collapse header="ima header" className="test-class" style={{opacity: 0.5}}>

Child

      </Collapse>,
      root);
  });

  it('passes through className', () => {
    expect('.pui-collapse').toHaveClass('test-class');
  });

  it('passes through style', () => {
    expect('.pui-collapse').toHaveStyle({opacity: 0.5});
  });

  it('contains a right-caret as its collapsed icon when closed', () => {
    expect('svg').toHaveClass('icon-arrow_drop_right');
  });

  it('contains a down-caret as its collapsed icon when open', () => {
    $('.pui-collapse-panel-title svg').simulate('click');
    expect('svg').toHaveClass('icon-arrow_drop_down');
  });
});

describe('AltCollapse', () => {
  beforeEach(() => {
    ReactDOM.render(
      <AltCollapse header="ima header">

Child

      </AltCollapse>
      , root);
  });

  it('contains a right-caret as its collapsed icon when closed', () => {
    expect('svg').toHaveClass('icon-add_circle');
  });

  it('contains a down-caret as its collapsed icon when open', () => {
    $('.pui-collapse-panel-title svg').simulate('click');
    expect('svg').toHaveClass('icon-remove_circle');
  });
});