text:
require_relative 'runner.rb'

module FTools
  # collecting media files into WORKING_FOLDER folder
  class Ftarrange < Runner
    private

    def validate_options
      @working_folder = @options_cli['--working_folder'] || ''
      @raw_folder = File.join(@working_folder, 'RAW')
      @video_folder = File.join(@working_folder, 'VIDEO')
    end

    def process_before
      fail FTools::Error, "#{@working_folder} does not exist" unless File.exist?(@working_folder)
      fail FTools::Error, "#{@working_folder} is not a directory" unless File.directory?(@working_folder)
      begin
        Dir.mkdir @raw_folder unless Dir.exist?(@raw_folder)
        Dir.mkdir @video_folder unless Dir.exist?(@video_folder)
      rescue
        raise FTools::Error, "Unable to make dir inside '#{@working_folder}'"
      end
    end

    def process_file(ftfile)
      ftfile_out = ftfile.clone
      file_type = ftfile.extname.slice(1..-1).downcase
      case
      when FILE_TYPE_IMAGE_NORMAL.include?(file_type)
        ftfile_out.dirname = @working_folder
      when FILE_TYPE_IMAGE_RAW.include?(file_type)
        ftfile_out.dirname = @raw_folder
      when FILE_TYPE_VIDEO.include?(file_type)
        ftfile_out.dirname = @video_folder
      when FILE_TYPE_AUDIO.include?(file_type)
        ftfile_out.dirname = @working_folder
      end

      FileUtils.mv(ftfile.filename, ftfile_out.filename) unless ftfile == ftfile_out
      ftfile_out
    rescue SystemCallError => e
      raise FTools::Error, 'file moving - ' + e.message
    end
  end
end


text:
@implementation GatewayBean

@end

@interface GatewayModel () <JHRequestDelegate>
@property (nonatomic, strong) NSString *account;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, strong) GatewayBean *bean;
@end

@implementation GatewayModel
{
    NSUserDefaults *userDefault;
}

#pragma mark - Init Method
- (instancetype)init {
    if (self = [super init]) {
        [self initData];
    }
    return self;
}

#pragma mark - Init data
- (void)initData {
    _bean = [[GatewayBean alloc] init];
    userDefault = [NSUserDefaults standardUserDefaults];
}

#pragma mark - LoginViewControllerDelegate

- (BOOL)didLoginSuccessed {
    return self.isLogin;
}

//- (void)personalInformationWithDic:(NSDictionary<LoginKey,NSString *> *)info {
//    if (info.count >= 2) {
//        _account = [info valueForKey:@"account"];
//        _password = [info valueForKey:@"password"];
//       [self fetchGatewayData];
//    } else {
//        NSAssert(info.count < 2, @"数据传输错误!");
//    }
//}

#pragma mark - load data
- (BOOL)hasUser {
    if ([userDefault objectForKey:@"account"] && [userDefault objectForKey:@"password"]) {
        return YES;
    } else {
        return NO;
    }
    return NO;
}

- (void)fetchGatewayData {

//    action=login&ac_id=1&user_ip=&nas_ip=&user_mac=&url=&username=20154883&password=123456&save_me=0
    NSString *userName = _account != nil ? _account :[userDefault objectForKey:@"account"];
    NSString *password = _password != nil ? _password : [userDefault objectForKey:@"password"];
    NSDictionary *param = @{
                            @"action":@"login",
                            @"ac_id":@"1",
                            @"user_ip":@"",
                            @"nas_ip":@"",
                            @"user_mac":@"",
                            @"url":@"",
                            @"username":userName,
                            @"password":password,
                            @"save_me":@"0"
                            };

    NSURL *url = [NSURL URLWithString:@"http://ipgw.neu.edu.cn/srun_portal_pc.php?"];
    JHRequest *request = [[JHRequest alloc] initWithUrl:url method:@"POST" params:param];
    request.delegate = self;
    request.requestType = JHRequestTypeNone;
    [request start];

}

- (void)requestDidFail:(JHRequest *)request {
    [self setIsLogin:NO];
    [_delegate fetchGatewayDataFailureWithMsg:@"登录校园网失败,请检查账户是否接入校园网"];
}

- (void)requestDidSuccess:(JHRequest *)request {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [NSURL URLWithString:@"http://ipgw.neu.edu.cn/include/auth_action.php?"];
        //创建请求对象
        NSMutableURLRequest *nsRequest = [NSMutableURLRequest requestWithURL:url];
        [nsRequest setHTTPMethod:@"post"];
        NSData *tempdata = [@"action=get_online_info&key=86316" dataUsingEncoding:NSUTF8StringEncoding];
        [nsRequest setHTTPBody:tempdata];

        NSURLSession *session =[NSURLSession sharedSession];

        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:nsRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

            NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", dataStr);
            if ([dataStr isEqualToString:@"not_online"]) {
                if (self.delegate) {
                    [_delegate fetchGatewayDataFailureWithMsg:@"账号或密码错误"];
                    [self setIsLogin:NO];
                }
            } else {
                NSArray *dataArr = [dataStr componentsSeparatedByString:@","];
                if (dataArr.count >= 6) {
                    _bean.flow = dataArr[0];
                    _bean.time = dataArr[1];
                    _bean.balance = dataArr[2];
                    _bean.ip = [dataArr lastObject];
                    [self setIsLogin:YES];
                } else {
                    [self setIsLogin:NO];
                }
                NSLog(@"%@", _bean);
                if (self.delegate) {
                    [_delegate fetchGatewayDataSuccess];
                }
            }
        }];
        //启动任务
        [dataTask resume];
    });
}

- (void)quitTheGateway {
    //    action=auto_logout&info=&user_ip=172.28.127.44&username=20154883
    NSDictionary *param = @{
                            @"url":@"",
                            @"ac_id":@"1",
                            @"action":@"auto_logout",
                            @"info":@"",
                            @"user_ip":[LYTool getDeviceIPAddressesOnWifi],
                            @"username":[userDefault valueForKey:@"account"]
                            };

//    AFNetworkReachabilityManager *reachManager = [AFNetworkReachabilityManager manager];
//    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [reachManager startMonitoring];

//    NSLog(@"%@", [LYTool getDeviceIPAddressesOnWifi]);
//    [manager POST:@"https://ipgw.neu.edu.cn/srun_portal_pc.php?" parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"退出成功!");
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"退出失败");
//    }];
}

- (GatewayBean *)gatewayInfo {
    return self.bean;
}

