text:
package instancecontroller

import (
	"context"
	"errors"
	"fmt"
	"reflect"
	"strings"
	"time"

	maintenance "github.com/GoogleCloudPlatform/elcarro-oracle-operator/common/pkg/maintenance"
	v1alpha1 "github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/api/v1alpha1"
	"github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/controllers"
	"github.com/GoogleCloudPlatform/elcarro-oracle-operator/oracle/pkg/k8s"
	"github.com/go-logr/logr"
	corev1 "k8s.io/api/core/v1"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

// reservedParameters holds the list of parameters that aren't allowed for modification.
var reservedParameters = map[string]bool{
	"audit_file_dest":           true,
	"audit_trail":               true,
	"compatible":                true,
	"control_files":             true,
	"db_block_size":             true,
	"db_recovery_file_dest":     true,
	"diagnostic_dest":           true,
	"dispatchers":               true,
	"enable_pluggable_database": true,
	"filesystemio_options":      true,
	"local_listener":            true,
	"remote_login_passwordfile": true,
	"undo_tablespace":           true,
	"log_archive_dest_1":        true,
	"log_archive_dest_state_1":  true,
	"log_archive_format":        true,
	"standby_file_management":   true,
}

func (r *InstanceReconciler) recordEventAndUpdateStatus(ctx context.Context, inst *v1alpha1.Instance, conditionStatus v1.ConditionStatus, reason, msg string, log logr.Logger) {
	if conditionStatus == v1.ConditionTrue {
		r.Recorder.Eventf(inst, corev1.EventTypeNormal, reason, msg)
	} else {
		r.Recorder.Eventf(inst, corev1.EventTypeWarning, reason, msg)
	}
	k8s.InstanceUpsertCondition(&inst.Status, k8s.Ready, conditionStatus, reason, msg)
	if err := r.Status().Update(ctx, inst); err != nil {
		log.Error(err, "failed to update the instance status")
	}
}

// fetchCurrentParameterState infers the type and current value of the
// parameters by querying the database and is used for the following purpose,
// * The parameter type (static or dynamic) will be used for deciding whether
//
//	a database restart is required.
//
// * The current parameter value will be used for rollback if the parameter
//
//	update fails or the database is non-functional after the restart.
func fetchCurrentParameterState(ctx context.Context, r client.Reader, dbClientFactory controllers.DatabaseClientFactory, inst v1alpha1.Instance) (map[string]string, map[string]string, error) {
	spec := inst.Spec
	var unacceptableParams []string
	var keys []string
	for k := range spec.Parameters {
		if _, ok := reservedParameters[k]; ok {
			unacceptableParams = append(unacceptableParams, k)
		}
		keys = append(keys, k)
	}

	if len(unacceptableParams) != 0 {
		return nil, nil, fmt.Errorf("fetchCurrentParameterState: parameter list contains reserved parameters:%v", unacceptableParams)
	}
	staticParams := make(map[string]string)
	dynamicParams := make(map[string]string)
	setParameterReq := &controllers.GetParameterTypeValueRequest{
		Keys: keys,
	}
	response, err := controllers.GetParameterTypeValue(ctx, r, dbClientFactory, inst.Namespace, inst.Name, *setParameterReq)
	if err != nil {
		return nil, nil, fmt.Errorf("fetchCurrentParameterState: error while querying parameter type:%v", err)
	}

	// Check if static parameters are specified and restart is required.
	restartRequired := false
	paramType := response.Types
	paramValues := response.Values
	for i := 0; i < len(paramType); i++ {
		if paramType[i] == "FALSE" {
			restartRequired = restartRequired || paramType[i] == "FALSE"
			staticParams[keys[i]] = paramValues[i]
		} else {
			dynamicParams[keys[i]] = paramValues[i]
		}
	}

	// If restart is required, check if the restartTimeRange is specified in the config.
	if restartRequired && !maintenance.HasValidTimeRanges(spec.MaintenanceWindow) {
		return nil, nil, errors.New("maintenanceWindow for db downtime not specified for static parameter update")
	}

	currentTime := time.Now()
	inMaintenanceWindow := maintenance.InRange(spec.MaintenanceWindow, currentTime)

	if !inMaintenanceWindow {
		return nil, nil, errors.New("current time is not in a maintenance window that allows db restarts")
	}
	return staticParams, dynamicParams, nil
}

func (r *InstanceReconciler) setParameters(ctx context.Context, inst v1alpha1.Instance, log logr.Logger) (bool, error) {
	log.Info("Parameters are ", "parameters:", inst.Spec.Parameters)
	requireDatabaseRestart := false
	var keys []string

	for k, v := range inst.Spec.Parameters {
		isStatic, err := controllers.SetParameter(ctx, r.DatabaseClientFactory, r.Client, inst.Namespace, inst.Name, k, v)
		if err != nil {
			log.Error(err, "setParameters: error while running SetParameter query")
			return requireDatabaseRestart, err
		}
		keys = append(keys, k)
		requireDatabaseRestart = requireDatabaseRestart || isStatic
		log.Info("setParameters: requireDatabaseRestart", "requireDatabaseRestart", requireDatabaseRestart)
	}

	getParameterReq := &controllers.GetParameterTypeValueRequest{
		Keys: keys,
	}
	response, err := controllers.GetParameterTypeValue(ctx, r, r.DatabaseClientFactory, inst.Namespace, inst.Name, *getParameterReq)
	if err != nil {
		log.Error(err, "setParameters: error while running GetParameterTypeValue query")
		return false, err
	}

	paramValues := response.Values
	for i := 0; i < len(keys); i++ {
		if inst.Spec.Parameters[keys[i]] != paramValues[i] &&
			// For certain parameter types Oracle converts them to uppercase before storing
			// For eg boolean (true/false) units(char/byte)
			strings.ToUpper(inst.Spec.Parameters[keys[i]]) != paramValues[i] {
			msg := fmt.Sprintf("setParameters: parameter update for %s with value %s was rejected by database and instead set to %s", keys[i], inst.Spec.Parameters[keys[i]], paramValues[i])
			log.Error(err, msg)
			//Oracle does unit conversion while storing certain memory parameters like sga_target, pga_aggregate_target.
			//Thereby there is no foolproof to confirm if the parameter update silently failed. Thereby we just log the
			//parameters (whose values don't match the exact user provided values) instead of throwing an error.
			//return false, errors.New(msg)
		}
	}

	log.Info("setParameters: SQL commands executed successfully")
	return requireDatabaseRestart, nil
}

// parameterUpdateStateMachine guides the transition of the parameter update
// workflow to the next possible state based on the current state and the outcome
// of the task associated with the current state.
func (r *InstanceReconciler) parameterUpdateStateMachine(ctx context.Context, req ctrl.Request, inst v1alpha1.Instance, log logr.Logger) (ctrl.Result, error) {

	if !isParameterUpdateStateMachineEntryCondition(&inst) {
		return ctrl.Result{}, nil
	}

	// If the current parameter state is equal to the requested state skip the update
	if eq := reflect.DeepEqual(inst.Spec.Parameters, inst.Status.CurrentParameters); eq {
		return ctrl.Result{}, nil
	}

	// If the last failed parameter update is equal to the requested state skip it.
	if eq := reflect.DeepEqual(inst.Spec.Parameters, inst.Status.LastFailedParameterUpdate); eq {
		return ctrl.Result{}, nil
	}

	if result, err := r.sanityCheckTimeRange(inst, log); err != nil {
		return result, err
	}

	log.Info("parameterUpdateStateMachine: Entered state machine")
	instanceReadyCond := k8s.FindCondition(inst.Status.Conditions, k8s.Ready)
	switch instanceReadyCond.Reason {
	case k8s.CreateComplete:
		inst.Status.CurrentActiveStateMachine = controllers.ParameterUpdateStateMachine

		_, dynamicParamsRollbackState, err := fetchCurrentParameterState(ctx, r, r.DatabaseClientFactory, inst)
		if err != nil {
			msg := "parameterUpdateStateMachine: Sanity check failed for instance parameters"
			r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionFalse, k8s.ParameterUpdateRollbackInProgress, fmt.Sprintf("%s: %v", msg, err), log)
			return ctrl.Result{Requeue: true}, err
		}
		inst.Status.CurrentParameters = dynamicParamsRollbackState

		msg := "parameterUpdateStateMachine: parameter update in progress"
		r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionFalse, k8s.ParameterUpdateInProgress, msg, log)
		log.Info("parameterUpdateStateMachine: SM CreateComplete -> ParameterUpdateInProgress")

	case k8s.ParameterUpdateInProgress:
		restartRequired, err := r.setParameters(ctx, inst, log)
		if err != nil {
			msg := "parameterUpdateStateMachine: Error while setting instance parameters"
			r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionFalse, k8s.ParameterUpdateRollbackInProgress, fmt.Sprintf("%s: %v", msg, err), log)
			log.Info("parameterUpdateStateMachine: SM ParameterUpdateInProgress -> ParameterUpdateRollbackInProgress")
			return ctrl.Result{Requeue: true}, nil
		}
		if restartRequired {
			log.Info("parameterUpdateStateMachine: static parameter specified in config, scheduling restart to activate them")
			if err := controllers.BounceDatabase(ctx, r, r.DatabaseClientFactory, inst.Namespace, inst.Name, controllers.BounceDatabaseRequest{
				Sid: inst.Spec.CDBName,
			}); err != nil {
				msg := "parameterUpdateStateMachine: error while restarting database after setting static parameters"
				r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionFalse, k8s.ParameterUpdateRollbackInProgress, fmt.Sprintf("%s: %v", msg, err), log)
				log.Info("parameterUpdateStateMachine: SM ParameterUpdateInProgress -> ParameterUpdateRollbackInProgress")
				return ctrl.Result{Requeue: true}, nil
			}
		}
		r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionFalse, k8s.ParameterUpdateComplete, "", log)
		log.Info("parameterUpdateStateMachine: SM ParameterUpdateInProgress -> ParameterUpdateComplete")
		return ctrl.Result{Requeue: true}, nil

	case k8s.ParameterUpdateComplete:
		inst.Status.CurrentParameters = inst.Spec.Parameters
		msg := "parameterUpdateStateMachine: Parameter update successful"
		r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionTrue, k8s.CreateComplete, msg, log)
		inst.Status.CurrentActiveStateMachine = ""
		log.Info("parameterUpdateStateMachine: SM ParameterUpdateComplete -> CreateComplete")
		return ctrl.Result{}, nil

	case k8s.ParameterUpdateRollbackInProgress:
		if err := r.initiateRecovery(ctx, inst, inst.Status.CurrentParameters, log); err != nil {
			log.Info("parameterUpdateStateMachine: recovery failed, instance currently in irrecoverable state", "err", err)
			return ctrl.Result{}, err
		}
		inst.Status.LastFailedParameterUpdate = inst.Spec.Parameters
		msg := "parameterUpdateStateMachine: instance recovered after bad parameter update"
		r.recordEventAndUpdateStatus(ctx, &inst, v1.ConditionTrue, k8s.CreateComplete, msg, log)
		inst.Status.CurrentActiveStateMachine = ""
		log.Info("parameterUpdateStateMachine: SM ParameterUpdateRollbackInProgress -> CreateComplete")
		return ctrl.Result{}, nil
	}
	return ctrl.Result{}, nil
}

