text:
package bookshop2.supplier.management.bookOrdersManager;

import static javax.ejb.ConcurrencyManagementType.BEAN;
import static javax.ejb.TransactionAttributeType.REQUIRED;
import static javax.ejb.TransactionManagementType.CONTAINER;

import java.util.List;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;
import javax.inject.Inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aries.Assert;
import org.aries.message.Message;
import org.aries.message.MessageInterceptor;

import bookshop2.Order;
import bookshop2.OrderCriteria;

@Stateful
@LocalBean
@ConcurrencyManagement(BEAN)
@TransactionManagement(CONTAINER)
public class BookOrdersManagerInterceptor extends MessageInterceptor<BookOrdersManager> {

	private static final Log log = LogFactory.getLog(BookOrdersManagerInterceptor.class);

	@Inject
	protected BookOrdersManagerHandler bookOrdersManagerHandler;

	@TransactionAttribute(REQUIRED)
	public Message getAllBookOrders(Message message) {
		try {
			List<Order> bookOrders = bookOrdersManagerHandler.getAllBookOrders();
			Assert.notNull(bookOrders, "BookOrders must exist");
			message.addPart("bookOrders", bookOrders);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message getFromBookOrdersById(Message message) {
		try {
			Long orderId = message.getPart("orderId");
			Order bookOrders = bookOrdersManagerHandler.getFromBookOrders(orderId);
			Assert.notNull(bookOrders, "BookOrders must exist");
			message.addPart("bookOrders", bookOrders);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message getFromBookOrdersByIds(Message message) {
		try {
			List<Long> orderIds = message.getPart("orderIds");
			List<Order> bookOrders = bookOrdersManagerHandler.getFromBookOrders(orderIds);
			Assert.notNull(bookOrders, "BookOrders must exist");
			message.addPart("bookOrders", bookOrders);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message getFromBookOrdersByCriteria(Message message) {
		try {
			OrderCriteria orderCriteria = message.getPart("orderCriteria");
			List<Order> bookOrders = bookOrdersManagerHandler.getFromBookOrders(orderCriteria);
			Assert.notNull(bookOrders, "BookOrders must exist");
			message.addPart("bookOrders", bookOrders);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message getMatchingBookOrders(Message message) {
		try {
			List<Order> orderList = message.getPart("orderList");
			List<Order> bookOrders = bookOrdersManagerHandler.getMatchingBookOrders(orderList);
			Assert.notNull(bookOrders, "BookOrders must exist");
			message.addPart("bookOrders", bookOrders);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message addToBookOrders(Message message) {
		try {
			Order order = message.getPart("order");
			Long orderId = bookOrdersManagerHandler.addToBookOrders(order);
			Assert.notNull(orderId, "OrderId must exist");
			message.addPart("orderId", orderId);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message addToBookOrdersAsList(Message message) {
		try {
			List<Order> orderList = message.getPart("orderList");
			List<Long> orderIds = bookOrdersManagerHandler.addToBookOrders(orderList);
			Assert.notNull(orderIds, "OrderIds must exist");
			message.addPart("orderIds", orderIds);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message removeAllBookOrders(Message message) {
		try {
			bookOrdersManagerHandler.removeAllBookOrders();

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message removeFromBookOrders(Message message) {
		try {
			Order order = message.getPart("order");
			bookOrdersManagerHandler.removeFromBookOrders(order);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message removeFromBookOrdersById(Message message) {
		try {
			Long orderId = message.getPart("orderId");
			bookOrdersManagerHandler.removeFromBookOrders(orderId);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message removeFromBookOrdersAsList(Message message) {
		try {
			List<Order> orderList = message.getPart("orderList");
			bookOrdersManagerHandler.removeFromBookOrders(orderList);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

	@TransactionAttribute(REQUIRED)
	public Message removeFromBookOrdersByCriteria(Message message) {
		try {
			OrderCriteria orderCriteria = message.getPart("orderCriteria");
			bookOrdersManagerHandler.removeFromBookOrders(orderCriteria);

		} catch (Throwable e) {
			log.error(e);
			//send error to event queue
			//forward message to invalid queue
			message.addPart("exception", e);
		}

		return message;
	}

}


text:
<?php
  class Event extends CI_Model
  {
    //gamitan ng algo sa susunod
    // wag gawin ng basta basta. keep the algo simple and easy to maintain and read
    // plan return values and formats before doing dev and architecture (implementation)
    // tagalugin na parang UP
    /*
      Ilagay ang table names sa mga variables para madaling ibahin
      I check kung tama ang database
      Ayusin ko lang
    */
    private $table_name = "Scheduler_Event";
    function __construct()
    {
      parent::__construct();
      $this->load->library('email');
    }

    function get_event_by_month($email,$date)
    {
      $result = $this->db->distinct()->like('date',$date)->get_where($this->table_name,array("email" => $email));

      //die();
      $events = array();

      if($result->num_rows() > 0)
      {
        foreach($result->result() as $row)
        {
          //$events_by_day = $this->db->select("eid, name")->where("date",$row->date)->get($this->table_name,array("email"=>$email));
          $key = intval(substr($row->date,8,2));
          $events[$key] = '
';
          //$key = $day."";
        }
        foreach($result->result() as $row)
        {
          //$events_by_day = $this->db->select("eid, name")->where("date",$row->date)->get($this->table_name,array("email"=>$email));
          $key = intval(substr($row->date,8,2));
          $events[$key] = $events[$key]."
eid."'>".$row->name."
";
          //$key = $day."";
        }
        foreach($result->result() as $row)
        {
          //$events_by_day = $this->db->select("eid, name")->where("date",$row->date)->get($this->table_name,array("email"=>$email));
          $events[$key] = $events[$key]."
";
          //$key = $day."";
        }

        $output["events"] = $events;
        $output["success"] = TRUE;
      }
      else
      {
        $output["events"] = NULL;
        $output["success"] = FALSE;
      }
      return $output;
    }

    function get_event_images($id)
    {
      $img_ids = $this->db->get_where("Scheduler_Event_Has",array("eid"=>$id));
      $thumbs = array();
      if($img_ids->num_rows() > 0)
      {
        foreach($img_ids->result() as $img_id)
        {
          $img_info = $this->db->select("file_name,thumb_name")->get_where("Scheduler_File",array("file_id" => $img_id->file_id));

          if($img_info->num_rows() >0)
          {
            $thumbs[$img_id->file_id] = array(
              "thumb_name" => $img_info->result()[0]->thumb_name,
              "file_name" => $img_info->result()[0]->file_name,
            );
          }
        }
        return $thumbs;
      }
      else
      {
        return NULL;
      }

    }

    /*
      Get users with events today
    */
    function get_users_with_events($date)
    {
      $users_with_events = $this->db->select("email")->distinct("email")->where("date",$date)->get($this->table_name);
      if($users_with_events->num_rows() > 0)
      {
        return $users_with_events->result();
      }
      else
      {
        return NULL;
      }
    }

    /*
      Get events by user on given date $params = array ("email" and "date")
    */
    function get_user_events_on($email, $date)
    {
      $params = array(
        "email" => $email,
        "date" => $date,
      );
      $user_events = $this->db->select("name")->get_where($this->table_name,$params);

      if($user_events->num_rows() > 0)
      {

        return $user_events->result();
      }
      else
      {
        return NULL;
      }
    }

    function get_event($id)
    {
      $result = $this->db->select("eid, name, description, date")->where("eid",$id)->get($this->table_name);
      if($result->num_rows())
      {
        return $result->result();
      }
      else
      {
        return NULL;
      }
    }

    function add_event_to_db($data)
    {
      $added = $this->db->insert($this->table_name,$data);
      if($added)
      {
        return $this->db->insert_id();
      }
      else
      {
        return NULL;
      }
    }

    function edit_event_details($id, $updated_details)
    {
          $result = $this->db->where("eid",$id)->update($this->table_name,$updated_details);
          return $result;
    }

    function delete_event($id)
    {
      $this->load->helper("file");
      $files = $this->db->select("file_id")->get_where("Scheduler_Event_Has", array("eid" => $id));
      $deleted_assoc = $this->db->where("eid", $id)->delete("Scheduler_Event_Has");
      $output = array();
      if($deleted_assoc)
      {
        $deleted_events = $this->db->where("eid",$id)->delete($this->table_name);
        if($deleted_events)
        {
          foreach($files->result() as $file)
          {
            $curr_file = $this->db->select("*")->get_where("Scheduler_File",array("file_id" => $file->file_id))->result();
            $orig_file = $this->config->item("UPLOADS")."/".$curr_file[0]->file_name;
            $thumb = $this->config->item("UPLOADS")."/".$curr_file[0]->thumb_name;

            if(unlink($orig_file))
            {
              if(unlink($thumb))
              {
                $deleted_file = $this->db->where("file_id", $file->file_id)->delete("Scheduler_File");
                if($deleted_file)
                {
                  $output["message"] = "Deletion successful";
                  $output["success"] = TRUE;
                }
                else
                {
                  $output["message"] = "File not deleted";
                  $output["success"] = FALSE;
                  return $output;
                }

              }
              else
              {
                $output["message"] = "Thumbnail was not deleted";
                $output["success"] = FALSE;
                return $output;
              }
            }
            else
            {
              $output["message"] = "Original file was not deleted";
              $output["success"] = FALSE;
              return $output;
            }
          }
        }
        else
        {
          $output["message"] = "Event not deleted";
          $output["success"] = FALSE;
          return $ouput;
        }
      }
      else
      {
        $output["message"] = "Assocs not deleted";
        $output["success"] = FALSE;
        return $output;
      }

    }

    function search_event($term)
    {
      $desc_matches = $this->db->like("description",$term)->get_where($this->table_name,array("email" => $this->session->email));
      $name_matches = $this->db->like("name",$term)->get_where($this->table_name,array("email" => $this->session->email));
      $result = array();
      if($desc_matches->num_rows() > 0)
      {
        $result["desc"] = $desc_matches->result();
      }
      if($name_matches->num_rows() > 0)
      {
        $result["name"] = $name_matches->result();
      }
      if(empty($result))
      {
        return NULL;
      }
      else {
        return $result;
      }
    }

    function add_file($file_info)
    {
      $values = array(
        "file_name" => $file_info["file_name"],
        "thumb_name" => $file_info["raw_name"]."_thumb".$file_info["file_ext"],
      );
      $insert_success = $this->db->insert("Scheduler_File", $values);
      if($insert_success)
      {
        return $this->db->insert_id();
      }
      else
      {
        return NULL;
      }
    }

    function insert_to_event_has($eid, $file_id)
    {
      $values = array(
        "eid" => $eid,
        "file_id" => $file_id,
      );
      $insert_success = $this->db->insert("scheduler_Event_Has", $values);
      return $insert_success;
    }

    function delete_img($eid, $file_id)
    {

      $file = $this->db->select("file_name, thumb_name")->where("file_id",$file_id)->get("Scheduler_File")->result()[0];
      $result = $this->db->where(array("eid" => $eid, "file_id" => $file_id))->delete("Scheduler_Event_Has");
      $output = array();
      if($result)
      {
        $file_deleted = $this->db->where("file_id",$file_id)->delete("Scheduler_File");
        unlink($this->config->item("UPLOADS")."/".$file->file_name);
        unlink($this->config->item("UPLOADS")."/".$file->thumb_name);
        if($file_deleted)
        {
          $output["message"] = "Delete successful";
          $output["success"] = TRUE;
          return $output;
        }
        else
        {
          $output["message"] = "File not deleted.";
          $output["success"] = FALSE;
          return $output;
        }
      }
      else
      {
        $output["message"] = "Assoc not deleted.";
        $output["success"] = FALSE;
        return $output;
      }
    }

    function add_to_event_has($eid, $file_id)
    {
        $result = $this->db->insert("Scheduler_Event_Has",array("eid" => $eid, "file_id" => $file_id));
        return $result;
    }
  }
?>

redpajama_set_name: RedPajamaGithub


text:
"""The venstar component."""
import logging

DOMAIN = "venstar"

ATTR_FAN_STATE = "fan_state"
ATTR_HVAC_STATE = "hvac_mode"

CONF_HUMIDIFIER = "humidifier"

DEFAULT_SSL = False

HOLD_MODE_OFF = "off"
HOLD_MODE_TEMPERATURE = "temperature"

VENSTAR_TIMEOUT = 5
VENSTAR_SLEEP = 1.0

_LOGGER = logging.getLogger(__name__)


text:
package com.linkedin.datahub.graphql.types.glossary.mappers;

import javax.annotation.Nonnull;

import com.linkedin.datahub.graphql.generated.GlossaryTermInfo;
import com.linkedin.datahub.graphql.types.common.mappers.StringMapMapper;
import com.linkedin.datahub.graphql.types.mappers.ModelMapper;

/**
 * Maps Pegasus {@link RecordTemplate} objects to objects conforming to the GQL schema.
 *
 * To be replaced by auto-generated mappers implementations
 */
public class GlossaryTermInfoMapper implements ModelMapper<com.linkedin.glossary.GlossaryTermInfo, GlossaryTermInfo> {

    public static final GlossaryTermInfoMapper INSTANCE = new GlossaryTermInfoMapper();

    public static GlossaryTermInfo map(@Nonnull final com.linkedin.glossary.GlossaryTermInfo glossaryTermInfo) {
        return INSTANCE.apply(glossaryTermInfo);
    }

    @Override
    public GlossaryTermInfo apply(@Nonnull final com.linkedin.glossary.GlossaryTermInfo glossaryTermInfo) {
        com.linkedin.datahub.graphql.generated.GlossaryTermInfo glossaryTermInfoResult = new com.linkedin.datahub.graphql.generated.GlossaryTermInfo();
        glossaryTermInfoResult.setDefinition(glossaryTermInfo.getDefinition());
        glossaryTermInfoResult.setTermSource(glossaryTermInfo.getTermSource());
        if (glossaryTermInfo.hasSourceRef()) {
            glossaryTermInfoResult.setSourceRef(glossaryTermInfo.getSourceRef());
        }
        if (glossaryTermInfo.hasSourceUrl()) {
            glossaryTermInfoResult.setSourceUrl(glossaryTermInfo.getSourceUrl().toString());
        }
        if (glossaryTermInfo.hasCustomProperties()) {
            glossaryTermInfoResult.setCustomProperties(StringMapMapper.map(glossaryTermInfo.getCustomProperties()));
        }
        if (glossaryTermInfo.hasRawSchema()) {
            glossaryTermInfoResult.setRawSchema(glossaryTermInfo.getRawSchema());
        }
        return glossaryTermInfoResult;
    }
}


text:
//
//  ViewController.m
//  AutoLayoutPractice
//
//  Created by Xuan on 1/7/16.
//  Copyright © 2016 Wingzero. All rights reserved.
//

#import "ViewController.h"
#import "MyTableViewCell.h"
#import "MyCollectionViewCell.h"
#import "AnotherCollectionViewCell.h"
#import "MyFlowLayout.h"

@interface ViewController () <UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@end

@implementation ViewController {
    NSArray *images;
    NSArray *labels;
    UITableView *tView;
    UICollectionView *cView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    images = @[@"Earth", @"Alexstrasza_full"];
    labels = @[@"haha", @"asdfasdfasdfasdfasdfsadfasdfasdasdfasdfsadfasdfasdasdfasdfsadfasdfasdasdfasdfsadfasdfasdasdfasdfsadfasdfasdfasdfasdfasdfasdf"];

//    [self buildTableView];
    [self buildCollectionView];
}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    NSLog(@"view did layout subviews");
}

-(void)buildTableView {
    CGRect f = [[UIScreen mainScreen] bounds];
    tView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, f.size.width, f.size.height)];
    tView.dataSource = self;

    /**
     *  this is important, setting this will tell table view its row height is dynamic
     *
     */
    tView.estimatedRowHeight = 50;

    [tView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:nil] forCellReuseIdentifier:@"myCell"];
    [self.view addSubview:tView];
}

-(void)buildCollectionView {
    CGRect f = [[UIScreen mainScreen] bounds];
    cView = [[UICollectionView alloc] initWithFrame:f collectionViewLayout:[[MyFlowLayout alloc] init]];
    cView.backgroundColor = [UIColor whiteColor];

    /**
     *  This method is important to call, so the cell can self-sizing
     */
    ((UICollectionViewFlowLayout *)cView.collectionViewLayout).estimatedItemSize = CGSizeMake(f.size.width, 50);

    [cView registerNib:[UINib nibWithNibName:@"MyCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"myCollectionCell"];
    cView.dataSource = self;
    cView.delegate = self;
    [self.view addSubview:cView];
}

#pragma mark - UITableViewDataSouce
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = (MyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"myCell"];
    if (!cell) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
    }
    cell.imgView.image = [UIImage imageNamed:images[indexPath.row % images.count]];
    cell.labelView.text = labels[indexPath.row % images.count];

    return cell;
}

#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 10;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"myCollectionCell" forIndexPath:indexPath];
    cell.imgView.image = [UIImage imageNamed:images[indexPath.row % images.count]];
    cell.labelView.text = labels[indexPath.row % labels.count];

    return cell;
}

@end


text:
#import "RMXNumberVariable.h"

#import "RMXRemixer+Private.h"

@implementation RMXNumberVariable

@dynamic limitedToValues;

+ (instancetype)numberVariableWithKey:(NSString *)key
                         defaultValue:(CGFloat)defaultValue
                      limitedToValues:(NSArray<NSNumber *> *)limitedToValues
                          updateBlock:(nullable RMXNumberUpdateBlock)updateBlock {
  RMXVariable *existingVariable = [RMXRemixer variableForKey:key];
  if (existingVariable) {
    [existingVariable addAndExecuteUpdateBlock:^(RMXVariable *variable, id selectedValue) {
      if (updateBlock) {
        updateBlock((RMXNumberVariable *)variable, [selectedValue floatValue]);
      }
    }];
    return (RMXNumberVariable *)existingVariable;
  } else {
    RMXNumberVariable *variable = [[self alloc] initWithKey:key
                                               defaultValue:defaultValue
                                            limitedToValues:limitedToValues
                                                updateBlock:updateBlock];
    [RMXRemixer addVariable:variable];
    return variable;
  }
}

- (NSDictionary *)toJSON {
  NSMutableDictionary *json = [super toJSON];
  json[RMXDictionaryKeySelectedValue] = @(self.selectedFloatValue);
  if (self.limitedToValues.count > 0) {
    json[RMXDictionaryKeyLimitedToValues] = self.limitedToValues;
  }
  return json;
}

#pragma mark - Private

- (instancetype)initWithKey:(NSString *)key
               defaultValue:(CGFloat)defaultValue
            limitedToValues:(NSArray<NSNumber *> *)limitedToValues
                updateBlock:(nullable RMXNumberUpdateBlock)updateBlock {
  self = [super initWithKey:key
                   dataType:RMXDataTypeNumber
               defaultValue:@(defaultValue)
                updateBlock:^(RMXVariable *_Nonnull variable, id _Nonnull selectedValue) {
                  if (updateBlock) {
                    updateBlock((RMXNumberVariable *)variable, [selectedValue floatValue]);
                  }
                }];
  if (self) {
    self.limitedToValues = limitedToValues;
    self.controlType = limitedToValues.count > 0 ? RMXControlTypeTextList : RMXControlTypeTextInput;
  }
  return self;
}

- (CGFloat)selectedFloatValue {
  return [self.selectedValue floatValue];
}

- (void)setSelectedFloatValue:(CGFloat)selectedFloatValue {
  self.selectedValue = @(selectedFloatValue);
}

@end


text:
// This file is automatically generated.

package adila.db;

/*
 * Alcatel ONE TOUCH 6012D
 *
 * DEVICE: California
 * MODEL: ONE TOUCH 6012E
 */
final class california_one20touch206012e {
    public static final String DATA = "Alcatel|ONE TOUCH 6012D|";
}


text:
package com.b2international.snowowl.retrofit;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * @since 5.10.18
 */
public class AuthenticationInterceptor implements Interceptor {

	private final String authToken;

	public AuthenticationInterceptor(final String token) {
		this.authToken = token;
	}

	@Override
	public Response intercept(final Chain chain) throws IOException {
		return chain.proceed(chain.request().newBuilder().header("Authorization", authToken).build());
	}

}


text:
/*

Assign addresses to variables

(c) 2010 Rudolf Kudla
Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

This module is responsible for assigning physical addresses to variables.

*/

#include "language.h"

//var_heap:0..255 or 32000..65000

GLOBAL MemHeap VAR_HEAP;		// variable heap (or zero page heap), this is heap from which variables are preferably allocated

void ProcClearProcessed(Var * proc)
{
	SetFlagOff(proc->flags, VarProcessed);
}

Bool ProcCallsProc(Var * proc, Var * called_proc)
/*
Purpose:
	Test, whether procedure 'called_proc' is called (even indirectly) from specified procedure.
*/{
	Bool calls = false;
	Instr * i;
	InstrBlock * blk;

	// We use VarProcessed to prevent resursion for recursive functions, even
	// if recursion is not supported yet.

	if (FlagOff(proc->flags, VarProcessed)) {
		SetFlagOn(proc->flags, VarProcessed);
		for(blk = proc->instr; blk != NULL; blk = blk->next) {
			for(i = blk->first; i != NULL; i = i->next) {
				if (i->op == INSTR_CALL) {
					if (i->result == called_proc || ProcCallsProc(i->result, called_proc)) {
						calls = true;
						goto done;
					}
				}
			}
		}
done:
		SetFlagOff(proc->flags, VarProcessed);
	}
	return calls;
}

typedef struct
{
	VarSet vars;
	UInt8 * collisions;			// 2D array of collisions of local_variables
	LiveSet last_block;
} VarAllocInfo;

Bool BlockIsLast(InstrBlock * blk)
{
	return (blk->to == NULL || blk->to == blk) && (blk->cond_to == NULL || blk->cond_to == blk);
}

LiveSet MergeLiveSets(InstrBlock * blk, UInt16 count, LiveSet last_block)
{
	UInt16 i;
	LiveSet src_live;
	LiveSet live = (LiveSet)MemAllocEmpty(count);

	// For the last block, begin with of last block info
	if (BlockIsLast(blk)) {
		MemMove(live, last_block, count);
	// For non-last block, use union of to and cond_to block results
	} else {
		if (blk->to != NULL) {
			MemMove(live, blk->to->analysis_data, count);
		}
		if (blk->cond_to != NULL && blk->cond_to != blk) {
			src_live = (LiveSet)blk->cond_to->analysis_data;
			for(i=0; i<count; i++) {
				live[i] = live[i] | src_live[i];
			}
		}
	}
	return live;
}

void MarkVarCollision(VarAllocInfo * info, LiveSet live, UInt16 idx)
{
	UInt16 count, i;
	count = VarSetCount(&info->vars);
	for(i=0; i<count; i++) {
		if (live[i] == 1) {
			info->collisions[idx*count+i] = 1;
			info->collisions[i*count+idx] = 1;
		}
	}
}

void VarAllocVar(VarAllocInfo * info, Var * var, LiveSet live, UInt8 mark)
/*
Purpose:
	Mark variable in live set as either live (used) or dead (assigned).
	If variable is not in the live set, do nothing.
*/
{
	UInt16 idx;
	if (var == NULL) return;
	if (var->mode == INSTR_VAR) {
		idx = var->set_index;
		if (idx >= 0 && idx < VarSetCount(&info->vars) && VarSetItem(&info->vars, idx)->key == var) {
			live[idx] = mark;
//			if (mark == 1) {
				MarkVarCollision(info, live, idx);
//			}
		}
		if (var->adr != NULL) {
			VarAllocVar(info, var->adr, live, mark);
		}

	// For array element, we mark the index variable as read, while whole array gets marked as dead/alive
	} else if (var->mode == INSTR_ELEMENT || var->mode == INSTR_BYTE) {
		VarAllocVar(info, var->adr, live, mark);
		VarAllocVar(info, var->var, live, 1);
	}
}

void VarAllocProc(VarAllocInfo * info, Var * proc, LiveSet live)
/*
Purpose:
	Mark all variables in specified live set as either used or even assigned in the procedure.
	We are basically not interested in the order of the variable use, as for the purpose of the
	variable assignment analysis, the procedure call is single instruction.
*/
{
	Var * var;
	if (proc->instr == NULL) {

		// Local instructions used by procedure (not in or out arguments)
		FOR_EACH_LOCAL(proc, var)
			if (FlagOff(var->submode, SUBMODE_ARG_IN | SUBMODE_ARG_OUT)) {
				VarAllocVar(info, var, live, 1);
			}
		NEXT_LOCAL

		FOR_EACH_OUT_ARG(proc, var)
			VarAllocVar(info, var, live, 0);
		NEXT_LOCAL

		// Procedure may use same variable both for input and output (for example using aliasing)
		// a:proc >x@_a <y@_a
		// In such case, marking variable as live has precedence.

		FOR_EACH_IN_ARG(proc, var)
			VarAllocVar(info, var, live, 1);
		NEXT_LOCAL

	} else {
	}
}

Bool VarAllocBlock(Var * proc, InstrBlock * blk, void * pinfo)
{
	Instr * i;
	VarAllocInfo * info = (VarAllocInfo *)pinfo;
	UInt16 count = VarSetCount(&info->vars);
	LiveSet live = MergeLiveSets(blk, count, info->last_block);
	InstrInfo * ii;

	// Traverse block backwards and mark variables as live/dead

	for(i = blk->last; i != NULL; i = i->prev) {
		ii = &INSTR_INFO[i->op];

		if (i->op == INSTR_CALL) {
			// mark all variables used by the procedure as live
			VarAllocProc(info, i->result, live);
		} else {

			if (ii->arg_type[0] != TYPE_VOID) {
				VarAllocVar(info, i->result, live, 0);
				// mark variable as dead
			}

			if (ii->arg_type[1] != TYPE_VOID) {
				VarAllocVar(info, i->arg1, live, 1);
			}

			if (ii->arg_type[2] != TYPE_VOID) {
				VarAllocVar(info, i->arg2, live, 1);
			}
		}
	}
	blk->analysis_data = live;

	return true;
}

Bool FilterVar(Var * var)
{
	return !VarIsLabel(var) && var->type->variant != TYPE_PROC && var->type->variant != TYPE_MACRO && !VarIsReg(var);
}

void PrintCollisions(VarAllocInfo * info)
{
	UInt16 i, j, count;

	count = VarSetCount(&info->vars);

	for(i = 0; i < count; i++) {
		for(j = 0; j < count; j++) {
			Print(info->collisions[i*count+j]==0?".":"X");
		}
		PrintEOL();
	}

}

void BlockFreeLiveSet(InstrBlock * blk, void * pinfo)
{
	MemFree(blk->analysis_data);
	blk->analysis_data = NULL;
}

void AllocateVariablesFromHeap(Var * proc, MemHeap * heap)
/*
Purpose:
	Allocate procedure local variables using specified heap.
	Try to reuse non-conflicting variables.
	Two variables are in conflict, if they are used in the same time.
*/
{
	Var * var, * var2;
	UInt32 size, adr;
	UInt16 i, j, count;
	VarAllocInfo info;

	// Get all local variables defined for the procedure.
	// As we are going to assign addresses to them, labels, procedures, macros and registers are excluded.

	VarSetInit(&info.vars);
	ProcLocalVars(proc, &info.vars, &FilterVar);
	count = VarSetCount(&info.vars);

	// Graph of variable collisions is represented as 2D array.
	// If item collision[a,b] is set to 1, it means the variables a and b are colliding (i.e. they are live at the same moment)
	info.collisions = (UInt8 *)MemAllocEmpty(count * count);

	// For first live set, mark all output variables as live.
	info.last_block = (LiveSet)MemAllocEmpty(count);
	for(i=0; i<count; i++) {
		var = VarSetItem(&info.vars, i)->key;
		if (VarIsOutArg(var)) {
			VarAllocVar(&info, var, info.last_block, 1);
		}
	}

//	VarSetPrint(&info.vars);

	OptimizeDataFlowBack(proc, &VarAllocBlock, &info);

//	PrintCollisions(&info);

	for(i = 0; i < count; i++) {
		var = VarSetItem(&info.vars, i)->key;

		// Do not assign address to variable that already has address
		if (var->adr == NULL) {
			size = TypeSize(var->type);
			if (size > 0) {

				// Try to find another variable with address which does not collide with this variable
				for(j = 0; j < count; j++) {
					if (i != j && info.collisions[i*count+j] == 0) {
						var2 = VarSetItem(&info.vars, j)->key;
						if (VarIsIntConst(var2->adr) && !OutVar(var2) && !InVar(var2)) {
							if (TypeSize(var2->type) == size) {
								// We have found the variable, whose address we can use

								// Mark variable to which we assign address of other variable to be conflicting with same variables as the other
								MarkVarCollision(&info, &info.collisions[j*count], i);
								MarkVarCollision(&info, &info.collisions[i*count], j);
//								PrintVarName(var); Print("@"); PrintVarName(var2); PrintEOL();
//								PrintCollisions(&info);

								var->adr = var2;
								goto next;
							}
						}
					}

				}

				if (HeapAllocBlock(heap, size, &adr) || HeapAllocBlock(&VAR_HEAP, size, &adr)) {
//							PrintVarName(var); Print("@%d\n", adr);
					var->adr = VarInt(adr);
				} else {
					// failed to alloc memory
				}
			}
		}
next: ;
	}

	// Cleanup

	MemFree(info.collisions);
	MemFree(info.last_block);
	VarSetCleanup(&info.vars);
	ForEachBlock(proc->instr, &BlockFreeLiveSet, NULL);

/*
	for (var = VarFirstLocal(proc); var != NULL; var = VarNextLocal(proc, var)) {

		// Scope can contain variables in subscope, we need to allocate them too
		if (var->mode == INSTR_SCOPE) {
			AllocateVariablesFromHeap(var, heap);
		} else {
			// Do not assign address to unused variables, labels and registers
			if (var->adr == NULL && var->mode == INSTR_VAR) {
				if ((var->write > 0 || var->read > 0) && !VarIsLabel(var) && !VarIsReg(var)) {
					size = TypeSize(var->type);
					if (size > 0) {
						if (HeapAllocBlock(heap, size, &adr) || HeapAllocBlock(&VAR_HEAP, size, &adr)) {
//							PrintVarName(var); Print("@%d\n", adr);
							var->adr = VarInt(adr);
						} else {
							// failed to alloc in zero page
						}
					}
				}
			}
		}
	}
*/
}

void AllocateVariablesFromHeapNoOptim(Var * proc, MemHeap * heap)
{
	Var * var;
	UInt32 size, adr;

	for (var = VarFirstLocal(proc); var != NULL; var = VarNextLocal(proc, var)) {

		// Scope can contain variables in subscope, we need to allocate them too
		if (var->mode == INSTR_SCOPE) {
			AllocateVariablesFromHeap(var, heap);
		} else {
			// Do not assign address to unused variables, labels and registers
			if (var->adr == NULL && var->mode == INSTR_VAR) {
				if ((var->write > 0 || var->read > 0) && !VarIsLabel(var) && !VarIsReg(var)) {
					size = TypeSize(var->type);
					if (size > 0) {
						if (HeapAllocBlock(heap, size, &adr) || HeapAllocBlock(&VAR_HEAP, size, &adr)) {
//							PrintVarName(var); Print("@%d\n", adr);
							var->adr = VarInt(adr);
						} else {
							// failed to alloc in zero page
						}
					}
				}
			}
		}
	}
}

#define VAR_ADD 0
#define VAR_REMOVE 1

void HeapVarOp(MemHeap * heap, Var * var, int op)
{
	UInt32 size, adr;
	Var * vadr;
	BigInt * ia;

	if (var == NULL) return;

	if (var->mode == INSTR_VAR) {
		size = TypeSize(var->type);
		vadr = var->adr;
		if (size > 0 && vadr != NULL) {
			if (vadr->mode == INSTR_TUPLE) {
				HeapVarOp(heap, vadr, op);
			} else {
				ia = VarIntConst(vadr);
				if (ia != NULL) {
					adr  = IntN(ia);
					if (op == VAR_REMOVE) {
						HeapRemoveBlock(heap, adr, size);
					} else {
						HeapAddBlock(heap, adr, size);
					}
				}
			}
		}

	} else if (var->mode == INSTR_TUPLE) {
		// Tuple is ignored. If it references variables local to this scope, they will be processed separately anyways.
		//HeapVarOp(heap, var->adr, op);
		//HeapVarOp(heap, var->var, op);
	}
}

void HeapVariablesOp(MemHeap * heap, Var * scope, int op)
{
	Var * var;

	for (var = VarFirstLocal(scope); var != NULL; var = VarNextLocal(scope, var)) {
		if (var->mode == INSTR_SCOPE) {
			HeapVariablesOp(heap, var, op);
		} else {
			HeapVarOp(heap, var, op);
		}
	}
}

extern Var   ROOT_PROC;

void AllocateVariables(Var * proc)
{
	Var * proc2;
	Type * type;
	MemHeap heap;

	HeapInit(&heap);

	//==== Find space already allocated for other procedure variables that can be reused
	//     We can reuse variables from procedures, that this procedure
	//     does not call (even indirectly) and which does not call this procedure.

	for(proc2 = VarFirst(); proc2 != NULL; proc2 = VarNext(proc2)) {
		type = proc2->type;
		if (type != NULL && type->variant == TYPE_PROC && proc2->read > 0 && proc2->instr != NULL) {
//			Print("%s -> %s", proc2->name, proc->name);
			if (proc2 != proc && !ProcCallsProc(proc, proc2) && !ProcCallsProc(proc2, proc)) {
//				if (/*StrEqual(proc->name, "copyblock") &&*/ StrEqual(proc->name, "drawmainscreen")) {
//					Print("***\n");
//				}
				HeapVariablesOp(&heap, proc2, VAR_ADD);
//				if (StrEqual(proc->name, "drawmainscreen")) {
//					HeapPrint(&heap);
//				}

			} else {
//				Print("... Dependent");
			}
//			Print("\n");
		}
	}

	//==== Remove space allocated by procedures we are calling or which call us

	//TODO: Procedure must not have body (may be external) and still define arguments

	for(proc2 = VarFirst(); proc2 != NULL; proc2 = VarNext(proc2)) {
		type = proc2->type;

//		if (StrEqual(proc2->name, "copyblock") && StrEqual(proc->name, "drawmainscreen")) {
//			Print("***");
//		}

		if (type != NULL && type->variant == TYPE_PROC && proc2->read > 0 && proc2->instr != NULL) {
			if (proc2 != proc && (FlagOn(proc2->flags, VarUsedInInterupt) || ProcCallsProc(proc, proc2) || ProcCallsProc(proc2, proc))) {
//				if (StrEqual(proc->name, "drawmainscreen")) {
//					HeapPrint(&heap);
//				}
				HeapVariablesOp(&heap, proc2, VAR_REMOVE);
//				if (StrEqual(proc->name, "drawmainscreen")) {
//					HeapPrint(&heap);
//				}
			}
		}
	}

	//==== Allocate space for all variables, that has not been assigned yet

	AllocateVariablesFromHeapNoOptim(proc, &heap);

	HeapCleanup(&heap);
}


text:
<!DOCTYPE html>

  <title>Failed</title>

OMG, something went horribly wrong.

If this were real, this would be a beautifully-styled fail page.

Your error is:

({{.Error.Code}}) - {{.Error.ClientMsg}}


text:
package br.gov.servicos.editor.conteudo.cartas;

import br.gov.servicos.editor.git.Metadados;
import br.gov.servicos.editor.git.RepositorioGit;
import br.gov.servicos.editor.git.Revisao;
import br.gov.servicos.editor.utils.EscritorDeArquivos;
import br.gov.servicos.editor.utils.LeitorDeArquivos;
import br.gov.servicos.editor.utils.ReformatadorXml;
import com.github.slugify.Slugify;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Optional;
import java.util.function.Supplier;

import static br.gov.servicos.editor.utils.TestData.PROFILE;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
public class CartaTest {

    static final Date HORARIO = new Date();

    static final Revisao REVISAO = new Revisao().withHash("da39a3ee5e6b4b0d3255bfef95601890afd80709")
            .withAutor("User Name")
            .withHorario(HORARIO);

    static final Metadados<Carta.Servico> METADADOS = new Metadados<Carta.Servico>().withId("um-id-qualquer");

    Carta carta;

    @Mock
    RepositorioGit repositorio;

    @Mock
    LeitorDeArquivos leitorDeArquivos;

    @Mock
    EscritorDeArquivos escritorDeArquivos;

    @Mock
    ReformatadorXml reformatadorXml;

    @Captor
    ArgumentCaptor<Supplier<Optional<String>>> captor;

    @Before
    public void setUp() throws Exception {
        carta = new Carta.Factory(new Slugify(), repositorio, leitorDeArquivos, escritorDeArquivos, reformatadorXml)
                .carta("um-id-qualquer");
    }

    @Test
    public void formataBranchLocal() throws Exception {
        assertThat(carta.getBranchRef(),
                is("refs/heads/um-id-qualquer"));
    }

    @Test
    public void resolveCaminhoAbsoluto() throws Exception {
        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        assertThat(carta.getCaminhoAbsoluto(),
                is(Paths.get("/um/caminho/qualquer/cartas-servico/v3/servicos/um-id-qualquer.xml")));
    }

    @Test
    public void resolveCaminhoRelativo() throws Exception {
        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        assertThat(carta.getCaminhoRelativo(),
                is(Paths.get("cartas-servico/v3/servicos/um-id-qualquer.xml")));
    }

    @Test
    public void buscaMetadadosDoUltimoCommitQuandoExisteBranch() throws Exception {
        given(repositorio.getRevisaoMaisRecenteDoArquivo(Paths.get("cartas-servico/v3/servicos/um-id-qualquer.xml")))
                .willReturn(Optional.empty());

        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        given(repositorio.getRevisaoMaisRecenteDoBranch("refs/heads/um-id-qualquer"))
                .willReturn(of(REVISAO));

        assertThat(carta.getMetadados(), is(METADADOS.withPublicado(null).withEditado(REVISAO)));
    }

    @Test
    public void buscaMetadadosDoUltimoCommitQuandoNaoExisteBranch() throws Exception {
        given(repositorio.getRevisaoMaisRecenteDoBranch("refs/heads/um-id-qualquer"))
                .willReturn(empty());

        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        given(repositorio.getRevisaoMaisRecenteDoArquivo(Paths.get("cartas-servico/v3/servicos/um-id-qualquer.xml")))
                .willReturn(of(REVISAO));

        assertThat(carta.getMetadados(), is(METADADOS.withPublicado(REVISAO).withEditado(null)));
    }

    @Test
    public void retornaConteudoDoArquivoNoBranch() throws Exception {
        given(repositorio.comRepositorioAbertoNoBranch(eq("refs/heads/um-id-qualquer"), captor.capture()))
                .willReturn(of("<servico/>"));

        assertThat(carta.getConteudoRaw(), is("<servico/>"));

        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        given(leitorDeArquivos.ler(new File("/um/caminho/qualquer/cartas-servico/v3/servicos/um-id-qualquer.xml")))
                .willReturn(of("<servico/>"));

        assertThat(captor.getValue().get().get(), is("<servico/>"));
    }

    @Test
    public void retornaConteudoVazioQuandoArquivoNaoExisteNoBranch() throws Exception {
        given(repositorio.comRepositorioAbertoNoBranch(eq("refs/heads/um-id-qualquer"), captor.capture()))
                .willReturn(of("<servico/>"));

        assertThat(carta.getConteudoRaw(), is("<servico/>"));

        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        given(leitorDeArquivos.ler(new File("/um/caminho/qualquer/cartas-servico/v3/servicos/um-id-qualquer.xml")))
                .willReturn(Optional.empty());

        assertThat(captor.getValue().get().isPresent(), is(false));
    }

    @Test(expected = FileNotFoundException.class)
    public void jogaFileNotFoundExceptionCasoNaoHajaArquivoNoBranch() throws Exception {
        given(repositorio.comRepositorioAbertoNoBranch(eq("refs/heads/um-id-qualquer"), anyObject())).willReturn(Optional.empty());

        carta.getConteudoRaw();
    }

    @Test
    public void salvaConteudoNoBranch() throws Exception {
        given(repositorio.comRepositorioAbertoNoBranch(eq("refs/heads/um-id-qualquer"), captor.capture()))
                .willReturn(null);

        carta.salvar(PROFILE, "<servico/>");

        given(repositorio.getCaminhoAbsoluto())
                .willReturn(Paths.get("/um/caminho/qualquer"));

        captor.getValue().get();

        verify(repositorio).pull();

        Path caminho = Paths.get("cartas-servico/v3/servicos/um-id-qualquer.xml");

        verify(repositorio).add(caminho);
        verify(repositorio).commit(caminho, "Cria 'um-id-qualquer'", PROFILE);
        verify(repositorio).push("refs/heads/um-id-qualquer");
    }

    @Test
    public void publicaConteudo() {
        given(repositorio.comRepositorioAbertoNoBranch(eq("refs/heads/master"), captor.capture()))
                .willReturn(null);

        carta.publicar();

        captor.getValue().get();

        verify(repositorio).merge("refs/heads/um-id-qualquer");
        verify(repositorio).push("refs/heads/master");
    }
}


text:
package org.nschmidt.ldparteditor.helper.compositetext;

import org.nschmidt.ldparteditor.data.DatFile;

/**
 * Selects selected lines in the "3D view"
 */
public enum Text2SelectionConverter {
    INSTANCE;

    /**
     * Selects selected lines in the "3D view"
     *
     * @param cText
     *            the selected CompositeText
     * @param lineStart
     *            start line number to annotate
     * @param lineEnd
     *            end line number to annotate
     * @param datFile
     */
    public static void convert(int lineStart, int lineEnd, DatFile datFile) {
        datFile.getVertexManager().clearSelection();
        lineEnd++;
        for (int line = lineStart; line < lineEnd; line++) {
            datFile.getVertexManager().addTextLineToSelection(line);
        }
    }
}


text:
Name

jrunscript - command line script shell

SYNOPSIS

f3
f3jrunscript [ f2options ] [ arguments... ]

PARAMETERS

options  Options, if used, should follow immediately after the command name.

arguments  Arguments, if used, should follow immediately after options or command name.

DESCRIPTION

f3jrunscript is a command line script shell. jrunscript supports both an interactive (read-eval-print) mode and a batch (-f option) mode of script execution. This is a scripting language independent shell. By default, JavaScript is the language used, but the -l option can be used to specify a different language. Through Java to scripting language communication, jrunscript supports "exploratory programming" style.

f3NOTE: This tool is f3experimental and may f3not be available in future versions of the JDK.

OPTIONS

-classpath path  Specify where to find the user's .class files that are accessed by the script.

-cp path  This is a synonym for -classpath f2path

-Dname=value  Set a Java system property.

-J<flag>  Pass <flag> directly to the Java virtual machine on which jrunscript is run.

-l language  Use the specified scripting language. By default, JavaScript is used. Note that to use other scripting languages, you also need to specify the corresponding script engine's jar file using -cp or -classpath option.

-e script  Evaluate the given script. This option can be used to run "one liner" scripts specified completely on the command line.

-encoding encoding  Specify the character encoding used while reading script files.

-f script-file  Evaluate the given script file (batch mode).

-f -  Read and evaluate a script from standard input (interactive mode).

-help   Output help message and exit.

-?   Output help message and exit.

-q   List all script engines available and exit.

ARGUMENTS

If [arguments...] are present and if no f3-e or f3-f option is used, then the first argument is the script file and the rest of the arguments, if any, are passed as script arguments. If [arguments..] and f3-e or f3-f option are used, then all [arguments..] are passed as script arguments. If [arguments..], f3-e and f3-f are missing, interactive mode is used. Script arguments are available to a script in an engine variable named "arguments" of type String array.

EXAMPLES

Executing inline scripts

f3
jrunscript -e "print('hello world')"
jrunscript -e "cat('http://www.example.com')"

Use specified language and evaluate given script file

f3
jrunscript -l js -f test.js

Interactive mode

f3
jrunscript
js> print('Hello World\n');
Hello World
js> 34 + 55
89.0
js> t = new java.lang.Thread(function() { print('Hello World\n'); })
Thread[Thread-0,5,main]
js> t.start()
js> Hello World

js>

Run script file with script arguments

f3
jrunscript test.js arg1 arg2 arg3

test.js is script file to execute and arg1, arg2 and arg3 are passed to script as script arguments. Script can access these using "arguments" array.
SEE ALSO

If JavaScript is used, then before evaluating any user defined script, jrunscript initializes certain built-in functions and objects. These JavaScript built-ins are documented in

f2jsdocs @

http://docs.oracle.com/javase/7/docs/technotes/tools/share/jsdocs/allclasses-noframe.html.


text:
package me.lucko.helper.setting;

import com.google.common.io.BaseEncoding;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;

import java.util.Arrays;
import java.util.Objects;

/**
 * Creates and decodes {@link SettingMap}s for a given realm of settings and states.
 *
 *
It is safe to introduce additional settings and states, so long as the
 * ordinal values of existing ones are not affected.

 *
 * @param <S> the setting type
 */
public final class SettingMapFactory<S extends Setting<V>, V extends Setting.State> {

    /** The instance used for encoding/decoding setting maps */
    static final BaseEncoding ENCODING = BaseEncoding.base64().omitPadding();

    /**
     * Creates a new {@link SettingMapFactory} for the given {@link Setting} and {@link Setting.State} enums.
     *
     *
Factories should ideally be cached (stored in a static field) in the
     * setting enum and reused.

     *
     * @param settingsEnum the setting enum
     * @param statesEnum the states enum
     * @param <S> the class type
     * @return a new factory
     */
    public static <S extends Enum<S> & Setting<V>, V extends Enum<V> & Setting.State> SettingMapFactory<S, V> create(Class<S> settingsEnum, Class<V> statesEnum) {
        Objects.requireNonNull(settingsEnum, "settingsEnum");
        Objects.requireNonNull(statesEnum, "statesEnum");
        return create(settingsEnum.getEnumConstants(), statesEnum.getEnumConstants());
    }

    /**
     * Creates a new {@link SettingMapFactory} for the given {@link Setting}s and {@link Setting.State}s.
     *
     *
Factories should ideally be cached (stored in a static field) in the
     * setting class.

     *
     * @param settings the settings
     * @param <S> the class type
     * @return a new factory
     */
    public static <S extends Setting<V>, V extends Setting.State> SettingMapFactory<S, V> create(S[] settings, V[] states) {
        Objects.requireNonNull(settings, "settings");
        Objects.requireNonNull(states, "states");

        // ensure the number of settings can fit into a byte
        // we encode the number of "changes" from default as a byte.
        if (settings.length > 255) {
            throw new IllegalArgumentException("number of settings cannot be greater than 255");
        }

        // ensure the ordinal of any of the states can fit into a byte
        // means indexes run from 0-255
        if (states.length > 256) {
            throw new IllegalArgumentException("number of states cannot be greater than 256");
        }

        // ensure ordinal has been correctly implemented for the states
        for (int i = 0; i < states.length; i++) {
            V state = states[i];
            if (state.ordinal() != i) {
                throw new IllegalArgumentException("The ordinal of state " + state + " does not equal its array index. ordinal=" + state.ordinal() + ", index=" + i);
            }
        }

        byte[] defaultStates = new byte[settings.length];
        for (int i = 0; i < settings.length; i++) {
            S setting = settings[i];

            // ensure ordinal has been correctly implemented for the settings
            if (setting.ordinal() != i) {
                throw new IllegalArgumentException("The ordinal of setting " + setting + " does not equal its array index. ordinal=" + setting.ordinal() + ", index=" + i);
            }

            defaultStates[i] = (byte) setting.defaultState().ordinal();
        }

        return new SettingMapFactory<>(settings, states, defaultStates);
    }

    final S[] settings;
    final V[] states;

    // the index corresponds to the setting ordinal, the value corresponds to the state ordinal
    private final byte[] defaultStates;

    private SettingMapFactory(S[] settings, V[] states, byte[] defaultStates) {
        this.settings = settings;
        this.states = states;
        this.defaultStates = defaultStates;
    }

    /**
     * Gets the {@link Setting} instances.
     *
     * @return the setting instances
     */
    public S[] getSettings() {
        return Arrays.copyOf(this.settings, this.settings.length);
    }

    /**
     * Gets the {@link Setting.State} instances.
     *
     * @return the state instances
     */
    public V[] getStates() {
        return Arrays.copyOf(this.states, this.states.length);
    }

    /**
     * Returns if the given set of states differs from the defaults.
     *
     * @param states the states to compare
     * @return true if different
     */
    boolean isDifferentFromDefault(byte[] states) {
        return !Arrays.equals(this.defaultStates, states);
    }

    byte[] encode(byte[] states) {
        // calculate the number of differences
        int n = 0;
        for (int i = 0; i < states.length; i++) {
            byte state = states[i];
            byte defaultState = this.defaultStates[i];

            if (state == defaultState) {
                continue;
            }

            n++;
        }

        if (n == 0) {
            return new byte[0];
        }

        ByteArrayDataOutput out = ByteStreams.newDataOutput();

        // write the number of differences to "expect"
        out.writeByte((byte) n);

        for (int i = 0; i < states.length; i++) {
            byte state = states[i];
            byte defaultState = this.defaultStates[i];

            if (state == defaultState) {
                continue;
            }

            byte settingOrdinal = (byte) i;
            out.writeByte(settingOrdinal);
            out.writeByte(state);
        }

        return out.toByteArray();
    }

    /**
     * Creates a new {@link SettingMap}, with the default states set for each of the settings.
     *
     * @return the new map
     */
    public SettingMap<S, V> newMap() {
        return new SettingMap<>(this, Arrays.copyOf(this.defaultStates, this.defaultStates.length));
    }

    /**
     * Decodes the given byte array to a {@link SettingMap}.
     *
     *
Operates on the reverse of {@link SettingMap#encode()}.

     *
     * @param buf the byte array
     * @return the decoded map
     */
    public SettingMap<S, V> decode(byte[] buf) {
        if (buf.length == 0) {
            return newMap();
        }

        ByteArrayDataInput in = ByteStreams.newDataInput(buf);
        int n = Byte.toUnsignedInt(in.readByte());

        byte[] states = Arrays.copyOf(this.defaultStates, this.defaultStates.length);

        for (int i = 0; i < n; i++) {
            int settingOrdinal = Byte.toUnsignedInt(in.readByte());
            byte stateByte = in.readByte();

            states[settingOrdinal] = stateByte;
        }

        return new SettingMap<>(this, states);
    }

    /**
     * Decodes the given string to a {@link SettingMap}.
     *
     *
Operates on the reverse of {@link SettingMap#encodeToString()}.

     *
     * @param encodedString the string
     * @return the decoded map
     */
    public SettingMap<S, V> decode(String encodedString) {
        return decode(ENCODING.decode(encodedString));
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp
{
    internal enum ConversionKind : byte
    {
        NoConversion,
        Identity,
        ImplicitNumeric,
        ImplicitEnumeration,
        ImplicitThrow,
        ImplicitTupleLiteral,
        ImplicitTuple,
        ExplicitTupleLiteral,
        ExplicitTuple,
        ImplicitNullable,
        NullLiteral,
        ImplicitReference,
        Boxing,
        PointerToVoid,
        NullToPointer,
        ImplicitDynamic,
        ExplicitDynamic,
        ImplicitConstant,
        ImplicitUserDefined,
        AnonymousFunction,
        MethodGroup,
        ExplicitNumeric,
        ExplicitEnumeration,
        ExplicitNullable,
        ExplicitReference,
        Unboxing,
        ExplicitUserDefined,
        PointerToPointer,
        IntegerToPointer,
        PointerToInteger,
        // The IntPtr conversions are not described by the specification but we must
        // implement them for compatibility with the native compiler.
        IntPtr,
        InterpolatedString, // a conversion from an interpolated string to IFormattable or FormattableString
    }
}


text:
prime = 101
def pattern_matching(text, pattern):
    m = len(pattern)
    n = len(text)
    pattern_hash = create_hash(pattern, m - 1)
    text_hash = create_hash(text, m - 1)

    for i in range(1, n - m + 2):
        if pattern_hash == text_hash:
            if check_equal(text[i-1:i+m-1], pattern[0:]) is True:
                return i - 1;
        if i < n - m + 1:
            text_hash = recalculate_hash(text, i-1, i+m-1, text_hash, m)
    return -1;

def check_equal(str1, str2):
    if len(str1) != len(str2):
        return False;
    i = 0
    j = 0
    for i, j in zip(str1, str2):
        if i != j:
            return False;
    return True

def create_hash(input, end):
    hash = 0
    for i in range(end + 1):
        hash = hash + ord(input[i])*pow(prime, i)
    return hash

def recalculate_hash(input, old_index, new_index, old_hash, pattern_len):
    new_hash = old_hash - ord(input[old_index])
    new_hash = new_hash/prime
    new_hash += ord(input[new_index])*pow(prime, pattern_len - 1)
    return new_hash;

index = pattern_matching("TusharRoy", "sharRoy")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roy")
print("Index ", index)
index = pattern_matching("TusharRoy", "shar")
print("Index ", index)
index = pattern_matching("TusharRoy", "usha")
print("Index ", index)
index = pattern_matching("TusharRoy", "Tus")
print("Index ", index)
index = pattern_matching("TusharRoy", "Roa")
print("Index ", index)


text:
      5

        Notifications
        Mark All as Read
        Settings

{{nt.text}}

            {{nt.time}}

      See all notifications

      5

        Messages
        Mark All as Read
        Settings

{{msg.text}}

            {{msg.time}}

      See all messages


text:
class MoveEventReferenceIdAndTypeToAdditionalData < ActiveRecord::Migration
  def up
    remove_column :events, :reference_id
    remove_column :events, :reference_type
  end

  def down
    add_column :events, :reference_id, :integer
    add_column :events, :reference_type, :string
  end
end


text:
Chef::Recipe.send(:include, MariaDB::Helper)
case node['mariadb']['install']['type']
when 'package'
  if use_os_native_package?(node['mariadb']['install']['prefer_os_package'],
                            node['platform'], node['platform_version'])
    # currently, no releases with apt (e.g. ubuntu) ship mariadb
    # only provide one type of server here (with yum support)
    include_recipe "#{cookbook_name}::_redhat_server_native"
  else
    include_recipe "#{cookbook_name}::repository"

    case node['platform']
    when 'debian', 'ubuntu'
      include_recipe "#{cookbook_name}::_debian_server"
    when 'redhat', 'centos', 'fedora', 'scientific', 'amazon'
      include_recipe "#{cookbook_name}::_redhat_server"
    end
  end
when 'from_source'
  # To be filled as soon as possible
end

include_recipe "#{cookbook_name}::config"

service 'mysql' do
  service_name node['mariadb']['mysqld']['service_name']
  supports restart: true
  action :nothing
end

# move the datadir if needed
if node['mariadb']['mysqld']['datadir'] !=
   node['mariadb']['mysqld']['default_datadir']

  bash 'move-datadir' do
    user 'root'
    code <<-EOH
    /bin/cp -a #{node['mariadb']['mysqld']['default_datadir']}/* \
               #{node['mariadb']['mysqld']['datadir']} &&
    /bin/rm -r #{node['mariadb']['mysqld']['default_datadir']} &&
    /bin/ln -s #{node['mariadb']['mysqld']['datadir']} \
               #{node['mariadb']['mysqld']['default_datadir']}
    EOH
    action :nothing
  end

  directory node['mariadb']['mysqld']['datadir'] do
    owner 'mysql'
    group 'mysql'
    mode 00750
    action :create
    notifies :stop, 'service[mysql]', :immediately
    notifies :run, 'bash[move-datadir]', :immediately
    notifies :start, 'service[mysql]', :immediately
    only_if { !File.symlink?(node['mariadb']['mysqld']['default_datadir']) }
  end
end

# restart the service if needed
# workaround idea from https://github.com/stissot
Chef::Resource::Execute.send(:include, MariaDB::Helper)
execute 'mariadb-service-restart-needed' do
  command 'true'
  only_if do
    mariadb_service_restart_required?(
      node['mariadb']['mysqld']['bind_address'],
      node['mariadb']['mysqld']['port'],
      node['mariadb']['mysqld']['socket']
    )
  end
  notifies :restart, 'service[mysql]', :immediately
end

if node['mariadb']['allow_root_pass_change']
  # Used to change root password after first install
  # Still experimental
  if node['mariadb']['server_root_password'].empty?
    md5 = Digest::MD5.hexdigest('empty')
  else
    md5 = Digest::MD5.hexdigest(node['mariadb']['server_root_password'])
  end

  file '/etc/mysql_root_change' do
    content md5
    action :create
    notifies :run, 'execute[install-grants]', :immediately
  end
end

if  node['mariadb']['allow_root_pass_change'] ||
    node['mariadb']['forbid_remote_root']
  execute 'install-grants' do
    # Add sensitive true when foodcritic #233 fixed
    command '/bin/bash /etc/mariadb_grants \'' + \
      node['mariadb']['server_root_password'] + '\''
    only_if { File.exist?('/etc/mariadb_grants') }
    action :nothing
  end

  template '/etc/mariadb_grants' do
    sensitive true
    source 'mariadb_grants.erb'
    owner 'root'
    group 'root'
    mode '0600'
    notifies :run, 'execute[install-grants]', :immediately
  end
end

# MariaDB Plugins
include_recipe "#{cookbook_name}::plugins" if node['mariadb']['plugins_options']['auto_install']


text:
class MymenuTabnav < Tabnav::Base

    tab = add_tab do
      named 'My Menu'
    end

    add_submenu(tab) {submenu 'My Control Panel',    :links_to => {:controller => '/account', :action => 'index'}}
    add_submenu(tab) {submenu 'My Collection', :links_to => {:controller => '/collections', :action => 'my_collection'}}
    add_submenu(tab) {submenu 'Upload Photos', :links_to => {:controller => '/account', :action => 'pictures'}}
    add_submenu(tab) {submenu 'Write a New Blog', :links_to => {:controller => '/blogs', :action => :my_blog}}
    add_submenu(tab) {submenu 'Logout',        :links_to => {:controller => '/account', :action => 'logout'}}
    add_submenu(tab) {submenu 'Admin',         :links_to => {:controller => '/admin/dashboard', :action => 'index'},
                                               :conditions => 'admin?' }
end


text:
import { Query } from 'hotaru';
import { DbAdapter, SavingOptions } from './DbAdapter';

export abstract class InternalDbAdapter extends DbAdapter {
  public abstract async internalFind(query: Query): Promise<any[]>;
  public abstract async internalFirst(query: Query): Promise<any>;
  public abstract async internalSaveAll(className: string, objects: any[], options: SavingOptions): Promise<any[]>;
  public abstract async internalSaveObject(className: string, object: any, options: SavingOptions): Promise<any>;
  public abstract async internalDeleteAll(className: string, objects: any[]): Promise<boolean>;
  public abstract async internalDeleteObject(className: string, object: any): Promise<boolean>;
}


text:
set -ex

source "${HOME}/INSTALL/bin/activate"
pip install --upgrade pip wheel six setuptools nodeenv

# Install the latest version of nodejs. Some packages
# may not be compatible with the version.
nodeenv -p --prebuilt --node=12.11.1

# Pull in changes to activate made by nodeenv
source "${HOME}/INSTALL/bin/activate"

# Get around a Travis bug: https://github.com/travis-ci/travis-ci/issues/8315#issuecomment-327951718
unset _JAVA_OPTIONS

# This causes 'gulp compile' to fail.
unset JAVA_TOOL_OPTIONS

# Install grr packages as links pointing to code in the
# checked-out repository.
# Note that because of dependencies, order here is important.
#
# Proto package.
pip install -e grr/proto --progress-bar off

# Depends on grr-response-proto
pip install -e grr/core --progress-bar off

# Depends on grr-response-core
pip install -e grr/client --progress-bar off

# Depends on grr-response-core
pip install -e api_client/python --progress-bar off

# Depends on grr-response-client
pip install -e grr/client_builder --progress-bar off

# Depends on grr-response-client-builder
pip install -e grr/server/[mysqldatastore] --progress-bar off

# Depends on grr-api-client and grr-response-proto
pip install -e colab --progress-bar off

# Depends on all other packages
pip install -e grr/test --progress-bar off

cd grr/proto && python makefile.py && cd -
cd grr/core/grr_response_core/artifacts && python makefile.py && cd -