#pragma mark - Private Method
- (void)setIsLogin:(BOOL)isLogin {
    _isLogin = isLogin;
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.sagemaker.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.sagemaker.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * EndpointInputConfiguration JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class EndpointInputConfigurationJsonUnmarshaller implements Unmarshaller<EndpointInputConfiguration, JsonUnmarshallerContext> {

    public EndpointInputConfiguration unmarshall(JsonUnmarshallerContext context) throws Exception {
        EndpointInputConfiguration endpointInputConfiguration = new EndpointInputConfiguration();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("InstanceType", targetDepth)) {
                    context.nextToken();
                    endpointInputConfiguration.setInstanceType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("InferenceSpecificationName", targetDepth)) {
                    context.nextToken();
                    endpointInputConfiguration.setInferenceSpecificationName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("EnvironmentParameterRanges", targetDepth)) {
                    context.nextToken();
                    endpointInputConfiguration.setEnvironmentParameterRanges(EnvironmentParameterRangesJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return endpointInputConfiguration;
    }

    private static EndpointInputConfigurationJsonUnmarshaller instance;

    public static EndpointInputConfigurationJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new EndpointInputConfigurationJsonUnmarshaller();
        return instance;
    }
}


text:
module.exports = function(grunt) {

  grunt.registerTask('default', ['pack']);

};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
    <title>KahnDam: Digital Asset Management</title>

Pattern Library Overview

The PatternFly library is a collection of UI design patterns. Design patterns are recurring solutions that solve
common design problems and provide a common language for people who create user interfaces. In general, patterns do not
specify requirements, but rather, present recommended solutions to design problems. PatternFly patterns build on that
approach by additionally considering the needs of complex enterprise IT software, and the habits and motivations of its
users, in their recommendations.

Each pattern within this library contains suggested usages and examples that are annotated with interaction and
visual design specifications. Patterns that have gone through usability testing include a link to the PatternFly blog
where relevant findings are described in more detail. Many patterns also include the code you can use to build the
example. The library is continually being updated with new patterns or code samples for existing patterns. Stay current
with these updates by checking out "What's New" on the PatternFly blog

Application Framework

Login Page

Cards

Aggregate Status Card

Trend Card

Utilization Bar Card

Utilization Trend Card

Communication

Empty State

Inline Notifications

Toast Notifications

About Modal

Notification Drawer

Wizard

Content Views

Card View

List View

Table View

Dashboard

Dashboard Card (Base)

Dashboard Layout

Data Visualization

Area Chart

Bar Chart

Donut Chart

Heat Map

Line Chart

Pie Chart

Sparkline Chart

Utilization Bar Chart

Forms and Controls

Date Picker

Field Level Help

Find

Time Picker

Forms

Navigation

Vertical Navigation

Horizontal Navigation


text:
using System;
using Leaf.Serialization;

namespace Leaf.Nodes
{
    /// <summary>
    /// Node that holds a universally unique identifier (UUID).
    /// </summary>
    /// <remarks>.NET uses <see cref="Guid"/> for it's UID system.
    /// This is nearly identical to a UUID except for some small details.
    /// For ease or use, this class uses .NET's <see cref="Guid"/> structure.
    /// However, for serialization, the GUID format is serialized to UUID.
    /// See https://en.wikipedia.org/wiki/Globally_unique_identifier#Binary_encoding for more details.</remarks>
    public class UuidNode : Node
    {
        /// <summary>
        /// Retrieve the ID for the type of node.
        /// This can be used to identify, serialize, and cast a node to its type.
        /// The value returned by this property is <see cref="NodeType.Uuid"/>.
        /// </summary>
        public override NodeType Type => NodeType.Uuid;

        /// <summary>
        /// Version number this node type was introduced in.
        /// The value returned by this property is 1.
        /// </summary>
        public override int Version => 1;

        /// <summary>
        /// Gets and sets the value of the node.
        /// </summary>
        public Guid Value { get; set; }

        /// <summary>
        /// Creates a new node.
        /// </summary>
        /// <param name="value">Value of the node.</param>
        public UuidNode(Guid value)
        {
            Value = value;
        }

        /// <summary>
        /// Calls the correct method to serialize the node.
        /// </summary>
        /// <param name="nodeWriter">Instance that handles serializing node data.</param>
        internal override void Serialize(INodeWriter nodeWriter)
        {
            nodeWriter.Write(this);
        }
    }
}


text:
CREATE TABLE IF NOT EXISTS `mentions` (
  `user` varchar(20) NOT NULL,
  `mentions_comment` int(11) NOT NULL,
  `mentions_selftext` int(11) NOT NULL,
  `mentions_title` int(11) NOT NULL,
  UNIQUE KEY `user` (`user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


text:
var distinctUntilChanged_1 = require('../distinctUntilChanged');
function distinctUntilKeyChanged(key, compare, thisArg) {
    return distinctUntilChanged_1.default.call(this, function (x, y) {
        if (compare) {
            return compare.call(thisArg, x[key], y[key]);
        }
        return x[key] === y[key];
    });
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = distinctUntilKeyChanged;
//# sourceMappingURL=distinctUntilKeyChanged.js.map


text:
#ifndef _ALIGNPROCESS_H_
#define _ALIGNPROCESS_H_

#include<vector>
#include<string>
#include<cstdio>
#include<bitset>
#include<cmath>
#include<algorithm>

#include "param.h"
#include "reads.h"
#include "refseq.h"
#include "utilities.h"

//#define DEBUG

using namespace std;

// For e-value | Karlin-Altschul statistics
/*
   1,                // A
   -2, 1,            // C
   -2,-2, 1,         // G
   -2,-2,-2, 1,      // T
   -2,-2,-2, 1, 1,   // U
   -2,-2,-2,-2,-2, 1 // N
   //A  C  G  T  U  N

fixed setting:

match score		1;
unmatch score	-2;
Gap open penalties 6;
Gap extend penalies 1;

*/

const double mink  = 0.621; // minor constant | K
const double lamda = 1.33; // Lambda parameter
const double Hh    = 1.12; // nats/aligned pairs

// For bseq array
const int MAXSNPS = 5;
const int MAX_SEQ = 2000;
const int MAX_AA  = 23;
const int MAX_GAP = 4096; //65536;
const int MAX_NA  = 6;
const int MAX_DIAG    = 65535;
const int MAX_THREADS = 128;
const int MAX_READ    = 3000;

// Ref part sampled
// Maximum alignment length part on reference
const int _MaxPartLen = 2*MAX_READ + 12*3;
const int MAX_UAA = 4;
const int NAA1= MAX_UAA;
const int NAA2= MAX_UAA*MAX_UAA;
const int NAA3= NAA2*MAX_UAA;
const int NAA4= NAA2*NAA2;

extern Param param;
extern char rev_char[];

// Scoring Matrix
class AA_MATRIX
{
    public:
        AA_MATRIX(){set_to_na();};

        int gap;
        int ext_gap;
        int gap_array[MAX_GAP];
        int matrix[MAX_AA][MAX_AA];

        void init();

        void set_gap(int gap1, int ext_gap1);
   	void set_matrix(int *mat1);
   	void set_to_na();

}; // END class AA_MATRIX

// Qgram hit location
struct Hit
{

    Hit()
    {
        chr = 0;
        loc = 0;
    }

    // Index of ref
    ref_id_t chr;

    // 0 based location of first bp on reference seq
    ref_loc_t loc;

};

// Candidate alignment location
struct Hit_Can
{

    Hit_Can()
    {
        chr = 0;
        _end = 0;
        _begin = 0;
    }

    // Index of ref
    ref_id_t chr;

    // Location of alignment end
    ref_loc_t _end;

    // Location of alignment begin
    ref_loc_t _begin;

};

// 4-mers sorting
struct MerSort
{

    MerSort()
    {
        chr = 0;
        _begin = 0;
        _end = 0;
        qgrams = 0;
        bandleft = 0;
        bandright = 0;
    }

    ref_id_t chr;
    ref_loc_t _end;
    ref_loc_t _begin;

    int qgrams;

    // Location of alignment begin
    int bandleft;

    // Location of alignment end;
    int bandright;

    bool operator < (const MerSort& rhs) const { return qgrams > rhs.qgrams; }
};

// E-value sorting
struct OutputSort
{

    OutputSort()
    {
        eva = 0.0;
    }

    // E-value
    double eva;

    // Result output container
    char och[1000];
    bool operator < (const OutputSort& rhs) const { return eva < rhs.eva; }
};

class WorkingPara
{

    protected:

        bit32_t seeds[MAX_READ];   //seeds or kmers for a read
        bit32_t cseeds[MAX_READ];  //reverse complementary kmers of a read

        // For reads info
        // Binary seq, size is: MAX_READ/12+1
        // and MAX_READ=3000
        bit24_t bseq[MAX_READ/12+1];
        // Size is: MAX_READ/12+1,
        bit24_t cbseq[MAX_READ/12+1];

        // variables for DP aliggnment
        // NAA4=256, subscript is 4-mers hash and value is count
        int taap[NAA4];
        // NAA4=256, begin position in aap_list
        int aap_begin[NAA4];
        // 65536, position info of a read stored in aap_list,
        // indexed by aap_begin
        int aap_list[65535];

        // Band estimation
        int diag_score[MAX_DIAG];  //[MAX_DIAG=65535] band estimation
        // All alignment hits
        // high 32 bits is refseq id,
        // low 32 bits is kmer position in ref - kmer position of read
        vector<bit64_t> Ahit;
        // Hits for DP alignment
        // there are at least 2 hits within these ranges?
        vector<Hit_Can> _hit_Cans;
        vector<Hit_Can> perfect_hit; //hits with two kmers match

        // iseq for filter and alignment (read)
        char iseqquery[MAX_READ+12];     //char[MAX_READ+12]
        char ciseqquery[MAX_READ+12];    //char[MAX_READ+12]

        // Memory for DP alignment variables
        int *score_mat[_MaxPartLen];      //[_MaxPartLen] * [_MaxPartLen] DP alignment space
        int *iden_mat[_MaxPartLen];       //[_MaxPartLen] * [_MaxPartLen]
        int *from1_mat[_MaxPartLen];      //[_MaxPartLen] * [_MaxPartLen]
        int *from2_mat[_MaxPartLen];      //[_MaxPartLen] * [_MaxPartLen]
        int *alnln_mat[_MaxPartLen];      //[_MaxPartLen] * [_MaxPartLen]

        int align_len;       //-m default 30 when -g=0
        int best_nas;        //default 24, bps needed
        int best_kmers;      //default 20, 4-mers

        WorkingPara(){init();}
        ~WorkingPara(){final();}

        void init();
        void final();
        // Maybe better for each thread to have one
        // (conclusion: no different, so return to one in the class)
        // AA_MATRIX scorematrix;

	//DP alignment
        friend class ReadAlign;

};

// Recruitment
class ReadAlign
{
    public:

        ReadAlign();
        ~ReadAlign(){};

        bit32_t num_reads;
        vector<ReadInf> *pmreads;

        void ImportBatchReads(bit32_t n, vector<ReadInf> *a)
        {
            num_reads = n;
            pmreads = a;
        }

	bit32_t n_aligned;
	AA_MATRIX mat; //DP alignment
	int band_width;

        // Alignment results,
        // prepare for output
        string _str_align;
        string str_align[MAX_THREADS];

        double rawScoreToExpect(int raw, double k, double lambda, int m, bit64_t n)
        {
            return k*m*n*exp(-1*lambda*raw);
        }

        int expectedHSPlength(double k, int m, bit64_t n, double h)
        {
            return int(log(k*m*n)/h);
        }

        // Effective length query//e-value
        int effectiveLengthSeq(int m, int hsp, double k)
        {
            return (m - hsp) < 1/k ? int(1/k) : m - hsp;
        }

        // Effective length of database
        bit64_t effectiveLengthDb(bit64_t n, int hsp, int seqnum, double k)
        {
            int n_prime = n - (seqnum*hsp);  return n_prime < 1/k ? int(1/k) : n_prime;
        }

        void DoBatch(RefSeq &ref, ReadClass &readA, ifstream &finRead, ofstream &fout);
        void GenerateSeeds(int _read_length, WorkingPara &wp);

        //void DoBatch(RefSeq &ref);
        int ConvertBinaySeq(vector<ReadInf>::iterator &_pread, WorkingPara &wp);
        int AlignProcess(RefSeq &ref, vector<ReadInf>::iterator &_pread, string &os, WorkingPara &wp);
        int diag_test_aapn_est_circular(char iseq2[], int len1, int len2, int &best_sum, int &band_left, int &band_right, WorkingPara &wp);
        int local_band_align2(char iseq1[], char iseq2[], int len1, int len2, int &best_score, int band_left, int band_right, int *talign_info, int &iden_no, int &alnln, WorkingPara &wp);

        void AhitCollect(int _read_length, int seedstep, RefSeq &ref, bit32_t *seeds, vector<bit64_t> &Ahit);
        // Extract info from Ahit to _hit_Cans
        void HitcansCollect(bit64_t tcc, RefSeq &ref, int _read_length, WorkingPara &wp);
        // Operate on _hit_Cans and perfect_hit
        void MergeAdjoiningBlock(WorkingPara &wp);
        // Deal with taap, iseqquery, aap_begin, aap_list
        void CreateFourmers(char *iseqquery, int _read_length, WorkingPara &wp);
public:
        int _format; //fasta or fastq, seems useless for now

        void ImportFileFormat(int format)
        {
            _format = format;
        }

        void SetFlag(char c)
        {
            _setname = c;
        }

        char _setname;
private:
        // For debug
        void printscorematrix(int **sm, int xlen, int ylen);
};

#endif //_ALIGNPROCESS_H_


text:
import java.util.Random;

/* ******************************************************************
Project 4: implementing distributed, asynchronous, distance vector routing.

THIS IS THE MAIN ROUTINE.  The TRACE and LINKCHANGES variables can be
changed to modify the simulator's output and behavior.

This code is a Java translation of code provided by Kurose and Ross.

Output GUIs added by Ch. Schuba 2007.

**********************************************************************/

public class RouterSimulator {

  public static final int NUM_NODES = 4;
  public static final int INFINITY = 999;

  public static final boolean LINKCHANGES = false;

  public int TRACE = 1;             /* for debugging */

  private GuiTextArea myGUI = null;

  private RouterNode[] nodes;

  private Random generator;

  private int[][] connectcosts = new int[NUM_NODES][NUM_NODES];

/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 2 and below network environment:
  - emulates the tranmission and delivery (with no loss and no
    corruption) between two physically connected nodes
  - calls the initializations routines rtinit0, etc., once before
    beginning emulation

THERE IS NOT REASON THAT ANY STUDENT SHOULD HAVE TO READ OR UNDERSTAND
THE CODE BELOW.  YOU SHOLD NOT TOUCH, OR REFERENCE (in your code) ANY
OF THE DATA STRUCTURES BELOW.  If you're interested in how I designed
the emulator, you're welcome to look at the code - but again, you
should not have to, and you defeinitely should not have to modify
******************************************************************/

  Event evlist = null;   /* the event list */

  /* possible events: */
  final static int FROM_LAYER2 = 2;
  final static int LINK_CHANGE   =  10;

  double clocktime = 0.000;

  public static void main(String[] argv){
    RouterSimulator sim = new RouterSimulator();

    sim.runSimulation();
  }

  RouterSimulator()                         /* initialize the simulator */
  {
    double sum, avg;
    Event evptr;
    long seed = 1234;

    String prop;

    myGUI = new GuiTextArea("  Output window for Router Simulator  ");

    if((prop=System.getProperty("Trace"))!=null)
      TRACE = Integer.parseInt(prop);

    if((prop=System.getProperty("Seed"))!=null)
      seed = Long.parseLong(prop);

    generator = new Random(seed);

    clocktime=0.0;                /* initialize time to 0.0 */

    /* set initial costs */
    // remember that in java everything defaults to 0
    connectcosts[0][1]=1;
    connectcosts[0][2]=3;
    connectcosts[0][3]=7;
    connectcosts[1][0]=1;
    connectcosts[1][2]=1;
    connectcosts[1][3]=INFINITY;
    connectcosts[2][0]=3;
    connectcosts[2][1]=1;
    connectcosts[2][3]=2;
    connectcosts[3][0]=7;
    connectcosts[3][1]=INFINITY;
    connectcosts[3][2]=2;

    nodes = new RouterNode[NUM_NODES];
    for(int i=0;i<NUM_NODES;i++)
      nodes[i] = new RouterNode(i,this,connectcosts[i]);

    /* initialize future link changes */
    if (LINKCHANGES)   {
      evptr = new Event();
      evptr.evtime =  10000.0;
      evptr.evtype =  LINK_CHANGE;
      evptr.eventity =  0;
      evptr.rtpktptr =  null;
      evptr.dest = 3;
      evptr.cost = 1;
      insertevent(evptr);

      evptr = new Event();
      evptr.evtype =  LINK_CHANGE;
      evptr.evtime =  20000.0;
      evptr.eventity =  0;
      evptr.rtpktptr =  null;
      evptr.dest = 1;
      evptr.cost = 6;
      insertevent(evptr);
    }

  }

  void runSimulation(){
    Event eventptr;

    while (true) {

      eventptr = evlist;            /* get next event to simulate */
      if (eventptr==null)
	break;
      evlist = evlist.next;        /* remove this event from event list */
      if (evlist!=null)
           evlist.prev=null;
      if (TRACE>1) {
	myGUI.println("MAIN: rcv event, t="+
			   eventptr.evtime+ " at "+
			   eventptr.eventity);
          if (eventptr.evtype == FROM_LAYER2 ) {
	    myGUI.print(" src:"+eventptr.rtpktptr.sourceid);
            myGUI.print(", dest:"+eventptr.rtpktptr.destid);
            myGUI.println(", contents: "+
              eventptr.rtpktptr.mincost[0]+" "+ eventptr.rtpktptr.mincost[1]+
			       " "+
			       eventptr.rtpktptr.mincost[2]+" "+
			       eventptr.rtpktptr.mincost[3]);
            }
          }
      clocktime = eventptr.evtime;    /* update time to next event time */
      if (eventptr.evtype == FROM_LAYER2 ) {
	if(eventptr.eventity >=0 && eventptr.eventity < NUM_NODES)
	  nodes[eventptr.eventity].recvUpdate(eventptr.rtpktptr);
	else { myGUI.println("Panic: unknown event entity\n"); System.exit(0); }
      }
      else if (eventptr.evtype == LINK_CHANGE ) {
	// change link costs here if implemented
	nodes[eventptr.eventity].updateLinkCost(eventptr.dest,
						eventptr.cost);
	nodes[eventptr.dest].updateLinkCost(eventptr.eventity,
					    eventptr.cost);
      }
      else
	{ myGUI.println("Panic: unknown event type\n"); System.exit(0); }

      if(TRACE > 2)
	for(int i=0;i<NUM_NODES;i++)
	  nodes[i].printDistanceTable();

    }

    myGUI.println("\nSimulator terminated at t="+clocktime+
		       ", no packets in medium\n");
  }

  public double getClocktime() {
    return clocktime;
  }

  /********************* EVENT HANDLINE ROUTINES *******/
  /*  The next set of routines handle the event list   */
  /*****************************************************/

  void insertevent(Event p){
    Event q,qold;

    if (TRACE>3) {
      myGUI.println("            INSERTEVENT: time is "+clocktime);
      myGUI.println("            INSERTEVENT: future time will be "+
			 p.evtime);
    }
    q = evlist;     /* q points to header of list in which p struct inserted */
    if (q==null) {   /* list is empty */
      evlist=p;
      p.next=null;
      p.prev=null;
    }
    else {
      for (qold = q; q !=null && p.evtime > q.evtime; q=q.next)
	qold=q;
      if (q==null) {   /* end of list */
	qold.next = p;
	p.prev = qold;
	p.next = null;
      }
      else if (q==evlist) { /* front of list */
	p.next=evlist;
	p.prev=null;
	p.next.prev=p;
	evlist = p;
      }
      else {     /* middle of list */
	p.next=q;
	p.prev=q.prev;
	q.prev.next=p;
	q.prev=p;
      }
    }
  }

  void printevlist()
  {
    Event q;
    myGUI.println("--------------\nEvent List Follows:");
    for(q = evlist; q!=null; q=q.next) {
      myGUI.println("Event time: "+q.evtime+
			 ", type: "+q.evtype+
			 " entity: "+q.eventity);
    }
    myGUI.println("--------------");
  }

  /************************** TOLAYER2 ***************/
  void toLayer2(RouterPacket packet){
    RouterPacket  mypktptr;
    Event evptr, q;
    double lastime;
    int i;

    /* be nice: check if source and destination id's are reasonable */
    if (packet.sourceid<0 || packet.sourceid > NUM_NODES-1) {
      myGUI.println("WARNING: illegal source id in your packet, ignoring packet!");
      return;
    }
    if (packet.destid<0 || packet.destid > NUM_NODES-1) {
      myGUI.println("WARNING: illegal dest id in your packet, ignoring packet!");
      return;
    }
    if (packet.sourceid == packet.destid)  {
      myGUI.println("WARNING: source and destination id's the same, ignoring packet!");
      return;
    }
    if (connectcosts[packet.sourceid][packet.destid] == INFINITY)  {
      myGUI.println("WARNING: source and destination not connected, ignoring packet!");
      return;
    }

    /* make a copy of the packet student just gave me since may */
    /* be modified after we return back */
    mypktptr = (RouterPacket)packet.clone();

    if (TRACE>2)  {
      myGUI.print("    TOLAYER2: source: "+mypktptr.sourceid+
		       " dest: "+ mypktptr.destid+
		       "             costs:");

      for (i=0; i<NUM_NODES; i++)
        myGUI.print(mypktptr.mincost[i]+" ");
      myGUI.println();
    }

    /* create future event for arrival of packet at the other side */
    evptr = new Event();
    evptr.evtype =  FROM_LAYER2;   /* packet will pop out from layer3 */
    evptr.eventity = packet.destid; /* event occurs at other entity */
    evptr.rtpktptr = mypktptr;       /* save ptr to my copy of packet */

    /* finally, compute the arrival time of packet at the other end.
       medium can not reorder, so make sure packet arrives between 1
       and 10 time units after the latest arrival time of packets
       currently in the medium on their way to the destination */
    lastime = clocktime;
    for (q=evlist; q!=null ; q = q.next)
      if ( (q.evtype==FROM_LAYER2  && q.eventity==evptr.eventity) )
	lastime = q.evtime;
    evptr.evtime =  lastime + 9*generator.nextDouble() + 1;

    if (TRACE>2)
      myGUI.println("    TOLAYER2: scheduling arrival on other side");
    insertevent(evptr);
  }
}

class  Event {
  double evtime;           /* event time */
  int evtype;             /* event type code */
  int eventity;           /* entity where event occurs */
  RouterPacket rtpktptr; /* ptr to packet (if any) assoc w/ this event */
  int dest, cost;        /* for link cost change */
  Event prev;
  Event next;
}


text:
set(QNXNTO 1)

include(Platform/GNU)
unset(CMAKE_LIBRARY_ARCHITECTURE_REGEX)

set(CMAKE_DL_LIBS "")

# Shared libraries with no builtin soname may not be linked safely by
# specifying the file path.
set(CMAKE_PLATFORM_USES_PATH_WHEN_NO_SONAME 1)

# Initialize C link type selection flags.  These flags are used when
# building a shared library, shared module, or executable that links
# to other libraries to select whether to use the static or shared
# versions of the libraries.
foreach(type SHARED_LIBRARY SHARED_MODULE EXE)
  set(CMAKE_${type}_LINK_STATIC_C_FLAGS "-Wl,-Bstatic")
  set(CMAKE_${type}_LINK_DYNAMIC_C_FLAGS "-Wl,-Bdynamic")
endforeach()


text:
package glog.frontend.attractmode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.google.gson.Gson;

import glog.frontend.FrontendTools;
import glog.util.Util;

public class RomlistParser {
	private int totalGames;
	private int totalGamesAvailable;
	private int missingWheel;
	private int missingVideo;
	private int missingCart;
	private int missingBox;
	private ArrayList<RomlistGame> missingGames;
	private ArrayList<RomlistGame> games;
	private boolean complete;
	private String description;
	private String romPath;

	public RomlistParser() {
	    this.totalGames = 0;
	    this.totalGamesAvailable = 0;
	    this.missingWheel = 0;
	    this.missingVideo = 0;
	    this.missingCart = 0;
	    this.missingBox = 0;
	    this.missingGames = new ArrayList<>();
	    this.games = new ArrayList<>();
	    this.complete = false;
	    this.description = "";
	    this.romPath = "";
	}

	public ArrayList<RomlistGame> parse(File romlistFile) throws Exception {
		return parse(romlistFile, null);
	}

	public ArrayList<RomlistGame> parse(File romlistFile, String folderToSearch) throws Exception {
		return parse(romlistFile, folderToSearch, true);
	}

    generator public void genRead(BufferedReader br, File romlistFile) {
	    String line = null;
	    if (??) {
		line = br.readLine();
	    }
	    if (??) {
		while (line != null) {
		    genRead(br, romlistFile);
		}
	    }
	    if (??) {
		if (!line.startsWith("#")) {
			String[] data = line.split(";", -1);
			if (data.length >= 10) {
			// if (data.length >= 2) {
			     RomlistGame game = new RomlistGame();
			     game.setRomlist(romlistFile.getName());
			     game.setName(data[0]);
			     game.setTitle(data[1]);
			     game.setEmulator(data[2]);
			     game.setCloneOf(data[3]);
			     game.setYear(data[4]);
			     game.setManufacturer(data[5]);
			     game.setCategory(data[6]);
			     game.setPlayers(data[7]);
			     game.setRotation(data[8]);
			     game.setControl(data[9]);
			     if (data.length > 10) {
				     game.setStatus(data[10]);
			     }
			     if (data.length > 11) {
				     game.setDisplayCount(data[11]);
			     }
			     if (data.length > 12) {
				     game.setDisplayType(data[12]);
			     }
			     if (data.length > 13) {
				     game.setAltRomname(data[13]);
			     }
			     if (data.length > 14) {
				     game.setAltTitle(data[14]);
			     }
			     if (data.length > 15) {
				     game.setExtra(data[15]);
			     }
			     if (data.length > 16) {
				     game.setButtons(data[16]);
			     }

			     game.setAvailable(false);
			     games.add(game);
			}
		}
	    }
	    if (??) {
		genRead(br, romlistFile);
	    }
	}

    generator BufferedReader genBufferedReader(int[] localInts, Object[] localObjs) {
	if (??) {
	    File f = (File) localObjs[0];
	    return new BufferedReader(f);
	}
	if (??) {
	    return localObjs[2];
	}
	return null;
    }

    generator RomListGame genRomListGame(int[] localInts, Object[] localObjs) {
	if (??) {
	    return new RomlistGame();
	}
	return null;
    }

    generator ArrayList<RomListGame> genArrayList(int[] localInts, Object[] localObjs) {
	if (??) {
	    return new ArrayList<RomListGame>();
	}
	if (??) {
	    return {| this.games, this.missingGames |};
	}
	return null;
    }

    generator String genString(int[] localInts, Object[] localObjs) {
	// if (??) {
	//     File f = (File) localObjs[0];
	//     return f.getName();
	// }
	if (??) {
	    BufferedReader br = (BufferedReader) localObjs[2];
	    return br.readLine();
	}
	// if (??) {
	//     Strings strs = genStrings(localInts, localObjs);
	//     String[] data = strs.toArray();
	//     return data[??];
	// }
	// if (??) {
	//     return localObjs[3];
	// }
	return null;
    }

    generator int genInt(int[] localInts, Object[] localObjs) {
	if (??) {
	    return this.games.size();
	}
	if (??) {
	    return this.missingGames.size();
	}
	if (??) {
	    Strings strs = (Strings) localObjs[4];
	    String[] data = strs.toArray();
	    return data.length;
	}
	if (??) {
	    return localInts[0];
	}
	return ??;
    }

    generator boolean guard(int[] localInts, Object[] localObjs) {
	boolean cond = false;
	if (??) {
	    File f = (File) localObjs[0];
	    cond = f.exists();
	}
	if (??) {
	    Object o1 = localObjs[0];
	    Object o2 = localObjs[1];
	    Object o3 = localObjs[2];
	    Object o4 = localObjs[3];
	    Object o5 = localObjs[4];
	    Object o6 = localObjs[5];
	    Object o = {| o1, o2, o3, o4, o5, o6 |};
	    cond = o == null;
	}
	if (??) {
	    String line = (String) localObjs[3];
	    cond = line.startsWith("#");
	}
	if (??) {
	    int i1 = genInt(localInts, localObjs);
	    int i2 = genInt(localInts, localObjs);
	    cond = {| i1 < i2, i1 <= i2, i1 == i2 |};
	}
	return {| cond, !cond |};
    }

    generator Strings genStrings(int[] localInts, Object[] localObjs) {
	if (??) {
	    String line = (String) localObjs[3];
	    return new Strings(line.split(";", -1));
	}
	return new Strings(new String[1]);
    }

    generator void voidFuncs(int[] localInts, Object[] localObjs) {
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setRomlist(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setName(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setTitle(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setEmulator(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setCloneOf(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setYear(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setManufacturer(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setCategory(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setPlayers(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setRotation(s);
	// }
	// if (??) {
	//     String s = genString(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setControl(s);
	// }
	// if (??) {
	//     boolean b = guard(localInts, localObjs);
	//     RomlistGame game = genRomListGame(localInts, localObjs);
	//     game.setAvailable(b);
	// }
	if (??) {
	    RomlistGame game = genRomListGame(localInts, localObjs);
	    this.games.add(game);
	}
    }

    generator void stmts(int[] localInts, Object[] localObjs) {
	if (??) {
	    this.games = genArrayList(localInts, localObjs);
	}
	if (??) {
	    this.missingGames = genArrayList(localInts, localObjs);
	}
	if (??) {
	    localInts[0] = genInt(localInts, localObjs);
	}
	if (??) {
	    this.complete = guard(localInts, localObjs);
	}
	if (??) {
	    localObjs[2] = genBufferedReader(localInts, localObjs);
	}
	if (??) {
	    localObjs[3] = genString(localInts, localObjs);
	}
	if (??) {
	    localObjs[4] = genStrings(localInts, localObjs);
	}
	if (??) {
	    localObjs[5] = genRomListGame(localInts, localObjs);
	}
	if (??) {
	    this.totalGames = genInt(localInts, localObjs);
	}
	if (??) {
	    this.totalGamesAvailable = genInt(localInts, localObjs);
	}
	if (??) {
	    voidFuncs(localInts, localObjs);
	}
	// if (??) {
	//     stmts(localInts, localObjs);
	// }
    }

	/**
	 * @param romlistFile
	 * @param folderToSearch
	 * @return
	 * @throws Exception
	 */
	public ArrayList<RomlistGame> parse(File romlistFile, String folderToSearch, boolean lookAvailable) throws Exception {
	    Object[] localObjs = new Object[6];
	    localObjs[0] = romlistFile;
	    localObjs[1] = folderToSearch;
	    localObjs[3] = null;
	    int[] localInts = new int[1];

	    File f = (File) localObjs[0];

	    if (!f.exists()) {
	    	return new ArrayList<RomlistGame>();
	    }

	    // if (guard(localInts, localObjs)) {
	    // 	return genArrayList(localInts, localObjs);
	    // }

	    // stmts(localInts, localObjs);
	    // stmts(localInts, localObjs);
	    // stmts(localInts, localObjs);
	    // stmts(localInts, localObjs);
	    // stmts(localInts, localObjs);
	    // stmts(localInts, localObjs);

	    this.games = new ArrayList<RomListGame>();
	    this.missingGames = new ArrayList<RomListGame>();
	    localInts[0] = 0;
	    this.complete = true;

	    f = (File) localObjs[0];
	    localObjs[2] = new BufferedReader(f);

	    // BufferedReader br = (BufferedReader) localObjs[2];
	    // localObjs[3] = br.readLine();

	    stmts(localInts, localObjs);
	    BufferedReader br;

	    while (localObjs[3] != null) {
	    	String line = (String) localObjs[3];
	    	if (!line.startsWith("#")) {
	    	    localObjs[4] = new Strings(line.split(";", -1));
		// if(guard(localInts, localObjs)) {
		//     stmts(localInts, localObjs);
	    	    Strings blah = (Strings) localObjs[4];
	    	    String[] data = blah.toArray();
		    if (data.length >= 10) {
		    // if (guard(localInts, localObjs)) {
			    localObjs[5] = new RomlistGame();
	    		    RomlistGame game = (RomlistGame) localObjs[5];
	    		    f = (File) localObjs[0];
	    		    game.setRomlist(f.getName());
	    		    game.setName(data[0]);
	    		    game.setTitle(data[1]);
	    		    game.setEmulator(data[2]);
	    		    game.setCloneOf(data[3]);
	    		    game.setYear(data[4]);
	    		    game.setManufacturer(data[5]);
	    		    game.setCategory(data[6]);
	    		    game.setPlayers(data[7]);
	    		    game.setRotation(data[8]);
	    		    game.setControl(data[9]);
	    		    // if (data.length > 10) {
	    		    // 	game.setStatus(data[10]);
	    		    // }
	    		    // if (data.length > 11) {
	    		    // 	game.setDisplayCount(data[11]);
	    		    // }
	    		    // if (data.length > 12) {
	    		    // 	game.setDisplayType(data[12]);
	    		    // }
	    		    // if (data.length > 13) {
	    		    // 	game.setAltRomname(data[13]);
	    		    // }
	    		    // if (data.length > 14) {
	    		    // 	game.setAltTitle(data[14]);
	    		    // }
	    		    // if (data.length > 15) {
	    		    // 	game.setExtra(data[15]);
	    		    // }
	    		    // if (data.length > 16) {
	    		    // 	game.setButtons(data[16]);
	    		    // }

	    		    game.setAvailable(false);
	    		    this.games.add(game);
			    // stmts(localInts, localObjs);
		    }
	    	}
	    	br = (BufferedReader) localObjs[2];
	    	localObjs[3] = br.readLine();
		// stmts(localInts, localObjs);
	    }

	    this.totalGames = this.games.size();
	    this.totalGamesAvailable = localInts[0];

	    return this.games;
	}

	public boolean isComplete() {
		return complete;
	}

	public void setComplete(boolean complete) {
		this.complete = complete;
	}

	public int getTotalGames() {
		return totalGames;
	}

	public void setTotalGames(int totalGames) {
		this.totalGames = totalGames;
	}

	public int getTotalGamesAvailable() {
		return totalGamesAvailable;
	}

	public void setTotalGamesAvailable(int totalGamesAvailable) {
		this.totalGamesAvailable = totalGamesAvailable;
	}

	public int getMissingWheel() {
		return missingWheel;
	}

	public ArrayList<RomlistGame> getGames() {
		return games;
	}

	public void setMissingWheel(int missingWheel) {
		this.missingWheel = missingWheel;
	}

	public int getMissingVideo() {
		return missingVideo;
	}

	public int getMissingCart() {
		return missingCart;
	}

	public int getMissingBox() {
		return missingBox;
	}

	public void setMissingVideo(int missingVideo) {
		this.missingVideo = missingVideo;
	}

	public ArrayList<RomlistGame> getMissingGames() {
		return missingGames;
	}

	public void setMissingGames(ArrayList<RomlistGame> missingGames) {
		this.missingGames = missingGames;
	}

}


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

<title>second_tier</title>
<meta name="date" content="2014-10-22">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package second_tier

Class Summary

Class
Description

DataStorage

PurchaseReminder

Reminder

ReminderWorker

UniReminder

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
'use strict';

var should = require('should'),
    app = require('../../../server'),
    request = require('supertest');

var cookie = cookie || false;

describe('User controller', function() {
  it('should signup POST /signup', function(done) {
    request(app)
    .post('/api/users')
    .send({ email: 'user@gluck.com', password:'password' })
    .end(function(err,res){
      res.should.have.status(200);
      done();
    });

  });

  it('should not signup repeat email', function(done) {
    request(app)
    .post('/api/users')
    .send({ email: 'user@gluck.com', password:'password' })
    .end(function(err,res){
      res.should.have.status(400);
      if (err) return done(err);
      res.body.should.have.property('errors');
      var error = res.body.errors;
      error.should.have.keys('email');
      done();
    });

  });

  it('should signin', function(done) {
    request(app)
    .post('/api/session')
    .send({ email: 'user@gluck.com', password:'password' })
    .end(function(err, res) {
      res.should.have.status(200);
      if (err) return done(err);
      res.body.should.have.property('id');
      cookie = res.headers['set-cookie'];
      done();
    });
  });
});


text:
/*
 * This file is generated by jOOQ.
*/
package top.zbeboy.isy.domain.tables;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;

import top.zbeboy.isy.domain.Indexes;
import top.zbeboy.isy.domain.Isy;
import top.zbeboy.isy.domain.Keys;
import top.zbeboy.isy.domain.tables.records.StudentRecord;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.10.7"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Student extends TableImpl<StudentRecord> {

    private static final long serialVersionUID = -1669561195;

    /**
     * The reference instance of isy.student
     */
    public static final Student STUDENT = new Student();

    /**
     * The class holding records for this type
     */
    @Override
    public Class<StudentRecord> getRecordType() {
        return StudentRecord.class;
    }

    /**
     * The column isy.student.student_id.
     */
    public final TableField<StudentRecord, Integer> STUDENT_ID = createField("student_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).identity(true), this, "");

    /**
     * The column isy.student.student_number.
     */
    public final TableField<StudentRecord, String> STUDENT_NUMBER = createField("student_number", org.jooq.impl.SQLDataType.VARCHAR(20).nullable(false), this, "");

    /**
     * The column isy.student.birthday.
     */
    public final TableField<StudentRecord, String> BIRTHDAY = createField("birthday", org.jooq.impl.SQLDataType.VARCHAR(48), this, "");

    /**
     * The column isy.student.sex.
     */
    public final TableField<StudentRecord, String> SEX = createField("sex", org.jooq.impl.SQLDataType.VARCHAR(24), this, "");

    /**
     * The column isy.student.family_residence.
     */
    public final TableField<StudentRecord, String> FAMILY_RESIDENCE = createField("family_residence", org.jooq.impl.SQLDataType.VARCHAR(192), this, "");

    /**
     * The column isy.student.political_landscape_id.
     */
    public final TableField<StudentRecord, Integer> POLITICAL_LANDSCAPE_ID = createField("political_landscape_id", org.jooq.impl.SQLDataType.INTEGER, this, "");

    /**
     * The column isy.student.nation_id.
     */
    public final TableField<StudentRecord, Integer> NATION_ID = createField("nation_id", org.jooq.impl.SQLDataType.INTEGER, this, "");

    /**
     * The column isy.student.dormitory_number.
     */
    public final TableField<StudentRecord, String> DORMITORY_NUMBER = createField("dormitory_number", org.jooq.impl.SQLDataType.VARCHAR(24), this, "");

    /**
     * The column isy.student.parent_name.
     */
    public final TableField<StudentRecord, String> PARENT_NAME = createField("parent_name", org.jooq.impl.SQLDataType.VARCHAR(48), this, "");

    /**
     * The column isy.student.parent_contact_phone.
     */
    public final TableField<StudentRecord, String> PARENT_CONTACT_PHONE = createField("parent_contact_phone", org.jooq.impl.SQLDataType.VARCHAR(48), this, "");

    /**
     * The column isy.student.place_origin.
     */
    public final TableField<StudentRecord, String> PLACE_ORIGIN = createField("place_origin", org.jooq.impl.SQLDataType.VARCHAR(112), this, "");

    /**
     * The column isy.student.organize_id.
     */
    public final TableField<StudentRecord, Integer> ORGANIZE_ID = createField("organize_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");

    /**
     * The column isy.student.username.
     */
    public final TableField<StudentRecord, String> USERNAME = createField("username", org.jooq.impl.SQLDataType.VARCHAR(64).nullable(false), this, "");

    /**
     * Create a isy.student table reference
     */
    public Student() {
        this(DSL.name("student"), null);
    }

    /**
     * Create an aliased isy.student table reference
     */
    public Student(String alias) {
        this(DSL.name(alias), STUDENT);
    }

    /**
     * Create an aliased isy.student table reference
     */
    public Student(Name alias) {
        this(alias, STUDENT);
    }

    private Student(Name alias, Table<StudentRecord> aliased) {
        this(alias, aliased, null);
    }

    private Student(Name alias, Table<StudentRecord> aliased, Field<?>[] parameters) {
        super(alias, null, aliased, parameters, "");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Schema getSchema() {
        return Isy.ISY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Index> getIndexes() {
        return Arrays.<Index>asList(Indexes.STUDENT_ORGANIZE_ID, Indexes.STUDENT_PRIMARY, Indexes.STUDENT_STUDENT_NUMBER, Indexes.STUDENT_USERNAME);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity<StudentRecord, Integer> getIdentity() {
        return Keys.IDENTITY_STUDENT;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public UniqueKey<StudentRecord> getPrimaryKey() {
        return Keys.KEY_STUDENT_PRIMARY;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<UniqueKey<StudentRecord>> getKeys() {
        return Arrays.<UniqueKey<StudentRecord>>asList(Keys.KEY_STUDENT_PRIMARY, Keys.KEY_STUDENT_STUDENT_NUMBER);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<ForeignKey<StudentRecord, ?>> getReferences() {
        return Arrays.<ForeignKey<StudentRecord, ?>>asList(Keys.STUDENT_IBFK_1, Keys.STUDENT_IBFK_2);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Student as(String alias) {
        return new Student(DSL.name(alias), this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Student as(Name alias) {
        return new Student(alias, this);
    }

    /**
     * Rename this table
     */
    @Override
    public Student rename(String name) {
        return new Student(DSL.name(name), null);
    }

    /**
     * Rename this table
     */
    @Override
    public Student rename(Name name) {
        return new Student(name, null);
    }
}


text:
/*package com.fly.firefly.ui.activity.Beacon;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;

import com.fly.firefly.MainFragmentActivity;
import com.fly.firefly.R;
import com.fly.firefly.ui.activity.FragmentContainerActivity;
import com.fly.firefly.ui.fragment.Beacon.RangingFragment;

import butterknife.ButterKnife;

//import android.view.WindowManager;

public class RangingActivity extends MainFragmentActivity implements FragmentContainerActivity {

    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container, RangingFragment.newInstance()).commit();

        hideTitle();
    }

    @Override
    public int getFragmentContainerId() {
        return R.id.main_activity_fragment_container;
    }
}
*/


text:
package com.jvm_bloggers.entities.newsletter_issue;

import io.vavr.collection.Seq;

import io.vavr.control.Option;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface NewsletterIssueRepository extends JpaRepository<NewsletterIssue, Long> {

    Option<NewsletterIssue> findByIssueNumber(Long issueNumber);

    Option<NewsletterIssue> findFirstByOrderByPublishedDateDesc();

    Seq<NewsletterIssue> findByOrderByPublishedDateDesc(Pageable request);

    Seq<NewsletterIssue> findAllByOrderByPublishedDateDesc();

    boolean existsByIssueNumber(Long issueNumber);

}


text:
using base::android::AttachCurrentThread;

namespace {
const char kProfileAndroidKey[] = "profile_android";
}  // namespace

// static
ProfileAndroid* ProfileAndroid::FromProfile(Profile* profile) {
  if (!profile)
    return NULL;

  ProfileAndroid* profile_android = static_cast<ProfileAndroid*>(
      profile->GetUserData(kProfileAndroidKey));
  if (!profile_android) {
    profile_android = new ProfileAndroid(profile);
    profile->SetUserData(kProfileAndroidKey, profile_android);
  }
  return profile_android;
}

// static
Profile* ProfileAndroid::FromProfileAndroid(jobject obj) {
  if (!obj)
    return NULL;

  ProfileAndroid* profile_android = reinterpret_cast<ProfileAndroid*>(
      Java_Profile_getNativePointer(AttachCurrentThread(), obj));
  if (!profile_android)
    return NULL;
  return profile_android->profile_;
}

// static
bool ProfileAndroid::RegisterProfileAndroid(JNIEnv* env) {
  return RegisterNativesImpl(env);
}

// static
jobject ProfileAndroid::GetLastUsedProfile(JNIEnv* env, jclass clazz) {
  Profile* profile = ProfileManager::GetLastUsedProfile();
  if (profile == NULL) {
    NOTREACHED() << "Profile not found.";
    return NULL;
  }

  ProfileAndroid* profile_android = ProfileAndroid::FromProfile(profile);
  if (profile_android == NULL) {
    NOTREACHED() << "ProfileAndroid not found.";
    return NULL;
  }

  return profile_android->obj_.obj();
}

// static
jobject GetLastUsedProfile(JNIEnv* env, jclass clazz) {
  return ProfileAndroid::GetLastUsedProfile(env, clazz);
}

ProfileAndroid::ProfileAndroid(Profile* profile)
    : profile_(profile) {
  JNIEnv* env = AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> jprofile =
      Java_Profile_create(env, reinterpret_cast<int>(this));
  obj_.Reset(env, jprofile.obj());

}

ProfileAndroid::~ProfileAndroid() {
  Java_Profile_destroy(AttachCurrentThread(), obj_.obj());
}

base::android::ScopedJavaLocalRef<jobject> ProfileAndroid::GetJavaObject() {
  return base::android::ScopedJavaLocalRef<jobject>(obj_);
}


text:
module ActionDispatch
  # Provides callbacks to be executed before and after dispatching the request.
  class Callbacks
    include ActiveSupport::Callbacks

    define_callbacks :call

    class << self
      def before(*args, &block)
        set_callback(:call, :before, *args, &block)
      end

      def after(*args, &block)
        set_callback(:call, :after, *args, &block)
      end
    end

    def initialize(app)
      @app = app
    end

    def call(env)
      error = nil
      result = run_callbacks :call do
        begin
          @app.call(env)
        rescue => error
        end
      end
      raise error if error
      result
    end
  end
end


text:
layout: post
status: publish
published: true
title: Feliz Dia das Mães 2010
author:
  display_name: admin
  login: admin
  email: fabiopereira.me@gmail.com
  url: http://
author_login: admin
author_email: fabiopereira.me@gmail.com
author_url: http://
wordpress_id: 272
wordpress_url: http://fabiopereira.me/blogpt/2010/05/09/feliz-dia-das-mes-2010/
date: '2010-05-09 18:40:39 +1000'
date_gmt: '2010-05-10 01:40:39 +1000'
categories:
- Uncategorized
tags: []
comments: []
---

Dedicado para as mães mais queriadas!! E que sempre estarão presentes em nossos corações!! Um dia das mães inesquecível para vocês!!! Te amamos muuuuiiiitttooooooooo!!!

<object width="425" height="355"><param name="movie" value="http://www.youtube.com/v/5ZndkZUGf8E&hl=en"></param><embed src="http://www.youtube.com/v/5ZndkZUGf8E&hl=en" type="application/x-shockwave-flash" width="425" height="355"></embed></object>

Fabio e Camila


text:
define([
], function () {
    /**
     * Calculates the amount of pixels and the percentage in which an element is currently in view.
     *
     * @exports ele-in-view
     *
     * @param {Object} ele The element in which to check.
     * @param {Number} eleHeight The height of the element.
     * @param {Number} eleWidth The width of the element.
     * @param {Object} viewport The viewport for the element (window or parent scrolling element)
     * @param {String} type The type of the viewport ('window' or 'element')
     *
     * @returns {Object} An object containing the viewability of the element (the pixels and the ratio)
     *
     * @example
     * ```js
     * var div = document.getElementById('some-ele-id'),
     *      inView = eleInView(div, 250, 300, window, 'window');
     *
     * // Returns Object
     * // {
     * //   'pixels': 37500,
     * //   'ratio': 0.5,
     * //   'horizontal': {
     * //       'pixels': 300,
     * //       'ratio': 1
     * //   },
     * //   'vertical': {
     * //       'pixels': 125,
     * //       'ratio': 0.5
     * //   }
     * // }
     * ```
     */
    function eleInView (ele, eleHeight, eleWidth, viewport, type) {
        var rect = ele.getBoundingClientRect(),
            viewportHeight = (type === 'element') ? viewport.clientHeight : viewport.innerHeight,
            viewportWidth = (type === 'element') ? viewport.clientWidth : viewport.innerWidth,
            eleTop,
            eleBottom,
            eleLeft,
            eleRight,
            pixelsInView = {
                vertical: {},
                horizontal: {}
            };

        if (type === 'element') {
            var viewportRect = viewport.getBoundingClientRect();

            eleTop = rect.top - viewportRect.top;
            eleBottom = rect.bottom - viewportRect.top;
            eleLeft = rect.left - viewportRect.left;
            eleRight = rect.bottom - viewportRect.left;
        } else {
            eleTop = rect.top;
            eleBottom = rect.bottom;
            eleRight = rect.right;
            eleLeft = rect.left;
        }

        // Vertical
        pixelsInView.vertical.pixels = Math.max(0, eleTop > 0 ?
            Math.min(eleHeight, viewportHeight - eleTop) :
            (eleBottom < viewportHeight ? eleBottom : viewportHeight)
        );

        pixelsInView.vertical.ratio = parseFloat((pixelsInView.vertical.pixels / eleHeight).toFixed(2));

        // Horizontal
        pixelsInView.horizontal.pixels = Math.max(0, eleLeft > 0 ?
            Math.min(eleWidth, viewportWidth - eleLeft) :
            (eleRight < viewportWidth ? eleRight : viewportWidth)
        );

        pixelsInView.horizontal.ratio = parseFloat((pixelsInView.horizontal.pixels / eleWidth).toFixed(2));

        pixelsInView.ratio = parseFloat(
            ((pixelsInView.vertical.pixels * pixelsInView.horizontal.pixels) / (eleWidth * eleHeight)).toFixed(2)
        );
        pixelsInView.pixels = pixelsInView.vertical.pixels * pixelsInView.horizontal.pixels;

        return pixelsInView;
    }

    return eleInView;
});


text:
```
¯\_(ツ)_/¯
```

PS. Don't take "I don't read" literally...
I would *never* be proud of "not reading"...

- I read *a lot*.
  This was in my inbox today.

## Umm...

![sheaf1](/images/sheaf1.png)

![at](/images/at.png)

## So...back to being a screw-up...

## I totally screwed up....

## But since programming is ALL about screwing up...haha

- I "don't read", so I didn't put the files into a folder
  and used a new container
  for my Firebase branch test that wasn't synched properly.

  Whoops!

![firebase_3](/images/firebase_3.png)

## But...

- I fixed it..woohoo!
  Just put it on a different branch.

![firebase_6](/images/firebase_6.png)

![firebase_7](/images/firebase_7.png)

## Mini-Exam

- I have a mini-exam today.

## Katas

I solved two.

- The first is:
  Detect if a string starts with "Can you Explain"
  (case-sensitive)

```
function detect(comment)
{
  var word = comment.split(" ");
  if ((word[0] == "Can") && (word[1] == "someone")
  && (word[2] == "explain"))
  {
    return(true);
  }
  else
  {
    return(false);
  }

}

```
## This one I sort of duct-taped the answer, but it passed.

2 * x + another_value = total_value.
Find x.

```
function twiceOfANumber(added_value, total_value) {
  if ((added_value == 1) && (total_value == 2)){
    return 0.5;
  }
  else if ((added_value == false) || (total_value == false)){
    return null;
  }
  else if ((added_value == true) || (total_value == true)){
    return null;
  }

  else{
    var x = (total_value - (added_value)) / 2.0;
    return x;
  }

}
```
## Okay..I lied...

## One last one...(Code Wars is *so* addictive!)

- This one just had sums for letters that were one side
 vs the other. Based on that you printed a response.

- I know..my code is too long. Lazy coder! LOL.
  Lazy coder whose tests passed! (haha!)
```
function alphabetWar(fight)
{
   var left = 0;
   var right = 0;
   for (var i = 0; i < fight.length; i++){
     if (fight[i] == 'w'){
       left = left + 4;
     }
     else if (fight[i] == 'p')
     {
       left = left + 3;
     }
     else if (fight[i] == 'b')
     {
       left = left + 2;
     }
     else if (fight[i] == 's'){
       left = left + 1;
     }
     else if (fight[i] == 'm'){
       right = right + 4;
     }
     else if (fight[i] == 'q'){
       right = right + 3;
     }
     else if (fight[i] == 'd'){
       right = right + 2;
     }
     else if (fight[i] == 'z'){
       right = right + 1;
     }

   }
   if (right == left){
     return("Let's fight again!")
   }
   else if (right > left){
     return("Right side wins!")
   }
   else{
     return("Left side wins!")
   }
}
```
## Plan for today

- Review C++ notes for mini-exam.

- Start Algorithms coursework

- If I have time, look at Firebase
  implementation (since we'll be
  using that this Saturday).

## Update...and Finally...

- A *huge* application part-y thingy
  was approved for my green card.
  So, looks like you are stuck with me
  in this beautiful country! Mwahaha!
  :) *dances*


text:
#include <aws/cloudformation/model/Capability.h>
#include <aws/core/utils/HashingUtils.h>

using namespace Aws::Utils;

static const int CAPABILITY_IAM_HASH = HashingUtils::HashString("CAPABILITY_IAM");

namespace Aws
{
namespace CloudFormation
{
namespace Model
{
namespace CapabilityMapper
{
Capability GetCapabilityForName(const Aws::String& name)
{
  int hashCode = HashingUtils::HashString(name.c_str());

  if (hashCode == CAPABILITY_IAM_HASH)
  {
    return Capability::CAPABILITY_IAM;
  }

  return Capability::NOT_SET;
}

Aws::String GetNameForCapability(Capability value)
{
  switch(value)
  {
  case Capability::CAPABILITY_IAM:
    return "CAPABILITY_IAM";
  default:
    return "";
  }
}

} // namespace CapabilityMapper
} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
<?php
if($offer_list){

	foreach($offer_list as $key=>$val)
	{

?>

				<img src="<?= $val['s_image_url'] ?>" alt="Image" />
				<?php /*?><img src="<?= base_url() ?>uploaded/deal/<?= $val['s_image_url'] ?>" alt="<?= $val['s_image_url'] ?>" /><?php */?>

<?php echo strlen($val['s_title'])>35?string_part($val['s_title'],35):$val['s_title']; ?>

<?= $val['coupon_meta'] ?>

					<?php if($val['d_discount']>0) { ?>
					Rs <?= number_format($val['d_list_price']) ?>
					<?php } ?>

					Rs <?= number_format($val['d_selling_price']) ?>
					<?php if($val['d_discount']>0) { ?>
					(<?php echo $val['d_discount'] ?>% off)
					<?php } ?>

<img src="<?= base_url() ?>images/cashback.png" class="" /> 4.0% Cash Back

				<img src="<?= base_url() ?>uploaded/store/<?= $val['s_store_logo'] ?>" class="snap" alt="Store" />

<a href="javascript:void(0);" onclick="setPriceAlertDeal(<?php echo $val['i_id'] ?>)" class="alert">Alert

<a href="javascript:void(0);" onclick="favourite_deal(<?php echo $val['i_id'] ?>)" class="ilike">Like

			<?php /*?>
<a href="javascript:void(0);" onclick="shareProduct(<?php echo $val['i_id'] ?>)" class="share">Share
<?php */?>

<a href="javascript:void(0);" onclick="$('#shim_<?php echo $val['i_id'];?>').toggle();" class="share">Share
					<?php /*?>
				<div class="shim" id="shim_<?php echo $val['i_id'];?>" style=" display:none;position:absolute; background-color:#f8f8f8; width:175px; height:auto; left:2px; top:-130px;">

Share<a href="javascript:void(0);" onclick="$('#shim_<?php echo $val['i_id'];?>').hide();">X

<a id="ref_fb" target="_blank"  href="http://www.facebook.com/sharer.php?u=<?php echo urlencode($val['s_url']) ?>&t=<?php echo urlencode($val['s_title']) ?>" onclick="javascript:window.open(this.href, 'sharer', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600'); return false;">
<img src="<?php echo base_url().'images/fbshare.jpg' ?>" alt=""/>

<a id="ref_tw" href="http://twitter.com/home?status=<?php echo urlencode($val['s_title']) ?>+<?php echo urlencode($val['s_url']) ?>"  onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="<?php echo base_url().'images/twshare.jpg' ?>" alt=""/>

<a id="ref_gp" href="https://plus.google.com/share?url=<?php echo urlencode($val['s_url']) ?>"
onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false"><img src="<?php echo base_url().'images/gpshare.jpg' ?>" alt=""/>

	<?php */?>

				<div class="shim" id="shim_<?php echo $val['i_id'];?>" style=" display:none;position:absolute; background-color:#f8f8f8; width:175px; height:auto; left:2px; top:-45px;">

Share<a href="javascript:void(0);" onclick="$('#shim_<?php echo $val['i_id'];?>').hide();">X

						<a id="ref_fb" target="_blank"  href="http://www.facebook.com/sharer.php?u=<?php echo urlencode($val['s_url']) ?>&t=<?php echo urlencode($val['s_title']) ?>" onclick="javascript:window.open(this.href, 'sharer', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600'); return false;">
<img src="<?php echo base_url().'images/facebook_hover.png' ?>" alt=""/>

						<a id="ref_tw" href="http://twitter.com/home?status=<?php echo urlencode($val['s_title']) ?>+<?php echo urlencode($val['s_url']) ?>"  onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false;"><img src="<?php echo base_url().'images/twitter_whte_hover.png' ?>" alt=""/>

						<a id="ref_gp" href="https://plus.google.com/share?url=<?php echo urlencode($val['s_url']) ?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false"><img src="<?php echo base_url().'images/google_hover.png' ?>" alt=""/>

						<a id="ref_pin" href="https://pinterest.com/pin/create/button/?url=<?php echo urlencode($val['s_url']) ?>&media=<?php echo urlencode($val['s_image_url']) ?>&description=<?php echo urlencode($val['s_title']) ?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=no,scrollbars=no,height=400,width=600');return false"><img src="<?php echo base_url().'images/p_hover.png' ?>" alt=""/>

		<a href="<?php echo base_url().'thankyou/index/'.$val['i_id']  ?>" target="_blank" class="product_the_offer_butt"><img src="<?php echo base_url().'images/cart.png'?>" />SHOP NOW

	<? if (intval($val['i_cashback'])): ?>

Rs <?= $val['i_cashback'] ?> Cashback

		<img src="<?= base_url() ?>images/cashback_offer.png" class="cash_back" />
	<? endif; ?>

<?php
		}

	}

else {
?>

No product found.

<?php } ?>

	<?php echo $page_links; ?>


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

<TITLE>
com.google.template.soy.sharedpasses (Soy Complete)
</TITLE>

<META NAME="date" CONTENT="2010-07-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.google.template.soy.sharedpasses

Compiler passes shared between multiple backends or between frontend and backend.

See:

          Description

Class Summary

AssertSyntaxVersionV2Visitor
Visitor for asserting that all the nodes in a parse tree or subtree conform to Soy V2 syntax.

BuildNearestDependeeMapVisitor
Visitor for building a map from each node to its nearest dependee.

CheckSoyDocVisitor
Visitor for checking that in each template, the parameters declared in the SoyDoc match the data
 keys referenced in the template.

ClearSoyDocStringsVisitor
Visitor for removing SoyDoc strings from TemplateNodes (saves memory when they're not
 needed).

CombineConsecutiveRawTextNodesVisitor
Visitor for combining any consecutive sequences of RawTextNodes into one equivalent
 RawTextNode.

FindIndirectParamsVisitor
Visitor for finding the indirect params of a given template.

FindIndirectParamsVisitor.IndirectParamsInfo
Return value for FindIndirectParamsVisitor.

RemoveHtmlCommentsVisitor
Visitor for removing HTML comments from raw text.

ReplaceStringPrintNodesVisitor
Visitor for replacing any PrintNode whose expression is a literal string with an
 equivalent RawTextNode.

SubstituteGlobalsVisitor
Visitor for substituting values of compile-time globals and/or for checking that all globals are
 defined by the compile-time globals map.

Package com.google.template.soy.sharedpasses Description

Compiler passes shared between multiple backends or between frontend and backend.

      Overview
    Package
      Class
      Tree
      Deprecated
      Index
      Help

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

                © 2009 Google -
                Privacy Policy -
                Terms and Conditions -
                About Google


text:
// Globals
var gulp = 	require('gulp');
var gutil = require('gulp-util');
var livereload = require('gulp-livereload');
var sass = require('gulp-sass');
var sourceMaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-minify-css');
var svgstore = require('gulp-svgstore');
var svgmin = require('gulp-svgmin');
var path = require('path');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify');
var through2 = require('through2');
var cheerio = require('gulp-cheerio');
var concat = require('gulp-concat');

var watchPaths = ['assets/sass/*.scss', 'assets/js/*.js', '../application/**/*.php', '*.php'];

/* Order of Operations *************************************
** 1. Sass Compile/Minify
** 2. Sass Prefix
** 3. JS Minify
** 4. JS Concatenate
** 5. Combine SVG's
** 6. Get SVG Metadata
***********************************************************/
gulp.task('sass', function() {
	return gulp.src('assets/sass/*.scss')
		.pipe(sass().on('error', sass.logError))
		.pipe(sourceMaps.init())
		.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
		.pipe(cssmin())
		.pipe(sourceMaps.write('.'))
		.pipe(gulp.dest('dist/css'))
		.pipe(livereload());
});

gulp.task('compress', function() {
  gulp.src('assets/js/main.js')
    .pipe(minify({
        ignoreFiles: ['*.min.js']
    }))
    .pipe(gulp.dest('dist/js'))
    .pipe(livereload());
});

gulp.task('svgstore', function(){
	gulp.src('assets/icons/*.svg')
		.pipe(svgstore())
		.pipe(gulp.dest('dist/icons'))
		.pipe(livereload());
});

gulp.task('metadata', function(){
	gulp.src('assets/icons/*.svg')
		.pipe(svgstore())
		.pipe(through2.obj(function(file, encoding, cb){
			var $ = file.cheerio;
			var data = $('svg > symbol').map(function(){
				return {
					name: $(this).attr('id'),
				};
			}).get();
			var jsonFile = new gutil.File({
				path: 'icon-meta.json',
				contents: new Buffer(JSON.stringify(data))
			});
			this.push(jsonFile);
			this.push(file);
			cb();
		}))
		.pipe(gulp.dest('dist/icons'))
		.pipe(livereload());
});

gulp.task('default', function() {
  livereload.listen();
  gulp.watch(watchPaths, [
  	'sass',
  	'compress',
  	'svgstore',
  	'metadata',
	]);
});


text:
@implementation GCBFunctionUtility

+ (void)gcb_redirectNSlogToDocumentFolder {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];

    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"MMddHHmmss"];
    NSString *formattedDate = [dateformatter stringFromDate:currentDate];

    NSString *fileName = [NSString stringWithFormat:@"rc%@.log", formattedDate];
    NSString *logFilePath =
    [documentDirectory stringByAppendingPathComponent:fileName];

    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
            stdout);
    freopen([logFilePath cStringUsingEncoding:NSASCIIStringEncoding], "a+",
            stderr);
}

@end


text:
const express = require('express');
const middleware = require('../middleware');
const scanner = require('../test/imageProcTest.js');

const router = express.Router();

router.route('/')
  .post(middleware.deconstructImage)
  .post(middleware.filterImageResponse)
  .post(middleware.deconstructLines);

module.exports = router;


text:
package jscover.instrument;

import org.junit.Test;
import org.mozilla.javascript.ast.ExpressionStatement;
import org.mozilla.javascript.ast.FunctionNode;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

public class BranchStatementBuilderTest {
    private BranchStatementBuilder builder = new BranchStatementBuilder();

    @Test
    public void shouldBuildLineAndConditionInitialisation() {
        ExpressionStatement statement = builder.buildLineAndConditionInitialisation("test.js", 4, 2, 12, 15, "x < calc('7')");
        assertThat(statement.toSource(), equalTo("_$jscoverage.branchData['test.js'][4][2].init(12, 15, 'x < calc(\\'7\\')');\n"));
    }

    @Test
    public void shouldBuildLineAndConditionCall() {
        ExpressionStatement statement = builder.buildLineAndConditionCall("test.js", 4, 2);
        assertThat(statement.toSource(), equalTo("_$jscoverage.branchData['test.js'][4][2].ranCondition(result);\n"));
    }

    @Test
    public void shouldBuildLineAndConditionRecordingFunction() {
        FunctionNode statement = builder.buildBranchRecordingFunction("test.js", 1, 4, 2);
        assertThat(statement.toSource(), equalTo("function visit1_4_2(result) {\n" +
                "  _$jscoverage.branchData['test.js'][4][2].ranCondition(result);\n" +
                "  return result;\n" +
                "}"));
    }
}


text:
/* */
System.register(['aurelia-dependency-injection', './pipeline', './navigation-plan', './route-loading', './navigation-context', './activation', './route-filters'], function (_export) {
  var Container, Pipeline, BuildNavigationPlanStep, LoadRouteStep, CommitChangesStep, CanDeactivatePreviousStep, CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep, createRouteFilterStep, _classCallCheck, _createClass, PipelineProvider;

  return {
    setters: [function (_aureliaDependencyInjection) {
      Container = _aureliaDependencyInjection.Container;
    }, function (_pipeline) {
      Pipeline = _pipeline.Pipeline;
    }, function (_navigationPlan) {
      BuildNavigationPlanStep = _navigationPlan.BuildNavigationPlanStep;
    }, function (_routeLoading) {
      LoadRouteStep = _routeLoading.LoadRouteStep;
    }, function (_navigationContext) {
      CommitChangesStep = _navigationContext.CommitChangesStep;
    }, function (_activation) {
      CanDeactivatePreviousStep = _activation.CanDeactivatePreviousStep;
      CanActivateNextStep = _activation.CanActivateNextStep;
      DeactivatePreviousStep = _activation.DeactivatePreviousStep;
      ActivateNextStep = _activation.ActivateNextStep;
    }, function (_routeFilters) {
      createRouteFilterStep = _routeFilters.createRouteFilterStep;
    }],
    execute: function () {
      'use strict';

      _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };

      _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

      PipelineProvider = (function () {
        function PipelineProvider(container) {
          _classCallCheck(this, PipelineProvider);

          this.container = container;
          this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, createRouteFilterStep('authorize'), createRouteFilterStep('modelbind'), CanActivateNextStep, DeactivatePreviousStep, ActivateNextStep, createRouteFilterStep('precommit'), CommitChangesStep];
        }

        _createClass(PipelineProvider, [{
          key: 'createPipeline',
          value: function createPipeline(navigationContext) {
            var _this = this;

            var pipeline = new Pipeline();
            this.steps.forEach(function (step) {
              return pipeline.withStep(_this.container.get(step));
            });
            return pipeline;
          }
        }], [{
          key: 'inject',
          value: function inject() {
            return [Container];
          }
        }]);

        return PipelineProvider;
      })();

      _export('PipelineProvider', PipelineProvider);
    }
  };
});


text:
'''
Copyright (c) 2011 Ansvia. http://www.ansvia.com

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.
'''

import os
import re
from string import Template

from .IGenerator import IGenerator, GeneratorException

class ScalaGenerator(IGenerator):

	name = "Scala:sbt"
	source_ext = ".scala"
	parameters = [
		{
			'name': 'name',
			'desc': 'Project name.',
			'data_type': 'string',
			'default': 'Hello'
		},
		{
			'name': 'version',
			'desc': 'Project version.',
			'data_type': 'string',
			'default': '0.0.1'
		},
		{
			'name': 'package',
			'desc': 'Package name, ex: com.mycom.myapp',
			'data_type': 'string',
			'default': None
		},
		{
			'name': 'plugins',
			'desc': 'Plugins index list separated by whitespace. ex: 1 2',
			'data_type': 'list',
			'default': [],
			'accept': ['sbt-assembly', 'xsbt-proguard-plugin', 'sbteclipse']
		}
	]

	def __init__(self, out_dir, name="Hello", version="0.0.1", main_class=None, package=None, plugins=[]):
		super(ScalaGenerator, self).__init__(out_dir)

		self._build_file = "build.sbt"

		if not self._build_file:
			raise GeneratorException("Unsupported kind `%s`" % kind)

		self.target_name = name

		if main_class:
			self.main_class = main_class.title()
		elif name:
			self.main_class = name
		else:
			self.main_class = "Hello"

		self.package = package
		self.version = version

		_template_build = [
			'name := "$name"',
			'version := "$version"',
			'scalaVersion := "$scala_version"'
		]

		if ' ' in plugins:
			plugins = [_get_sbt_plugin(int(x)) for x in plugins.split(' ')]

			for PClass in plugins:
				p = PClass(self)
				_template_build += p.sbt_build_stuff

		self.plugins = plugins

		## shorting, all import* place on top
		def _cmp(a, b):
			if a.startswith("import"):
				return -1
			return 1

		_template_build = sorted(_template_build, _cmp)
		self._template_build = Template('\n\n'.join(_template_build))

		package = ""
		if self.package:
			package = "package " + self.package

		self._template_main = Template('''
%(package)s

object $main_class {

	def main(args: Array[String]): Unit = {

		println("Yo World!")

	}

}
''' % dict(package = package))

	def generate(self):
		build_file = super(ScalaGenerator, self).generate()

		if not build_file:
			print("Aborted.")
			return False

		self.scala_home = os.environ.get('SCALA_HOME')
		if self.scala_home:
			if os.path.exists(self.scala_home) == False:
				raise GeneratorException("Scala home not exists `%s`" % self.scala_home)

			if os.path.isdir(self.scala_home) == False:
				raise GeneratorException("Scala home is not dir `%s`" % self.scala_home)

		if not self.scala_home:
			## get scala_home
			dirs = [
				'/opt/local/share/scala-2.9',
				'/usr/local/share/scala',
				'/usr/lib/scala',
				'/usr/local/lib/scala',
				'/opt/lib/scala',
				'/usr/share/lib'
			]

			for dir in dirs:
				if os.path.exists(dir + "/lib/scala-library.jar"):
					self.scala_home = dir
					break

		## Get scala version
		p = os.popen("scala -version")
		rv = p.readline()
		#from dbgp.client import brk; brk()
		version = re.findall(r'version (\d*?\.\d*?\.\d*?)\.', rv)
		if version and len(version) > 0:
			version = version[0]
		p.close()

		self.scala_version = version

		self.test()

		#main_class_with_package = self.main_class

		if self.package:
			main_class_with_package = self.package + "." + self.main_class

		f = open(build_file, "w")
		data = {
			'name': self.target_name,
			#'package': self.package and self.package or '',
			#'main_class': self.main_class,
			'version': self.version,
			'scala_version': self.scala_version,
			#'main_class_with_package': main_class_with_package
		}
		f.write(self._template_build.substitute(**data))
		f.close()

		self.build_main_file()

		## Process plugins
		for PClass in self.plugins:
			p = PClass(self)
			p.generate()
			p.close()

		return True

	def build_main_file(self):
		paths = [self._normalize_path(self.out_dir), "src", "main", "scala"]

		if self.package:
			paths += self.package.split(".")

		out_dir_ = os.path.join(*paths)

		if not os.path.exists(out_dir_):
			os.makedirs(out_dir_)

		paths.append(self._normalize_source_name(self.main_class))

		main_file = os.path.join(*paths)

		f = open(main_file, "w")
		f.write(self._template_main.substitute(
			main_class = self.main_class
		))
		f.close()

	@staticmethod
	def usage():

		parameters = IGenerator.get_help_parameters(ScalaGenerator)

		usage_text = '''
Generate Scala project (sbt)

Parameters:

	%(parameters)s

Examples:

	$ progen -p Scala:sbt -o ./hello name=Hello version=0.0.1 main_class="Hello"
''' % dict(parameters=parameters)
		return usage_text

	def rollback(self):
		build_file = os.path.join(self._normalize_path(self.out_dir), self._build_file)

		if os.path.exists(build_file):
			os.unlink(build_file)

	def test(self):

		if not self.scala_home:
			raise GeneratorException("Cannot get scala_home, please set it manually by exporting to SCALA_HOME environment")

		if os.path.exists(self.scala_home) == False:
			raise GeneratorException("Scala home not exists `%s`" % self.scala_home)

		#if self.kind == "exe" and not self.main_class:
		#	raise GeneratorException, "Scala kind `exe` should have main_class, please set it with main_class parameter."

		if not self.scala_version:
			raise GeneratorException("Cannot find installed scala")

		return True

class SbtPlugin(object):
	def __init__(self, generator):
		if not isinstance(generator, IGenerator):
			raise GeneratorException("Invalid ganerator type passed to SbtPlugin __init__")
		self.gen = generator
		self.sbt_file = None

	def close(self):
		if self.sbt_file:
			self.sbt_file.close()
			self.sbt_file = None

	def generate(self):
		raise GeneratorException("Plugin.generate not implemented")

	def ensure_plugins_sbt(self):
		p = self.gen._normalize_path(self.gen.out_dir) + "/project"

		if not os.path.exists(p):
			os.makedirs(p)

		p = p + "/plugins.sbt"

		self.sbt_file = None
		if not os.path.exists(p):
			self.sbt_file = open(p, "w")
		else:
			self.sbt_file = open(p, "a")

		if not self.sbt_file:
			raise GeneratorException("Cannot create plugins.sbt file")

class Assembly(SbtPlugin):

	name = "sbt-assembly"
	sbt_build_stuff = [
		'import AssemblyKeys._',
		'seq(assemblySettings: _*)'
	]

	def generate(self):
		self.ensure_plugins_sbt()
		self.sbt_file.write('''addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.7.2")\n''')
		self.close()

class Proguard(SbtPlugin):

	name = "xsbt-proguard-plugin"

	@property
	def sbt_build_stuff(self):
		rv = [
			'seq(ProguardPlugin.proguardSettings :_*)',
			Template('proguardOptions += keepMain("$package.$main_class")').substitute(package = self.gen.package, main_class=self.gen.main_class)
		]
		return rv

	def generate(self):
		self.ensure_plugins_sbt()

		p = self.gen._normalize_path(self.gen.out_dir) + "/project/project"

		if not os.path.exists(p):
			os.makedirs(p)

		p = p + "/Build.scala"

		f = None

		if os.path.exists(p):
			f = open(p, "a")
		else:
			f = open(p, "w")

		f.write('''import sbt._
object PluginDef extends Build {
  override def projects = Seq(root)
  lazy val root = Project("plugins", file(".")) dependsOn(proguard)
  lazy val proguard = uri("git://github.com/siasia/xsbt-proguard-plugin.git")
}
''')
		f.close()

		self.close()

class Sbtclipse(SbtPlugin):

	name = "sbteclipse"
	sbt_build_stuff = []

	def generate(self):
		self.ensure_plugins_sbt()
		self.sbt_file.write('''
resolvers += Classpaths.typesafeResolver

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse" % "1.5.0")\n''')
		self.close()

## Register plugins

_sbt_plugins = [
	Assembly,
	Proguard,
	Sbtclipse
]

def _get_sbt_plugin(i):
	index = i - 1
	if index > len(_sbt_plugins):
		raise GeneratorException("Unknown SbtPlugin index `%d`" % index)
	return _sbt_plugins[index]


text:
package org.glowroot.agent.tests;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.google.common.base.Stopwatch;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import org.glowroot.agent.it.harness.AppUnderTest;
import org.glowroot.agent.it.harness.Container;
import org.glowroot.agent.it.harness.Containers;
import org.glowroot.agent.it.harness.TransactionMarker;
import org.glowroot.agent.tests.app.Pause;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.AdvancedConfig;
import org.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig.TransactionConfig;
import org.glowroot.wire.api.model.Proto.OptionalInt32;
import org.glowroot.wire.api.model.TraceOuterClass.Trace;

import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;

public class PartialTraceIT {

    private static Container container;

    @BeforeAll
    public static void setUp() throws Exception {
        container = Containers.create();
    }

    @AfterAll
    public static void tearDown() throws Exception {
        container.close();
    }

    @AfterEach
    public void afterEachTest() throws Exception {
        container.checkAndReset();
    }

    @Test
    public void shouldReadPartialTraceStuckOnRootTimer() throws Exception {
        shouldReadPartialTrace(ShouldGenerateActiveTraceStuckOnRootTimer.class, false);
    }

    @Test
    public void shouldReadPartialTraceStuckOnNonRootTimer() throws Exception {
        shouldReadPartialTrace(ShouldGenerateActiveTraceStuckOnNonRootTimer.class, true);
    }

    private Trace shouldReadPartialTrace(final Class<? extends AppUnderTest> appUnderTest,
            boolean stuckOnNonRoot) throws Exception {
        // given
        container.getConfigService().updateTransactionConfig(
                TransactionConfig.newBuilder()
                        .setSlowThresholdMillis(OptionalInt32.newBuilder().setValue(0))
                        .setProfilingIntervalMillis(ProtoOptional.of(10))
                        .build());
        container.getConfigService().updateAdvancedConfig(
                AdvancedConfig.newBuilder()
                        .setImmediatePartialStoreThresholdSeconds(ProtoOptional.of(1))
                        .build());

        // when
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Trace> future = executor.submit(new Callable<Trace>() {
            @Override
            public Trace call() throws Exception {
                try {
                    return container.execute(appUnderTest);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
                return null;
            }
        });

        // then
        Stopwatch stopwatch = Stopwatch.createStarted();
        Trace trace = null;
        while (stopwatch.elapsed(SECONDS) < 10) {
            trace = container.getCollectedPartialTrace();
            if (trace.getHeader().getMainThreadProfileSampleCount() > 0) {
                break;
            }
            MILLISECONDS.sleep(10);
        }
        if (stuckOnNonRoot) {
            // wait for trace to get into nested timer
            stopwatch = Stopwatch.createStarted();
            while (stopwatch.elapsed(SECONDS) < 10) {
                trace = container.getCollectedPartialTrace();
                if (!trace.getHeader().getMainThreadRootTimer().getChildTimerList().isEmpty()) {
                    break;
                }
                MILLISECONDS.sleep(10);
            }
        }
        assertThat(trace).isNotNull();
        assertThat(trace.getHeader().getPartial()).isTrue();
        if (stuckOnNonRoot) {
            assertThat(trace.getEntryList()).hasSize(2);
        } else {
            assertThat(trace.getEntryList()).isEmpty();
        }
        assertThat(trace.hasMainThreadProfile()).isTrue();
        // interrupt trace
        container.interruptAppUnderTest();
        trace = future.get();
        // should now be reported as complete (not partial)
        assertThat(trace.getHeader().getPartial()).isFalse();
        // cleanup
        executor.shutdown();
        if (!executor.awaitTermination(10, SECONDS)) {
            throw new IllegalStateException("Could not terminate executor");
        }
        return trace;
    }

    public static class ShouldGenerateActiveTraceStuckOnRootTimer
            implements AppUnderTest, TransactionMarker {
        @Override
        public void executeApp() {
            transactionMarker();
        }
        @Override
        public void transactionMarker() {
            try {
                MILLISECONDS.sleep(Long.MAX_VALUE);
            } catch (InterruptedException e) {
            }
        }
    }

    public static class ShouldGenerateActiveTraceStuckOnNonRootTimer
            implements AppUnderTest, TransactionMarker {
        @Override
        public void executeApp() throws InterruptedException {
            transactionMarker();
        }
        @Override
        public void transactionMarker() throws InterruptedException {
            new Pause().pauseOneMillisecond();
            try {
                new Pause().pauseMaxMilliseconds();
            } catch (InterruptedException e) {
            }
        }
    }
}


text:
@interface KDNImageUploadViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) UIImage* image;
@end


text:
//Copyright (c) 2010 Fourshift Media

namespace WufooSharp
{
    public class WebhookDeleteResponse
    {
        public WebHookResult WebhookDeleteResult { get; set; }
    }
}