func isParameterUpdateStateMachineEntryCondition(inst *v1alpha1.Instance) bool {
	instanceReadyCond := k8s.FindCondition(inst.Status.Conditions, k8s.Ready)
	dbInstanceCond := k8s.FindCondition(inst.Status.Conditions, k8s.DatabaseInstanceReady)
	return controllers.ParameterUpdateStateMachine == inst.Status.CurrentActiveStateMachine ||
		(k8s.ConditionStatusEquals(instanceReadyCond, v1.ConditionTrue) && k8s.ConditionStatusEquals(dbInstanceCond, v1.ConditionTrue) && inst.Spec.Parameters != nil)
}

// initiateRecovery will recover the config file (which contains the static
// parameters) to the last known working copy if the static
// parameter update failed (which caused the database to be non-functional
// after a restart).
func (r *InstanceReconciler) initiateRecovery(ctx context.Context, inst v1alpha1.Instance, dynamicParams map[string]string, log logr.Logger) error {

	log.Info("initiateRecovery: initiating recovery of config file")
	if err := controllers.RecoverConfigFile(ctx, r.DatabaseClientFactory, r.Client, inst.Namespace, inst.Name, inst.Spec.CDBName); err != nil {
		msg := "initiateRecovery: error while recovering config file"
		log.Info(msg, "err", err)
		return err
	}

	if err := controllers.BounceDatabase(ctx, r, r.DatabaseClientFactory, inst.Namespace, inst.Name, controllers.BounceDatabaseRequest{
		Sid: inst.Spec.CDBName,
	}); err != nil {
		return err
	}
	log.Info("initiateRecovery: database bounced completed successfully")

	// Rollback all the dynamic parameter updates after the database has recovered
	for k, v := range dynamicParams {
		_, err := controllers.SetParameter(ctx, r.DatabaseClientFactory, r.Client, inst.Namespace, inst.Name, k, v)
		if err != nil {
			log.Error(err, "initiateRecovery: error while rolling back dynamic parameters")
			return err
		}
	}
	log.Info("initiateRecovery: rolling back of dynamic parameters completed successfully", "dynamicParams", dynamicParams)
	return nil
}

func (r *InstanceReconciler) sanityCheckTimeRange(inst v1alpha1.Instance, log logr.Logger) (ctrl.Result, error) {
	if !maintenance.HasValidTimeRanges(inst.Spec.MaintenanceWindow) {
		return ctrl.Result{}, fmt.Errorf("MaintenanceWindow specification is not valid: %+v", inst.Spec.MaintenanceWindow)
	}

	now := time.Now()

	if maintenance.InRange(inst.Spec.MaintenanceWindow, now) {
		return ctrl.Result{}, nil
	}

	nextStart, _, err := maintenance.NextWindow(inst.Spec.MaintenanceWindow, now)

	// If there is no future maintenance windows (next window), return an error.
	if err != nil {
		return ctrl.Result{}, errors.New("current time is past the maintenance time range")
	}

	// Otherwise: requeue for processing when the maintenance window opens up.
	restartWaitTime := nextStart.Sub(now)
	log.Info("parameterUpdateStateMachine: Wait time before restart ", "restartWaitTime", restartWaitTime.Seconds())
	return ctrl.Result{RequeueAfter: restartWaitTime}, errors.New("current time is not within the maintenance window")
}

func mapsToStringArray(parameterMap map[string]string) []string {
	var parameters []string
	for k, v := range parameterMap {
		parameters = append(parameters, fmt.Sprintf("%s=%s", k, v))
	}
	return parameters
}


text:
package com.github.jinahya.database.metadata.bind;

class IndexInfoTypeTest extends IntFieldEnumTest<IndexInfo.Type> {

    IndexInfoTypeTest() {
        super(IndexInfo.Type.class);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace std;

const string rel_path_to_target = "./target/";

// initialize all vectors to empty
void Convert::init()
{
    int i;
    for (i=0; i<MAX_VID; i++)
        v[i].clear();
}

// read traditional reuse table
void Convert::read_index()
{
    ifstream fin;
    string filename;
    filename = rel_path_to_target + "cluster/" + string(did) + "/" + RTP::INDEX_FILE_NAME;
    fin.open(filename.c_str());
    int fid, size, i;
    int offset;
    int vid;
    // Since in each loop iteration, fid is visited from small to large, we can guarantee that the order it's pushed into v[] is also from small to large. Therefore, in "forward.txt", in each posting, the fid is sorted.
    while (fin >> fid)
    {
        if (fid < 0) // -99999
            return; // finish reading traditional reuse table
        fin >> size;
        for (i=0; i<size; i++){
            fin >> vid >> offset;
            ForwardTableInfo e;
            e.fid = fid;
            e.offset = offset;
            v[vid].push_back(e);
        }
    }
    fin.close();
}

// convert the traditional reuse table to a forward reuse table
void Convert::output_forward_table()
{
    // statistics for fragments number in one page
    int min=99999;
    int max=0;
    int count=0;
    double avg=0;
    int id;
    ofstream fout;
    string filename;
    filename = rel_path_to_target + "cluster/" + string(did) + "/" + RTP::FORWARD_FILE_NAME;
    fout.open(filename.c_str());
    int i, j;
    for (i=0; i<MAX_VID; i++)
        if (v[i].size() > 0){
            if (v[i].size() < min)
                min = v[i].size();
            if (v[i].size() > max){
                max = v[i].size();
                id = i;
            }
            count++;
            avg += v[i].size();
            fout << i << " " << v[i].size();
            for (j=0; j<v[i].size(); j++){
                fout << " " << v[i][j].fid << " " << v[i][j].offset;
            }
            fout << endl;
        }
    fout.close();
    cout << "max fragments at page" << id << " number: " << max << endl;
    cout << "min fragments number: " << min << endl;
    cout << "avg fragments number: " << avg/count << endl;
}


text:
.class public final Landroid/provider/ContactsContract$Intents;
.super Ljava/lang/Object;
.source "ContactsContract.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/provider/ContactsContract;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Intents"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/provider/ContactsContract$Intents$Insert;
    }
.end annotation

# static fields
.field public static final ACTION_GET_MULTIPLE_PHONES:Ljava/lang/String; = "com.android.contacts.action.GET_MULTIPLE_PHONES"

.field public static final ACTION_PROFILE_CHANGED:Ljava/lang/String; = "android.provider.Contacts.PROFILE_CHANGED"

.field public static final ACTION_VOICE_SEND_MESSAGE_TO_CONTACTS:Ljava/lang/String; = "android.provider.action.VOICE_SEND_MESSAGE_TO_CONTACTS"

.field public static final ATTACH_IMAGE:Ljava/lang/String; = "com.android.contacts.action.ATTACH_IMAGE"

.field public static final CONTACTS_DATABASE_CREATED:Ljava/lang/String; = "android.provider.Contacts.DATABASE_CREATED"

.field public static final EXTRA_CREATE_DESCRIPTION:Ljava/lang/String; = "com.android.contacts.action.CREATE_DESCRIPTION"

.field public static final EXTRA_EXCLUDE_MIMES:Ljava/lang/String; = "exclude_mimes"
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final EXTRA_FORCE_CREATE:Ljava/lang/String; = "com.android.contacts.action.FORCE_CREATE"

.field public static final EXTRA_MODE:Ljava/lang/String; = "mode"
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final EXTRA_PHONE_URIS:Ljava/lang/String; = "com.android.contacts.extra.PHONE_URIS"

.field public static final EXTRA_RECIPIENT_CONTACT_CHAT_ID:Ljava/lang/String; = "android.provider.extra.RECIPIENT_CONTACT_CHAT_ID"

.field public static final EXTRA_RECIPIENT_CONTACT_NAME:Ljava/lang/String; = "android.provider.extra.RECIPIENT_CONTACT_NAME"

.field public static final EXTRA_RECIPIENT_CONTACT_URI:Ljava/lang/String; = "android.provider.extra.RECIPIENT_CONTACT_URI"

.field public static final EXTRA_TARGET_RECT:Ljava/lang/String; = "target_rect"
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final INVITE_CONTACT:Ljava/lang/String; = "com.android.contacts.action.INVITE_CONTACT"

.field public static final METADATA_ACCOUNT_TYPE:Ljava/lang/String; = "android.provider.account_type"

.field public static final METADATA_MIMETYPE:Ljava/lang/String; = "android.provider.mimetype"

.field public static final MODE_LARGE:I = 0x3
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final MODE_MEDIUM:I = 0x2
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final MODE_SMALL:I = 0x1
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final SEARCH_SUGGESTION_CLICKED:Ljava/lang/String; = "android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"

.field public static final SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED:Ljava/lang/String; = "android.provider.Contacts.SEARCH_SUGGESTION_CREATE_CONTACT_CLICKED"

.field public static final SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED:Ljava/lang/String; = "android.provider.Contacts.SEARCH_SUGGESTION_DIAL_NUMBER_CLICKED"

.field public static final SHOW_OR_CREATE_CONTACT:Ljava/lang/String; = "com.android.contacts.action.SHOW_OR_CREATE_CONTACT"

# direct methods
.method public constructor <init>()V
    .locals 0

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

    return-void
.end method


text:
// Copyright (c) 2014 Marcin Polaczyk http://mpolaczyk.pl

#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <set>
#include <string.h>
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <sysexits.h>
#include <exception>

using namespace std;

inline void coutBegin(const string& text) { cout << "=== " << text << " ===" << endl; }
inline void coutEnd() { cout << endl; }
inline void coutE(const string& text) { cout << ' ' << text; }
inline void coutH()
{
	cout << "Usage: " << endl <<
		"--voice <voice> --text \"<text>\"" << endl <<
		"Where <voice> is directory name with wav files and <text> is a text to process." << endl <<
		"--listv" << endl <<
		"To list available voices";
}

bool modeSay = false;
bool modeListVoices = false;

string selfPath;

string get_selfPath()
{
    char buff[1024];
    ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
    if (len != -1) {
      buff[len] = '\0';
	  string ans(buff);
      return ans.substr(0, ans.length() - 5);
    } else {
     /* handle error condition */
    }
}

void getUTF8Char(const int& i, const string& word, string& outChar, int& outLen)
{
	int num = 0;
	int position = 7;
	while ((word[i] & (1 << position)) == (1 << position))
	{
		num++;
		position--;
	}

	outLen = (num == 0 ? 1 : num);
	outChar = word.substr(i, outLen);
}

bool mergeSounds(string& word, const string& voice, set<string>& sounds)
{
    string cmd = selfPath + "wavmerge ";
    cout << endl;

	// Current combination
	string current = "";
	// Next combination
	string next = "";

	int di;

    for ( int i = 0 ; i <= word.length(); i+=di)
    {
		di = 0;

		// If current combination is empty, get first not processed character
		if (current == "")
		{
			getUTF8Char(i, word, current, di);
		}

		// Check if current combination exists
		if(current != "" && sounds.find(current) != sounds.end())
		{
			// If we have more characters
			int din = 0;
			if(i+di < word.length())
			{
				// Build next combination
				string x;
				getUTF8Char(i+di, word, x, din);
				next = current + x;
			}
			else
			{
				next = "";
			}

			// Check if next combination exists
			if(din > 0 && sounds.find(next) != sounds.end())
			{
				// Save next combination to current and continue
				current = next;
				di += din;
			}
			else
			{
				// Send combination to merge and continue
				cmd = cmd + " " + selfPath + voice + "/" + current + ".wav";
				current = "";
				next = "";
			}
		}

    }
	cout << endl << cmd << endl;
    system(cmd.c_str()); // UNSECURE: Directory traversal / Command Injection
	// merge.wav lands in working directory, move this to bin
    cmd = "mv merge.wav " + selfPath + voice + "/" + word + ".wav";
    system(cmd.c_str()); // UNSECURE: Directory traversal / Command Injection
    return true;
}

bool tryParseParams(string& voice, string& text, int& argc, char *argv[])
{
	// Check params
	if(argc == 2)
	{
		modeListVoices = (strcmp(argv[1], "--listv") == 0);
		return modeListVoices;
	}
	else if(argc == 5)
	{
		modeSay = (strcmp(argv[1], "--voice") == 0 || strcmp(argv[3], "--text") == 0);
		if (modeSay)
		{
			voice = argv[2];
			text = argv[4];
			return true;
		}
	}

	return false;
}

bool listVoices()
{
	// Get all voices (directories)
	string cmd = "find " + selfPath + " -type d > " + selfPath + "/voices";
	system(cmd.c_str()); // UNSECURE: Directory traversal / Command Injection

	ifstream voicesFile(selfPath + "/voices", ifstream::in);
	if (voicesFile.is_open())
	{
		// Each line has sound name, store it
		string line;
		int x = selfPath.length();
		while (getline(voicesFile, line))
		{
			if(line.length() > 0)
			{
				cout << line.substr(x, line.length() - x) << endl;
			}
		}
		voicesFile.close();
	}
}

bool loadVoice(string& voice, set<string>& sounds)
{
    // Get all waves from directory and save to file
    coutBegin("Looking for sounds of: '" + voice + "'");

	string cmd = "find " + selfPath + voice + " -type f -name \"*.wav\" -exec basename {} .wav \\; > " + selfPath + voice + "/sounds";
	system(cmd.c_str()); // UNSECURE: Directory traversal / Command Injection

	ifstream soundsFile(selfPath + voice + "/sounds", ifstream::in);
	if (soundsFile.is_open())
	{
		// Each line has sound name, store it
		string line;
		while (getline(soundsFile, line))
		{
			coutE(line);
			sounds.insert(line);
		}
		soundsFile.close();
	}

	bool isEmpty = sounds.empty();
	if(isEmpty) { coutE("No sounds available..."); }

    coutEnd();

	return !isEmpty;
}

void splitTextIntoWords(string& text, vector<string>& words)
{
	// Split text into words
	coutBegin("Parsing text into words");

	istringstream iss(text);
	string word;
	while (iss >> word)
	{
		coutE(word);
		words.push_back(word);
	}

	coutEnd();
}

bool createWords(string& voice, vector<string>& words, set<string>& sounds)
{
	// Create wave files for words
	coutBegin("Creating word sounds");
	for(auto word : words)
	{
		if (sounds.find(word) == sounds.end())
		{
			coutE(word);
			if (!mergeSounds(word, voice, sounds)) { return false; }
			sounds.insert(word);
		}
	}
	coutEnd();
	return true;
}

void playWords(string& voice, vector<string>& words)
{
	// Play words
	coutBegin("Playing words");
	string cmd;
	for(auto word : words)
	{
		coutE(word);
		cmd = cmd + "aplay " + selfPath + voice + "/" + word + ".wav; ";
	}
	system(cmd.c_str()); // UNSECURE: Directory traversal / Command Injection
	coutEnd();
}

int main(int argc, char *argv[])
{
	selfPath = get_selfPath();

	string voice;
	string text;
	set<string> sounds;
	set<string> voices;
	vector<string> words;

	try
	{
		if(!tryParseParams(voice, text, argc, argv))
		{
			coutH();
			return EX_USAGE;
		}

		if(modeListVoices)
		{
			listVoices();
		}
		else if(modeSay)
		{
			if(!loadVoice(voice, sounds))
			{
				return EX_OK;
			}

			splitTextIntoWords(text, words);

			if(!createWords(voice, words, sounds))
			{
				return EX_OK;
			}

			playWords(voice, words);
		}
  	}
	catch(exception& e)
	{
		cout << endl << endl << "Exception: " << e.what() << endl;
	}

	return EX_OK;
}


text:
<?php

//Model Class

require_once "lib/enjoyClassBase/modelBase.php";
require_once "applications/hormiga/modules/avances/models/table_avances.php";

class avancesModel extends modelBase {

    var $tables="avances";
    var $usuarios_proyectosModel;
    var $usuarios_proyectos_tareasModel;

    function __construct($dataRep, &$config,&$incomingModels=array()) {
        parent::__construct($dataRep, $config,$incomingModels);
        $table=new table_avances();
        $this->fieldsConfig=$table->fieldsConfig;
        $this->primaryKey=$table->primaryKey;

        $tareasModel=$this->getModuleModelInstance("tareas");
        $this->usuarios_proyectosModel=$this->getModuleModelInstance("usuarios_proyectos");
        $this->usuarios_proyectos_tareasModel=$this->getModuleModelInstance("usuarios_proyectos_tareas");

        $this->label=array(
            "es_es"=>"Avances",
        );

        $this->foreignKeys = array (
            "id_tareas" => array(
                "model"=>&$tareasModel,
                "keyField"=>"tareas.id",
                "dataField"=>"_CONCAT(proyectos.proyecto,'_',tareas.tarea)",
             ),
        );

//        $this->subModels=array( //For many to many relations for example
//            0=>array(
//                "model"=>&$tareasModel ,
//                "linkerField"=>$this->primaryKey,
//                "linkedField"=>"external field that references this primary key",
//                "linkedDataField"=>"similar as a foreignKey dataField",
//                "type"=>"multiple",
//            ),
//        );

//        $this->dependents=array(
//            "id"=>array(
//                0=>array(
//                  "mod"=>"someModule",
//                    "act"=>"index",
//                    "keyField"=>"field of the dependent table that references here",
//                    "label"=>array(
//                        "es_es" =>"DependentCaption",
//                    ),
//                ),
//            ),
//        );

    }

    function traerTareasDisponibles() {

        //filtrar solo las tareas activas de los proyectos activos

        $userId=$this->usuarios_proyectosModel->usersModel->getId();

        $options['fields'][]='proyectos.proyecto';
        $options['fields'][]='tareas.id AS id_tarea';
        $options['fields'][]='tareas.tarea';
        $options['where'][]="usuarios_proyectos.id_users='$userId'";
        $options['where'][]="tareas.id IN (SELECT id_process FROM tareas_bpm WHERE tareas_bpm.id_process=tareas.id AND 'activado' IN ( SELECT tareas_bpm.state FROM tareas_bpm WHERE tareas_bpm.id IN ( SELECT MAX(id) FROM tareas_bpm WHERE tareas_bpm.id_process=tareas.id ) ) GROUP BY id_process )";
        $options['where'][]="proyectos.id IN (SELECT id_process FROM proyectos_bpm WHERE proyectos_bpm.id_process=proyectos.id AND 'activado' IN ( SELECT proyectos_bpm.state FROM proyectos_bpm WHERE proyectos_bpm.id IN ( SELECT MAX(id) FROM proyectos_bpm WHERE proyectos_bpm.id_process=proyectos.id ) ) GROUP BY id_process )";
        $result=$this->usuarios_proyectos_tareasModel->fetch($options);
        $tareas=$result["results"];
        return $tareas;

        //return $this->usuarios_proyectos_tareasModel->quickfetch("",$options);

    }

}


text:
"""
By default, Biohub will expose two URL prefixes `^` and `^/api`, where
developers can register their own urlpatterns by using `register_api` and
`register_default`. This design can prevent plugin authors from directly
modifying the main urlconf.
"""

from django.conf.urls import include, url

class UrlProxy(object):

    def __init__(self, prefix, name=None):
        self.__prefix = prefix
        self.__urls = []
        self.__name = name

    def register(self, prefix, urls, namespace=None):
        """
        Register a list of urlpatterns with given prefix and namespace.
        """
        self.__urls.append(
            url(prefix, include((urls, namespace))))

    @property
    def name(self):
        return self.__name

    @property
    def urls(self):
        return self.__urls

    @property
    def prefix(self):
        return self.__prefix

APIUrlProxy = UrlProxy(r'^api/', 'api')
DefaultUrlProxy = UrlProxy(r'^', 'default')

register_api = APIUrlProxy.register
register_default = DefaultUrlProxy.register

urlpatterns = []

for proxy in (APIUrlProxy, DefaultUrlProxy):
    urlpatterns.append(
        url(proxy.prefix, include(proxy.urls, namespace=proxy.name)))


text:
#ifndef WKView_h
#define WKView_h

#include <WebKit2/WKBase.h>

typedef struct _Evas Evas;

#ifdef __cplusplus
extern "C" {
#endif

WK_EXPORT WKViewRef WKViewCreate(Evas* canvas, WKContextRef context, WKPageGroupRef pageGroup);

WK_EXPORT WKViewRef WKViewCreateWithFixedLayout(Evas* canvas, WKContextRef context, WKPageGroupRef pageGroup);

WK_EXPORT WKPageRef WKViewGetPage(WKViewRef view);

#ifdef __cplusplus
}
#endif

#endif /* WKView_h */


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"
									 xmlns:dc="http://purl.org/dc/elements/1.1/"
									 xmlns:dcterms="http://purl.org/dc/terms/"
									 xmlns:dcmitype="http://purl.org/dc/dcmitype/"
									 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<dc:title>{@HtmlEncHelpTitle}</dc:title>
	<dc:creator>{@HtmlEncVendorName}</dc:creator>
	<dc:description>{@HtmlEncCopyrightText}</dc:description>
	<cp:lastModifiedBy>Sandcastle Help File Builder</cp:lastModifiedBy>
	<cp:revision>1</cp:revision>
	<dcterms:created xsi:type="dcterms:W3CDTF">{@BuildDate:yyyy-MM-ddTHH:mm:ssK}</dcterms:created>
</cp:coreProperties>


text:
.class Lmeizu/samba/client/SambaClientManager$ListenerTransport$1;
.super Landroid/os/Handler;
.source "SambaClientManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lmeizu/samba/client/SambaClientManager$ListenerTransport;-><init>(Lmeizu/samba/client/SambaClientManager;Lmeizu/samba/client/SambaStatusListener;Landroid/os/Looper;)V
.end annotation

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

# instance fields
.field final synthetic this$1:Lmeizu/samba/client/SambaClientManager$ListenerTransport;

.field final synthetic val$this$0:Lmeizu/samba/client/SambaClientManager;

# direct methods
.method constructor <init>(Lmeizu/samba/client/SambaClientManager$ListenerTransport;Lmeizu/samba/client/SambaClientManager;)V
    .locals 0

    .prologue
    .line 78
    iput-object p1, p0, Lmeizu/samba/client/SambaClientManager$ListenerTransport$1;->this$1:Lmeizu/samba/client/SambaClientManager$ListenerTransport;

    iput-object p2, p0, Lmeizu/samba/client/SambaClientManager$ListenerTransport$1;->val$this$0:Lmeizu/samba/client/SambaClientManager;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 1
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    .line 81
    iget-object v0, p0, Lmeizu/samba/client/SambaClientManager$ListenerTransport$1;->this$1:Lmeizu/samba/client/SambaClientManager$ListenerTransport;

    # invokes: Lmeizu/samba/client/SambaClientManager$ListenerTransport;->_handleMessage(Landroid/os/Message;)V
    invoke-static {v0, p1}, Lmeizu/samba/client/SambaClientManager$ListenerTransport;->access$000(Lmeizu/samba/client/SambaClientManager$ListenerTransport;Landroid/os/Message;)V

    .line 82
    return-void
.end method


text:
package com.idp.web.generator.util;

import org.apache.commons.lang.StringUtils;

public class FieldUtils {

	public static String getNullAble(String nullable){
	    if (("YES".equals(nullable)) || ("yes".equals(nullable)) || ("y".equals(nullable)) || ("Y".equals(nullable)) || ("f".equals(nullable))) {
	      return "Y";
	    }
	    if (("NO".equals(nullable)) || ("N".equals(nullable)) || ("no".equals(nullable)) || ("n".equals(nullable)) || ("t".equals(nullable))) {
	      return "N";
	    }
	    return null;
	}

	public static String getNullString(String nullable){
	    if (StringUtils.isEmpty(nullable)) {
	    	return "";
	    }

	    return nullable;
	}

	public static String formatField(String field){
		String[] strs = field.split("_");
	    field = "";
	    int m = 0;
	    for (int length = strs.length; m < length; m++) {
	    	if (m > 0) {
	    		String tempStr = strs[m].toLowerCase();
	    		tempStr = tempStr.substring(0, 1).toUpperCase() + tempStr.substring(1, tempStr.length());

	    		field = field + tempStr;
	    	}
	    	else {
	    		field = field + strs[m].toLowerCase();
	    	}
	    }

	    return field;
	}

	public static String formatFieldCapital(String field){
	    String[] strs = field.split("_");
	    field = "";
	    int m = 0;
	    for (int length = strs.length; m < length; m++) {
	    	if (m > 0) {
	    		String tempStr = strs[m].toLowerCase();
	    		tempStr = tempStr.substring(0, 1).toUpperCase() + tempStr.substring(1, tempStr.length());

	    		field = field + tempStr;
	    	}
	    	else {
	    		field = field + strs[m].toLowerCase();
	    	}
	    }
	    field = field.substring(0, 1).toUpperCase() + field.substring(1);

	    return field;
	}

	public static String getInitialSmall(String str){
	    if (StringUtils.isNotBlank(str)) {
	      str = str.substring(0, 1).toLowerCase() + str.substring(1);
	    }

	    return str;
	}

	public static String formatDataType(String dataType, String precision, String scale){

	    if (dataType.contains("char")){
	    	dataType = "String";
	    }
	    else if (dataType.contains("text")){
	    	dataType = "String";
	    }
	    else if (dataType.contains("bigint")){
	        dataType = "Long";
	    }
	    else if (dataType.contains("int")){
	    	dataType = "Integer";
	    }
	    else if (dataType.contains("float")){
	    	dataType = "Float";
	    }
	    else if (dataType.contains("double")){
	    	dataType = "Double";
	    }
	    else if (dataType.contains("number")) {
	    	if ((StringUtils.isNotEmpty(scale)) && (Integer.parseInt(scale) > 0))
	    		dataType = "BigDecimal";
	    	else if ((StringUtils.isNotEmpty(precision)) && (Integer.parseInt(precision) > 10)){
	    		dataType = "Long";
	    	}
	    	else{
	    		dataType = "Integer";
	    	}
	    }
	    else if (dataType.contains("decimal")){
	    	dataType = "BigDecimal";
	    }
	    else if (dataType.contains("date")){
	    	dataType = "Date";
	    }
	    else if (dataType.contains("time")){
	    	dataType = "Date";
	    }
	    else if (dataType.contains("blob")){
	    	//dataType = "java.sql.Blob";
	    	dataType = "String";
	    }
	    else if (dataType.contains("clob")){
	    	//dataType = "java.sql.Clob";
	    	dataType = "String";
	    }
	    else if (dataType.contains("numeric")){
	    	dataType = "BigDecimal";
	    }
	    else {
	    	dataType = "java.lang.Object";;
	    }

	    return dataType;
	}

}


text:
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.SecurityCenter.V1;
using sys = System;

namespace Google.Cloud.SecurityCenter.V1
{
    /// Resource name for the <c>NotificationConfig</c> resource.
    public sealed partial class NotificationConfigName : gax::IResourceName, sys::IEquatable<NotificationConfigName>
    {
        /// The possible contents of <see cref="NotificationConfigName"/>.
        public enum ResourceNameType
        {
            /// An unparsed resource name.
            Unparsed = 0,

            ///
            /// A resource name with pattern <c>organizations/{organization}/notificationConfigs/{notification_config}</c>
            /// .
            ///
            OrganizationNotificationConfig = 1,
        }

        private static gax::PathTemplate s_organizationNotificationConfig = new gax::PathTemplate("organizations/{organization}/notificationConfigs/{notification_config}");

        /// Creates a <see cref="NotificationConfigName"/> containing an unparsed resource name.
        /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
        /// <returns>
        /// A new instance of <see cref="NotificationConfigName"/> containing the provided
        /// <paramref name="unparsedResourceName"/>.
        /// </returns>
        public static NotificationConfigName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
            new NotificationConfigName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));

        ///
        /// Creates a <see cref="NotificationConfigName"/> with the pattern
        /// <c>organizations/{organization}/notificationConfigs/{notification_config}</c>.
        ///
        /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="notificationConfigId">
        /// The <c>NotificationConfig</c> ID. Must not be <c>null</c> or empty.
        /// </param>
        /// <returns>A new instance of <see cref="NotificationConfigName"/> constructed from the provided ids.</returns>
        public static NotificationConfigName FromOrganizationNotificationConfig(string organizationId, string notificationConfigId) =>
            new NotificationConfigName(ResourceNameType.OrganizationNotificationConfig, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), notificationConfigId: gax::GaxPreconditions.CheckNotNullOrEmpty(notificationConfigId, nameof(notificationConfigId)));

        ///
        /// Formats the IDs into the string representation of this <see cref="NotificationConfigName"/> with pattern
        /// <c>organizations/{organization}/notificationConfigs/{notification_config}</c>.
        ///
        /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="notificationConfigId">
        /// The <c>NotificationConfig</c> ID. Must not be <c>null</c> or empty.
        /// </param>
        /// <returns>
        /// The string representation of this <see cref="NotificationConfigName"/> with pattern
        /// <c>organizations/{organization}/notificationConfigs/{notification_config}</c>.
        /// </returns>
        public static string Format(string organizationId, string notificationConfigId) =>
            FormatOrganizationNotificationConfig(organizationId, notificationConfigId);

        ///
        /// Formats the IDs into the string representation of this <see cref="NotificationConfigName"/> with pattern
        /// <c>organizations/{organization}/notificationConfigs/{notification_config}</c>.
        ///
        /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="notificationConfigId">
        /// The <c>NotificationConfig</c> ID. Must not be <c>null</c> or empty.
        /// </param>
        /// <returns>
        /// The string representation of this <see cref="NotificationConfigName"/> with pattern
        /// <c>organizations/{organization}/notificationConfigs/{notification_config}</c>.
        /// </returns>
        public static string FormatOrganizationNotificationConfig(string organizationId, string notificationConfigId) =>
            s_organizationNotificationConfig.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(notificationConfigId, nameof(notificationConfigId)));

        ///
        /// Parses the given resource name string into a new <see cref="NotificationConfigName"/> instance.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description><c>organizations/{organization}/notificationConfigs/{notification_config}</c></description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="notificationConfigName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <returns>The parsed <see cref="NotificationConfigName"/> if successful.</returns>
        public static NotificationConfigName Parse(string notificationConfigName) => Parse(notificationConfigName, false);

        ///
        /// Parses the given resource name string into a new <see cref="NotificationConfigName"/> instance; optionally
        /// allowing an unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description><c>organizations/{organization}/notificationConfigs/{notification_config}</c></description>
        /// </item>
        /// </list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="notificationConfigName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <returns>The parsed <see cref="NotificationConfigName"/> if successful.</returns>
        public static NotificationConfigName Parse(string notificationConfigName, bool allowUnparsed) =>
            TryParse(notificationConfigName, allowUnparsed, out NotificationConfigName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");

        ///
        /// Tries to parse the given resource name string into a new <see cref="NotificationConfigName"/> instance.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description><c>organizations/{organization}/notificationConfigs/{notification_config}</c></description>
        /// </item>
        /// </list>
        /// </remarks>
        /// <param name="notificationConfigName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="NotificationConfigName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string notificationConfigName, out NotificationConfigName result) =>
            TryParse(notificationConfigName, false, out result);

        ///
        /// Tries to parse the given resource name string into a new <see cref="NotificationConfigName"/> instance;
        /// optionally allowing an unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet">
        /// <item>
        /// <description><c>organizations/{organization}/notificationConfigs/{notification_config}</c></description>
        /// </item>
        /// </list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="notificationConfigName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="NotificationConfigName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string notificationConfigName, bool allowUnparsed, out NotificationConfigName result)
        {
            gax::GaxPreconditions.CheckNotNull(notificationConfigName, nameof(notificationConfigName));
            gax::TemplatedResourceName resourceName;
            if (s_organizationNotificationConfig.TryParseName(notificationConfigName, out resourceName))
            {
                result = FromOrganizationNotificationConfig(resourceName[0], resourceName[1]);
                return true;
            }
            if (allowUnparsed)
            {
                if (gax::UnparsedResourceName.TryParse(notificationConfigName, out gax::UnparsedResourceName unparsedResourceName))
                {
                    result = FromUnparsed(unparsedResourceName);
                    return true;
                }
            }
            result = null;
            return false;
        }

        private NotificationConfigName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string notificationConfigId = null, string organizationId = null)
        {
            Type = type;
            UnparsedResource = unparsedResourceName;
            NotificationConfigId = notificationConfigId;
            OrganizationId = organizationId;
        }

        ///
        /// Constructs a new instance of a <see cref="NotificationConfigName"/> class from the component parts of
        /// pattern <c>organizations/{organization}/notificationConfigs/{notification_config}</c>
        ///
        /// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="notificationConfigId">
        /// The <c>NotificationConfig</c> ID. Must not be <c>null</c> or empty.
        /// </param>
        public NotificationConfigName(string organizationId, string notificationConfigId) : this(ResourceNameType.OrganizationNotificationConfig, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), notificationConfigId: gax::GaxPreconditions.CheckNotNullOrEmpty(notificationConfigId, nameof(notificationConfigId)))
        {
        }

        /// The <see cref="ResourceNameType"/> of the contained resource name.
        public ResourceNameType Type { get; }

        ///
        /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
        /// unparsed resource name.
        ///
        public gax::UnparsedResourceName UnparsedResource { get; }

        ///
        /// The <c>NotificationConfig</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
        /// resource name.
        ///
        public string NotificationConfigId { get; }

        ///
        /// The <c>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
        /// name.
        ///
        public string OrganizationId { get; }

        /// Whether this instance contains a resource name with a known pattern.
        public bool IsKnownPattern => Type != ResourceNameType.Unparsed;

        /// The string representation of the resource name.
        /// <returns>The string representation of the resource name.</returns>
        public override string ToString()
        {
            switch (Type)
            {
                case ResourceNameType.Unparsed: return UnparsedResource.ToString();
                case ResourceNameType.OrganizationNotificationConfig: return s_organizationNotificationConfig.Expand(OrganizationId, NotificationConfigId);
                default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
            }
        }

        /// Returns a hash code for this resource name.
        public override int GetHashCode() => ToString().GetHashCode();

        /// <inheritdoc/>
        public override bool Equals(object obj) => Equals(obj as NotificationConfigName);

        /// <inheritdoc/>
        public bool Equals(NotificationConfigName other) => ToString() == other?.ToString();

        /// <inheritdoc/>
        public static bool operator ==(NotificationConfigName a, NotificationConfigName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);

        /// <inheritdoc/>
        public static bool operator !=(NotificationConfigName a, NotificationConfigName b) => !(a == b);
    }

    /// Resource name for the <c>Topic</c> resource.
    public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName>
    {
        /// The possible contents of <see cref="TopicName"/>.
        public enum ResourceNameType
        {
            /// An unparsed resource name.
            Unparsed = 0,

            /// A resource name with pattern <c>projects/{project}/topics/{topic}</c>.
            ProjectTopic = 1,
        }

        private static gax::PathTemplate s_projectTopic = new gax::PathTemplate("projects/{project}/topics/{topic}");

        /// Creates a <see cref="TopicName"/> containing an unparsed resource name.
        /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
        /// <returns>
        /// A new instance of <see cref="TopicName"/> containing the provided <paramref name="unparsedResourceName"/>.
        /// </returns>
        public static TopicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
            new TopicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));

        ///
        /// Creates a <see cref="TopicName"/> with the pattern <c>projects/{project}/topics/{topic}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns>
        public static TopicName FromProjectTopic(string projectId, string topicId) =>
            new TopicName(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));

        ///
        /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern
        /// <c>projects/{project}/topics/{topic}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>
        /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c>
        /// .
        /// </returns>
        public static string Format(string projectId, string topicId) => FormatProjectTopic(projectId, topicId);

        ///
        /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern
        /// <c>projects/{project}/topics/{topic}</c>.
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
        /// <returns>
        /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c>
        /// .
        /// </returns>
        public static string FormatProjectTopic(string projectId, string topicId) =>
            s_projectTopic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)));

        /// Parses the given resource name string into a new <see cref="TopicName"/> instance.
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
        /// </remarks>
        /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <returns>The parsed <see cref="TopicName"/> if successful.</returns>
        public static TopicName Parse(string topicName) => Parse(topicName, false);

        ///
        /// Parses the given resource name string into a new <see cref="TopicName"/> instance; optionally allowing an
        /// unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <returns>The parsed <see cref="TopicName"/> if successful.</returns>
        public static TopicName Parse(string topicName, bool allowUnparsed) =>
            TryParse(topicName, allowUnparsed, out TopicName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");

        ///
        /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
        /// </remarks>
        /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string topicName, out TopicName result) => TryParse(topicName, false, out result);

        ///
        /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance; optionally
        /// allowing an unparseable resource name.
        ///
        /// <remarks>
        /// To parse successfully, the resource name must be formatted as one of the following:
        /// <list type="bullet"><item><description><c>projects/{project}/topics/{topic}</c></description></item></list>
        /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
        /// </remarks>
        /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param>
        /// <param name="allowUnparsed">
        /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
        /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
        /// specified.
        /// </param>
        /// <param name="result">
        /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed.
        /// </param>
        /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
        public static bool TryParse(string topicName, bool allowUnparsed, out TopicName result)
        {
            gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName));
            gax::TemplatedResourceName resourceName;
            if (s_projectTopic.TryParseName(topicName, out resourceName))
            {
                result = FromProjectTopic(resourceName[0], resourceName[1]);
                return true;
            }
            if (allowUnparsed)
            {
                if (gax::UnparsedResourceName.TryParse(topicName, out gax::UnparsedResourceName unparsedResourceName))
                {
                    result = FromUnparsed(unparsedResourceName);
                    return true;
                }
            }
            result = null;
            return false;
        }

        private TopicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string topicId = null)
        {
            Type = type;
            UnparsedResource = unparsedResourceName;
            ProjectId = projectId;
            TopicId = topicId;
        }

        ///
        /// Constructs a new instance of a <see cref="TopicName"/> class from the component parts of pattern
        /// <c>projects/{project}/topics/{topic}</c>
        ///
        /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
        /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param>
        public TopicName(string projectId, string topicId) : this(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId)))
        {
        }

        /// The <see cref="ResourceNameType"/> of the contained resource name.
        public ResourceNameType Type { get; }

        ///
        /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
        /// unparsed resource name.
        ///
        public gax::UnparsedResourceName UnparsedResource { get; }

        ///
        /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string ProjectId { get; }

        ///
        /// The <c>Topic</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
        ///
        public string TopicId { get; }

        /// Whether this instance contains a resource name with a known pattern.
        public bool IsKnownPattern => Type != ResourceNameType.Unparsed;

        /// The string representation of the resource name.
        /// <returns>The string representation of the resource name.</returns>
        public override string ToString()
        {
            switch (Type)
            {
                case ResourceNameType.Unparsed: return UnparsedResource.ToString();
                case ResourceNameType.ProjectTopic: return s_projectTopic.Expand(ProjectId, TopicId);
                default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
            }
        }

        /// Returns a hash code for this resource name.
        public override int GetHashCode() => ToString().GetHashCode();

        /// <inheritdoc/>
        public override bool Equals(object obj) => Equals(obj as TopicName);

        /// <inheritdoc/>
        public bool Equals(TopicName other) => ToString() == other?.ToString();

        /// <inheritdoc/>
        public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);

        /// <inheritdoc/>
        public static bool operator !=(TopicName a, TopicName b) => !(a == b);
    }

    public partial class NotificationConfig
    {
        ///
        /// <see cref="gcsv::NotificationConfigName"/>-typed view over the <see cref="Name"/> resource name property.
        ///
        public gcsv::NotificationConfigName NotificationConfigName
        {
            get => string.IsNullOrEmpty(Name) ? null : gcsv::NotificationConfigName.Parse(Name, allowUnparsed: true);
            set => Name = value?.ToString() ?? "";
        }

        ///
        /// <see cref="TopicName"/>-typed view over the <see cref="PubsubTopic"/> resource name property.
        ///
        public TopicName PubsubTopicAsTopicName
        {
            get => string.IsNullOrEmpty(PubsubTopic) ? null : TopicName.Parse(PubsubTopic, allowUnparsed: true);
            set => PubsubTopic = value?.ToString() ?? "";
        }
    }
}


text:
{% extends "base.html" %}
{% from "layout/breadcrumbs.html" import breadcrumbs %}
{% from "layout/helpers.html" import sectiontitle %}

{% block page_title %}
    {% if not  errors %}
        {{ _('Create entry on {part} : Participation : Mozilla Labs')|f(part=challenge.title) }}
    {% else %}
        {{ _('Entry failed: Create entry on {part} : Participation : Mozilla Labs')|f(part=challenge.title) }}
    {% endif %}
{% endblock %}

{% block page_id %}challenge_create{% endblock %}
{% block section_class %}projects{% endblock %}

{% block breadcrumbs %}
{{ breadcrumbs(
    (url('innovate_splash'), _('Mozilla Labs Home')),
    (url('projects_programs'), _('Programs')),
    (url('projects_show', slug=project.slug), project.name),
    (challenge.get_absolute_url(), challenge.title),
    last=_('Create entry')) }}
{% endblock %}

{% block content %}
{{ sectiontitle(_('Create entry on {part}')|f(part=challenge.title)) }}

        {% if errors %}

Errors

            {% for i, v in errors.iteritems() %}

                {{ i|title|replace('_', ' ') }} - {{ v|lower|replace('*', '') }}

            {% endfor %}

        {% endif %}
        <form action="{{ url('entry_create', project=project.slug, slug=challenge.slug) }}" method="post">
            {{ csrf()|safe }}

                {{ _('Title') }}
                {{ form.title }}

                {{ _('Summary') }}
                {{ _('Think of this as an elevator pitch. Keep it short and sweet - under 200 characters') }}
                {{ form.brief_description }}

                {{ _('Description') }}
                {{ form.description }}

                {{ _('Created by') }}
                {{ _('Hold down "Control", or "Command" on a Mac, to select more than one. And don\'t forget to add yourself!') }}
                {{ form.created_by }}

            <button class="submit sans" type="submit">{{ _('Create entry') }}</button>
        </form>

{% endblock %}


text:
using System;
using System.IO;
using System.Windows.Forms;

using System.Net;
using System.IO.Compression;

namespace PKHeX.WinForms
{
    public partial class Main : Form
    {
        public void DownloadMGDB(object o, EventArgs e)
        {
            if (Directory.Exists(MGDatabasePath))
            {
                DialogResult dialogResult = MessageBox.Show("Update MGDB?", "MGDB already exists!", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    DeleteDirectory(MGDatabasePath); // Adding events will be handled by the next conditional
                }
            }
            if (!Directory.Exists(MGDatabasePath))
            {
                DialogResult latestCommit = MessageBox.Show("Download the entire database, which includes past generation events?\nSelecting No will download only the public release of the database.", "Download entire database?", MessageBoxButtons.YesNo);
                if (latestCommit == DialogResult.Yes)
                {
                    string mgdbURL = @"https://github.com/projectpokemon/EventsGallery/archive/master.zip";

                    WebClient client = new WebClient();

                    string mgdbZipPath = @"mgdb.zip";
                    client.DownloadFile(new Uri(mgdbURL), mgdbZipPath);
                    ZipFile.ExtractToDirectory(mgdbZipPath, MGDatabasePath);
                    File.Delete("mgdb.zip");
                    DeleteDirectory(Path.Combine(MGDatabasePath, "EventsGallery-master", "Unreleased"));
                    DeleteDirectory(Path.Combine(MGDatabasePath, "EventsGallery-master", "Extras"));
                    File.Delete(Path.Combine(MGDatabasePath, "EventsGallery-master", ".gitignore"));
                    File.Delete(Path.Combine(MGDatabasePath, "EventsGallery-master", "README.md"));
                    WinFormsUtil.Alert("Download Finished");
                }
                else
                {
                    WebClient client = new WebClient();
                    string json_data = DownloadString("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest");
                    string mgdbURL = json_data.Split(new string[] { "browser_download_url" }, StringSplitOptions.None)[1].Substring(3).Split('"')[0];
                    Console.WriteLine(mgdbURL);
                    string mgdbZipPath = @"mgdb.zip";
                    client.DownloadFile(new Uri(mgdbURL), mgdbZipPath);
                    ZipFile.ExtractToDirectory(mgdbZipPath, MGDatabasePath);
                    File.Delete("mgdb.zip");
                    WinFormsUtil.Alert("Download Finished");
                }
            }
        }

        public static string DownloadString(string address)
        {
            using (WebClient client = new WebClient())
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/projectpokemon/EventsGallery/releases/latest");
                request.Method = "GET";
                request.UserAgent = "PKHeX-Auto-Legality-Mod";
                request.Accept = "application/json";
                WebResponse response = request.GetResponse(); //Error Here
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string result = reader.ReadToEnd();

                return result;
            }
        }
        public static void DeleteDirectory(string target_dir)
        {
            string[] files = Directory.GetFiles(target_dir);
            string[] dirs = Directory.GetDirectories(target_dir);

            foreach (string file in files)
            {
                File.SetAttributes(file, FileAttributes.Normal);
                File.Delete(file);
            }

            foreach (string dir in dirs)
            {
                DeleteDirectory(dir);
            }

            Directory.Delete(target_dir, false);
        }
    }
}


text:
/*jslint node: true */
"use strict";

var request = require('request'),
    areas = require('./areas'),
    categories = require('./categories'),
    collections = require('./collections'),
    posts = require('./posts');

module.exports = {
    areas : areas,
    categories : categories,
    collections : collections,
    posts : posts
};


text:
package com.github.wenhao.tdd.pos.domain;

public class DiscountItem {

    private String name;
    private Integer rate;

    public DiscountItem(String name, Integer rate) {
        this.name = name;
        this.rate = rate;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getRate() {
        return rate;
    }

    public void setRate(Integer rate) {
        this.rate = rate;
    }
}


text:
import logging, functools
import pyev
###

L = logging.getLogger("idlework")

###

def _execute(w):
	# Launch worker safely
	try:
		w()
	# except SystemExit, e:
	# 	L.debug("Idle worker requested system exit")
	# 	self.Terminate(e.code)
	except:
		L.exception("Exception during idle worker")

###

class idlework_appmixin(object):

	def __init__(self):
		self.idle_queue = []
		self.idle_watcher = pyev.Idle(self.loop, self.__idle_cb)

	def stop_idlework(self):
		self.idle_watcher.stop()
		self.idle_watcher = None

		while len(self.idle_queue) > 0:
			w = self.idle_queue.pop(0)
			_execute(w)

	def __del__(self):
		try:
			self.idle_watcher.stop()
		except AttributeError:
			pass

	def __idle_cb(self, watcher, revents):
		w = self.idle_queue.pop(0)

		if len(self.idle_queue) == 0:
			self.idle_watcher.stop()

		_execute(w)

	def add_idlework(self, worker, *args, **kwargs):
		'''
		Add worker (callable) to idle work queue.
		@param worker: Callable that will be invoked when applicaiton loops idles
		@param *args: Optional positional arguments that will be supplied to worker callable
		@param **kwargs: Optional keywork arguments that will be supplied to worker callable
		'''
		if len(args) > 0 or len(kwargs) > 0:
			worker = functools.partial(worker, *args, **kwargs)

		self.idle_queue.append(worker)
		self.idle_watcher.start()


text:
"""Stops a Launchpad program."""

import functools
import os
import signal
import sys
from typing import Union

from absl import logging
from launchpad import context
from launchpad import flags as lp_flags
from launchpad.launch import worker_manager
from launchpad.launch import worker_manager_v2

def _stop_vertex_ai(mark_as_completed=False):
  del mark_as_completed
  from google.cloud import aiplatform
  from google.api_core import exceptions
  aiplatform.init(project=os.environ['CLOUD_ML_PROJECT_ID'])
  try:
    aiplatform.CustomJob.get(os.environ['CLOUD_ML_JOB_ID']).cancel()
  except exceptions.FailedPrecondition:
    # Experiment could have been already cancelled.
    pass

def _ask_launcher_for_termination(launcher_process_id, mark_as_completed=False):
  del mark_as_completed
  os.kill(launcher_process_id, signal.SIGTERM)

def make_program_stopper(launch_type: Union[str, context.LaunchType]):
  """Returns a callable that stops the Launchpad program.

  Args:
    launch_type: launch_type with which the program stopper is used.

  Returns:
    A callable. When called, it stops the running program.
  """
  launch_type = context.LaunchType(launch_type)

  def _stop_mt():
    worker_manager_v2.get_worker_manager().stop_event.set()

  if launch_type is context.LaunchType.TEST_MULTI_THREADING:
    if lp_flags.LP_WORKER_MANAGER_V2.value:
      return _stop_mt
    else:
      def _stop():
        worker_manager.get_worker_manager()._sigterm()
      return _stop

  if (launch_type is context.LaunchType.LOCAL_MULTI_THREADING and
      lp_flags.LP_WORKER_MANAGER_V2.value):
    return _stop_mt

  if (launch_type in [
      context.LaunchType.LOCAL_MULTI_PROCESSING,
      context.LaunchType.TEST_MULTI_PROCESSING
  ] and lp_flags.LP_WORKER_MANAGER_V2.value):

    def _sigint_to_launcher(launcher_process_id, mark_as_completed=False):
      del mark_as_completed
      # Here we send a SIGINT to the launcher process for simplicity, but it
      # will bring down all programs launched from that process. A better
      # approach is to communicate to the launcher process through a unix pipe
      # (named after the launcher pid), so that the launcher process will only
      # kill subprocesses associated with the specific program.
      os.kill(launcher_process_id, signal.SIGINT)
    # In local_mp, we treat lp.stop() as a user-requested stop. The reason is
    # that it provides convenience in observing preemption handling logic (using
    # `lp.wait_for_stop()` or the stop event) being triggered locally.
    return functools.partial(_sigint_to_launcher, os.getpid())

  if launch_type in [
      context.LaunchType.LOCAL_MULTI_PROCESSING,
      context.LaunchType.LOCAL_MULTI_THREADING,
      context.LaunchType.TEST_MULTI_PROCESSING,
  ]:
    return functools.partial(_ask_launcher_for_termination, os.getpid())

  if launch_type in [context.LaunchType.VERTEX_AI]:
    return _stop_vertex_ai

  raise NotImplementedError(f'{launch_type} is not yet supported.')


text:
/*  $Id$ */
/*	$OpenBSD: rpc.h,v 1.7 1998/12/20 23:43:18 millert Exp $	*/
/*	$NetBSD: rpc.h,v 1.5 1994/12/04 01:15:30 cgd Exp $	*/

/*
 * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
 * unrestricted use provided that this legend is included on all tape
 * media and as a part of the software program in whole or part.  Users
 * may copy or modify Sun RPC without charge, but are not authorized
 * to license or distribute it to anyone else except as part of a product or
 * program developed by the user.
 *
 * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
 * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
 *
 * Sun RPC is provided with no support and without any obligation on the
 * part of Sun Microsystems, Inc. to assist in its use, correction,
 * modification or enhancement.
 *
 * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
 * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
 * OR ANY PART THEREOF.
 *
 * In no event will Sun Microsystems, Inc. be liable for any lost revenue
 * or profits or other special, indirect and consequential damages, even if
 * Sun has been advised of the possibility of such damages.
 *
 * Sun Microsystems, Inc.
 * 2550 Garcia Avenue
 * Mountain View, California  94043
 *
 *	from: @(#)rpc.h 1.9 88/02/08 SMI
 *	@(#)rpc.h	2.4 89/07/11 4.0 RPCSRC
 */

/*
 * rpc.h, Just includes the billions of rpc header files necessary to
 * do remote procedure calling.
 *
 * Copyright (C) 1984, Sun Microsystems, Inc.
 */
#ifndef _RPC_RPC_H
#define _RPC_RPC_H

#include <rpc/types.h>		/* some typedefs */
/* #include <netinet/in.h> */

/* external data representation interfaces */
#include <rpc/xdr.h>		/* generic (de)serializer */

/* Client side only authentication */
#include <rpc/auth.h>		/* generic authenticator (client side) */

/* Client side (mostly) remote procedure call */
#include <rpc/clnt.h>		/* generic rpc stuff */

/* Client side (mostly) pmap functions */
#include <rpc/pmap_clnt.h>	/* generic pmap stuff */

/* semi-private protocol headers */
#include <rpc/rpc_msg.h>	/* protocol for rpc messages */
#include <rpc/auth_unix.h>	/* protocol for unix style cred */
/*
 *  Uncomment-out the next line if you are building the rpc library with
 *  DES Authentication (see the README file in the secure_rpc/ directory).
 */
#ifdef notdef
#include <rpc/auth_des.h>	/* protocol for des style cred */
#endif

/* Server side only remote procedure callee */
#include <rpc/svc.h>		/* service manager and multiplexer */
#include <rpc/svc_auth.h>	/* service side authenticator */

/*
 * COMMENT OUT THE NEXT INCLUDE (or add to the #ifndef) IF RUNNING ON
 * A VERSION OF UNIX THAT USES SUN'S NFS SOURCE.  These systems will
 * already have the structures defined by <rpc/netdb.h> included in <netdb.h>.
 */
/* routines for parsing /etc/rpc */

struct rpcent {
      char    *r_name;        /* name of server for this rpc program */
      char    **r_aliases;    /* alias list */
      int     r_number;       /* rpc program number */
};

__BEGIN_DECLS
extern struct rpcent *getrpcbyname	__P((char *));
extern struct rpcent *getrpcbynumber	__P((int));
extern struct rpcent *getrpcent		__P((void));
extern void setrpcent __P((int));
extern void endrpcent __P((void));

extern int get_myaddress __P((struct sockaddr_in *));
extern int registerrpc __P((int, int, int, char *(*) __P((char [UDPMSGSIZE])),
	xdrproc_t, xdrproc_t));
extern int callrpc __P((char *, int, int, int, xdrproc_t, char *,
	xdrproc_t , char *));
extern int getrpcport __P((char *, int, int, int));

extern bool_t xdr_opaque_auth __P((XDR *, struct opaque_auth *));
__END_DECLS

#endif /* !_RPC_RPC_H */


text:
@implementation KnCDirectory

+(BOOL)isRegistred
{
    return [[NSUserDefaults standardUserDefaults]boolForKey:KEY_REGISTERED];
}

+(BOOL)isRemoved
{
    return [[NSUserDefaults standardUserDefaults]boolForKey:KEY_REMOVED];
}

+(NSString*)userAgent
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle]infoDictionary];

    NSString *versionName = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *versionCode = [infoDictionary objectForKey:@"CFBundleVersion"];

    return [NSString stringWithFormat:@"KnCWallet~{%@}~{%@}~{iOS}~{%@}",versionName,versionCode,DIRECTORY_UA_KEY];
}

+(void)setRemoved:(BOOL)removed
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:removed forKey:KEY_REMOVED];
    [defaults synchronize];
}

+(void)setRegistered:(BOOL)registered
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:registered forKey:KEY_REGISTERED];
    [defaults synchronize];
}

+(NSString*)clientId
{
    return [[NSUserDefaults standardUserDefaults]stringForKey:KEY_CLIENT_ID];
}

+(NSString*)clientSecret
{
    return [[NSUserDefaults standardUserDefaults]stringForKey:KEY_CLIENT_SECRET];
}

+(NSString*)telephoneNumber
{
    return [[NSUserDefaults standardUserDefaults]stringForKey:KEY_PHONE];
}

+(void)saveTelephoneNumber:(NSString*)telephoneNumber
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:telephoneNumber forKey:KEY_PHONE];
    [defaults synchronize];
}

+(void)requestResendCodeRequest:(NSString*)telephoneNumber completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self request:[NSString stringWithFormat:@"entries/%@/authToken", telephoneNumber] method:GET signed:YES payload:nil completionCallback:completion errorCallback:error];
}

+(void)registrationRequest:(NSString*)telephoneNumber bitcoinWalletAddress:(NSString*)bitcoinWalletAddress phoneID:(NSString*)phoneID completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
                             telephoneNumber,@"telephoneNumber",
                             bitcoinWalletAddress,@"bitcoinWalletAddress",
                             phoneID, @"phoneID",
                             nil];

    [self saveTelephoneNumber:telephoneNumber];

    NSDictionary *payload = [NSDictionary dictionaryWithObject:entry forKey:@"entry"];

    [self request:@"entries" method:POST signed:NO payload:payload completionCallback:completion errorCallback:error];
}

+(void)validateRegistrationRequest:(NSString*)authToken completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
                           authToken,@"authToken",
                           nil];

    NSDictionary *payload = [NSDictionary dictionaryWithObject:entry forKey:@"entry"];

    [self request:[NSString stringWithFormat:@"entries/%@",[self telephoneNumber]] method:PATCH signed:YES payload:payload completionCallback:completion errorCallback:error];
}

+(void)contactsRequest:(NSArray*)contacts completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{

    NSDictionary *payload = [NSDictionary dictionaryWithObject:contacts forKey:@"contacts"];

    [self request:[NSString stringWithFormat:@"entries/%@/contacts", [self telephoneNumber]] method:POST signed:YES payload:payload completionCallback:completion errorCallback:error];
}

+(void)addressPatchRequest:(NSString*)bitcoinWalletAddress completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    NSDictionary *entry = [NSDictionary dictionaryWithObject:bitcoinWalletAddress forKey:@"bitcoinWalletAddress"];
    NSDictionary *payload = [NSDictionary dictionaryWithObject:entry forKey:@"entry"];

    [self request:[NSString stringWithFormat:@"entries/%@",[self telephoneNumber]] method:PATCH signed:YES payload:payload completionCallback:completion errorCallback:error];
}

+(void)removeEntryRequest:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self request:[NSString stringWithFormat:@"entries/%@", [self telephoneNumber]] method:DELETE signed:YES payload:nil completionCallback:completion errorCallback:error];
}

+(void)updateTxRequest:(NSString*)counterpart note:(NSString*)note sent:(BOOL)sent txId:(NSString*)transactionId payload:(NSDictionary*)payload completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self submitTx:YES counterpart:counterpart note:note sent:sent txId:transactionId payload:payload completionCallback:completion errorCallback:error];
}

+(void)submitTxRequest:(NSString*)counterpart message:(NSString*)message sent:(BOOL)sent txId:(NSString*)transactionId payload:(NSDictionary*)payload completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self submitTx:NO counterpart:counterpart note:message sent:sent txId:transactionId payload:payload completionCallback:completion errorCallback:error];
}

+(void)submitTx:(BOOL)isUpdate counterpart:(NSString*)counterpart note:(NSString*)note sent:(BOOL)sent txId:(NSString*)transactionId payload:(NSDictionary*)payload completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    NSString *encodedAdditionalPayload = @"%7B%7B";
    if(payload){
        encodedAdditionalPayload = [[payload description]urlEncodeUsingEncoding:NSUTF8StringEncoding];
    }

    NSDictionary *transaction = nil;

    if(isUpdate){

        NSString *key = sent ? @"senderNote" : @"receiverNote";
        NSString *sentKey = sent ? @"sentFrom" : @"sentTo";
        transaction = [NSDictionary dictionaryWithObjectsAndKeys:encodedAdditionalPayload,@"payload", note, key, [self telephoneNumber], sentKey, nil];

    }else{

        NSString *sentFrom = nil;
        NSString *sentTo = nil;
        if(sent){
            sentFrom = [self telephoneNumber];
            sentTo = counterpart;
        }else{
            sentFrom = counterpart;
            sentTo = [self telephoneNumber];
        }

        transaction = [NSDictionary dictionaryWithObjectsAndKeys:[self telephoneNumber],@"sentFrom",sentTo,@"sentTo",encodedAdditionalPayload,@"payload", note, @"message", nil];
    }

    NSDictionary *fullPayload = [NSDictionary dictionaryWithObject:transaction forKey:@"transaction"];

    [self request:[NSString stringWithFormat:@"transactions/%@",transactionId] method:POST signed:YES payload:fullPayload completionCallback:completion errorCallback:error];
}

+(void)listTransactions:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self request:[NSString stringWithFormat:@"entries/%@/transactions", [self telephoneNumber]] method:GET signed:YES payload:nil completionCallback:completion errorCallback:error];
}

+(void)lookupTransactions:(NSString*)txId completion:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{
    [self request:[NSString stringWithFormat:@"transactions/%@", txId] method:GET signed:YES payload:nil completionCallback:completion errorCallback:error];
}

+(void)saveRegistrationRequest:(NSDictionary*)response{

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSDictionary *data = [response objectForKey:@"data"];
    if(data){

        if([data objectForKey:@"clientID"]){
            [defaults setObject:[data objectForKey:@"clientID"] forKey:KEY_CLIENT_ID];
        }

        if([data objectForKey:@"secret"]){
            [defaults setObject:[data objectForKey:@"secret"] forKey:KEY_CLIENT_SECRET];
        }
    }

    [defaults synchronize];

}

+(NSString*)trimWhitespace:(NSString*)string
{

    NSArray *chars = @[@"\n",@" "];
    for(NSString *character in chars){
        string = [string stringByReplacingOccurrencesOfString:character withString:@""];
    }

    return string;
}

+ (void)request:(NSString*)restPath method:(NSString*)method signed:(BOOL)signRequest payload:(NSDictionary*)payload completionCallback:(void (^)(NSDictionary *response))completion errorCallback:(void (^)(NSError *error))error
{

    if([self isRemoved]){
        return;
    }

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", DIRECTORY_BASE_URL, restPath]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:TIMEOUT];

    [request setHTTPMethod:method];

    long timestamp = (long)[[NSDate date] timeIntervalSince1970];
    NSString *userAgent = [self userAgent];

    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    [request setValue:[NSString stringWithFormat:@"%li",timestamp] forHTTPHeaderField:@"X-Timestamp"];

    if(signRequest){

        NSString *clientId = [self clientId];
        NSString *secret = [self clientSecret];

        if(!clientId){
            error([NSError errorWithDomain:@"no client id" code:-1 userInfo:nil]);
            return;
        }

        if(!secret){
            error([NSError errorWithDomain:@"no secret" code:-1 userInfo:nil]);
            return;
        }

        NSString *serializedBody = @"";
        if(payload){
            NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:NSJSONWritingPrettyPrinted error:nil];
            NSString *s =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            serializedBody = s;
            [request setHTTPBody:data];
        }

        NSString *data = [NSString stringWithFormat:@"%@%@%li",url.absoluteString, serializedBody, timestamp];

        NSString *hmac = [self HMACWithSecret:secret string:data];

        [request setValue:clientId forHTTPHeaderField:@"X-ClientId"];
        [request setValue:hmac forHTTPHeaderField:@"X-Signature"];
    }else if(payload){

        NSError *bodyError = nil;
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:payload options:NSJSONWritingPrettyPrinted error:&bodyError]];

        if(bodyError){
            error([NSError errorWithDomain:@"unable to serialize json body" code:-1 userInfo:payload]);
            return;
        }
    }

    NSString *isSigned = signRequest ? @"signed" : @"unsigned";

    if(payload){
        NSLog(@"perform %@ request %@ %@ %@",isSigned, url.absoluteString, method, payload);
    }else{
        NSLog(@"perform %@ request %@ %@ (no payload)",isSigned, url.absoluteString, method);
    }

    [NSURLConnection sendAsynchronousRequest:request queue:[self queue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        dispatch_sync(dispatch_get_main_queue(), ^{

            if(data){
                NSString *raw = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"response has data %@",raw);
            }else{
                NSLog(@"response has no data");
            }

            if(connectionError){

                if(data){
                    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                    if(json && [json isKindOfClass:[NSDictionary class]] && [json objectForKey:@"error"]){
                        NSLog(@"server response error %@",json);
                        error([NSError errorWithDomain:@"bad request" code:-2 userInfo:json]);
                        return;
                    }
                }

                NSLog(@"connection error %@ %@",url,connectionError);
                error(connectionError);

            }else{

                NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                int statusCode = [httpResponse statusCode];

                NSDictionary *dictionary = [httpResponse allHeaderFields];
                NSLog(@"Header response %@",[dictionary description]);

                NSError *err = nil;

                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];

              	if(statusCode < 200 || statusCode > 300){

                    if(err){
                        error(err);
                        return;
                    }

                    if(!err && json && [json isKindOfClass:[NSDictionary class]]){
                        NSLog(@"server response error %@",json);
                        error([NSError errorWithDomain:@"bad request" code:-2 userInfo:json]);
                    }

                }else{

                    if(!err && json && [json isKindOfClass:[NSDictionary class]]){

                        NSLog(@"response success %i %@",statusCode,json);
                        completion(json);
                    }else{
                        NSLog(@"response success %i (no data)",statusCode);
                        completion([NSDictionary dictionary]);

                    }
                    return;

                }

            }

        });

    }];

}

id queue;

+(NSOperationQueue*)queue
{
    if(!queue){
        queue = [[NSOperationQueue alloc]init];
    }
    return queue;
}

+ (NSString*) HMACWithSecret:(NSString*) secret string:(NSString*)string
{
    CCHmacContext    ctx;
    const char       *key = [secret UTF8String];
    const char       *str = [string UTF8String];
    unsigned char    mac[CC_MD5_DIGEST_LENGTH];
    char             hexmac[2 * CC_MD5_DIGEST_LENGTH + 1];
    char             *p;

    CCHmacInit( &ctx, kCCHmacAlgMD5, key, strlen( key ));
    CCHmacUpdate( &ctx, str, strlen(str) );
    CCHmacFinal( &ctx, mac );

    p = hexmac;
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++ ) {
        snprintf( p, 3, "%02x", mac[ i ] );
        p += 2;
    }

    return [NSString stringWithUTF8String:hexmac];
}

@end


text:
'use strict';
var bundalo = require('bundalo'),
	path = require('path'),
	bundaloConfig = {
		fallback: 'en_US',
		contentPath: path.join(process.cwd(), 'locales'),
		cache: true,
		engine: 'dust'
	};

module.exports = {

	/**
	 * Update the selected items for checkbox options
	 * @param selectedItems
	 * @param avalilabeItems
	 * returns availableItems with selected values
	 */

	handleCheckboxSelections: function (selectedItems, avalilabeItems) {
		var updatedItemDesc = {};
		avalilabeItems.forEach(function (key) {
			if (selectedItems.indexOf(key) !== -1) {
				updatedItemDesc[key] = "selected";
			} else {
				updatedItemDesc[key] = "unselected";
			}
		});
		return updatedItemDesc;
	},

	// about to handle
	fetchDynamicMessage: function (bundle, locale, data, callback) {
		var provider = bundalo(bundaloConfig);
		provider.get({'bundle': bundle,'locality': locale, 'model': data}, callback);
	},

	getbusinessName: function (obj) {
		var name;
		if (Array.isArray(obj.businesses) && obj.businesses[0] &&
				obj.businesses[0].name) {
			name = obj.businesses[0].name;
		} else if (obj.name.accountFullName) {
			name = obj.name.accountFullName;
		} else {
			name = "";
		}
		return name;
	}

};


text:
{% extends "main.j2.html" %}
{% block body %}

Paper details:

W. Sabrina Lin, Steven Tjoa, H. Vicky Zhao, and K. J. Ray Liu

IEEE Int. Conf. Multimedia and Expo, July 2007

Download: Paper

BibTeX:

@INPROCEEDINGS{lin2007icme,
  title = "Image Source Coding Forensics via Intrinsic Fingerprints",
  author = "W. Sabrina Lin and Steven Tjoa and H. Vicky Zhao and K. J. Ray Liu",
  booktitle = "Proc. IEEE Int. Conf. Multimedia and Expo",
  address = "Beijing, China",
  year = "2007",
  month = jul,
  pages = "1127--1130",
};

The most popular image compression schemes in use today are lossy, i.e., compression imposes some irreversible distortion in the image in order to achieve a smaller file size. Because each compression method imposes different kinds of distortion, the distortion can act as a fingerprint of the compression method.  Existing image compression methods can be grouped into a few categories — e.g., transform coding, vector quantization, subband coding, linear predictive coding, embedded coding — where all methods in the same category leave behind the same type of fingerprint in an image during compression.

In this paper, we analyze the intrinsic fingerprints of different types of image compression methods and propose a forensic system that identifies the type of the compression and provides a confidence measure in the system’s decision. Results show that the system can achieve a probability of detection of 0.82 for an image PSNR of 40 dB and even higher accuracy for lower PSNRs.

{% endblock %}


text:
namespace Mile
{
   class BlendState;
   class RenderTargetDX11;
   class MEAPI ToneMappingPass : public RenderingPass
   {
      DEFINE_CONSTANT_BUFFER(ToneMappingParams)
      {
         float ExposureFactor = 0.4f;
         float GammaFactor = 2.2f;
      };

      DEFINE_CONSTANT_BUFFER(PackedToneMappingParams)
      {
         Vector2 Factors;
      };

   public:
      ToneMappingPass(class RendererDX11* renderer);
      ~ToneMappingPass();

      bool Init();
      bool Bind(ID3D11DeviceContext& deviceContext, RenderTargetDX11* hdrBuffer);
      virtual void Unbind(ID3D11DeviceContext& deviceContext) override;

      void UpdateParameters(ID3D11DeviceContext& deviceContext, ToneMappingParams buffer);

   private:
      RenderTargetDX11* m_boundHdrBuffer;
      CBufferPtr m_params;

   };
}


text:
\begin{problema}{Hardwood Species}{Standard}{Standard}{UVa}

\noindent\begin{minipage}{.80\textwidth}
  {
  Hardwoods are the botanical group of trees that have broad leaves, produce a fruit or nut, and generally go dormant in the winter.\\

  America's temperate climates produce forests with hundreds of hardwood species -- trees that share certain biological characteristics. Although oak, maple and cherry all are types of hardwood trees, for example, they are different species. Together, all the hardwood species represent 40 percent of the trees in the United States. \\
  }
\end{minipage}%
\begin{minipage}{.20\textwidth}
  \centering
  \includegraphics[height=3cm]{graficos/tree}
\end{minipage}
\\
\\
On the other hand, softwoods, or conifers, from the Latin word meaning ``cone-bearing'', have needles. Widely available US softwoods include cedar, fir, hemlock, pine, redwood, spruce and cypress. In a home, the softwoods are used primarily as structural lumber such as 2x4s and 2x6s, with some limited decorative applications. \\

Using satellite imaging technology, the Department of Natural Resources has compiled an inventory of every tree standing on a particular day. You are to compute the total fraction of the tree population represented by each species. \\

The first line is the number of test cases, followed by a blank line. Each test case of your program consists of a list of the species of every tree observed by the satellite; one tree per line. No species name exceeds 30 characters. There are no more than 10,000 species and no more than 1,000,000 trees. There is a blank line between each consecutive test case. \\

For each test case print the name of each species represented in the population, in alphabetical order, followed by the percentage of the population it represents, to 4 decimal places. Print a blank line between 2 consecutive data sets.\\

\Example

\input ejemplos/hardwood.txt

URL: \\ http://uva.onlinejudge.org/index.php?\\
option=onlinejudge\&page=show\_problem\&problem=1167

\end{problema}