*/

/*

    Number DataType

    As in JavaScript all the numbers in TypeScript are also Floating point numbers.
    In addition to hexadecimal and decimal literals, TypeScript also
    supports binary and octal literals introduced in ECMAScript 2015.
    decimal, hex = 0x , binary = 0b , octal = 0o.
*/

/*
String Data type

 This is one of the commonly used datatype for textual data of any length,
 we may use with "" or ''
 */

// You can also use template strings, which can span multiple lines and have embedded expressions.

/*
    Array DataType

    An array is an indexed collection of values
    we can define multiple values with single variable name array
    we can use them like number[] or Array<number>
 */

/*

  Enum DataType

   enums are used to define a collection of constant values
    enums values once declared ,  they cannot be modified
 */

/*
    Any DataType

    This datatype accepts any types of data as a value to variables
 */

/*
    Void Data Type
    This is quite opposite to any datatype
    this may commonly used with function where no return types
 */
 // Number

 let tsVersion:number = 3.0;
 console.log(`tsVersion : ${tsVersion}`);

 //string
 let greet:string = 'Good Morning';
 console.log(`greet Msg: ${greet}`);

 //boolean
 let isTsEasy:boolean = true;
 console.log(`isTsEasy:${isTsEasy}`);

 //Any
 let someVar:any =10;
 console.log(`someVar :${someVar}`);
 someVar ='Test';
 console.log(`someVar :${someVar}`);
 someVar = true;
 console.log(`someVar :${someVar}`);

 //Array
 let numbers:Array<number> = [10,20,30,40,50];
 console.log(`numbers :${numbers}`);

 let technologies:Array<string> = ['HTML','CSS','JavaScript'];
 console.log(`technologies:${technologies}`);

 //Enum
 enum Month {
     JAN = 'January',
     FEB = 'February',
     MAR = 'March'
 }
 console.log(`JAN:${Month.JAN}`);

 //Void
 function greetMsg():void{
     console.log('Hello Good Morning');
 }
 greetMsg();export type TransformerFunction<T> = (s: string) => T;
export type StringMap = { [k: string]: string };
export type AnyMap = { [k: string]: never };
export type TMap<T> = { [k: string]: T };
export type Tuple<T> = [keyof T, T[keyof T]];
import reduce from './reduce.ts'

import { Curry2, FunctorWithArLk } from './utils/types.ts'
import curryN from './utils/curry_n.ts'
import { isArray, isIterable, isIterator, isArrayLike, isNotUndefinedOrNull } from './utils/is.ts'
import { throwFunctorError } from './utils/throw.ts'

function _arrayJoin<T>(separator: string, list: Array<T>) {
  return list.join(separator)
}
function join<T extends Object>(separator: string | number, functor: FunctorWithArLk<T>) {
  const sep = separator.toString()
  if(isArray(functor)) return _arrayJoin(sep, functor.filter(isNotUndefinedOrNull))
  if(isIterable(functor) || isIterator(functor) || isArrayLike(functor)) {
    return reduce(
      (acc: string, value: T) => {
        return(
          isNotUndefinedOrNull(value)
            ? acc + (acc ? sep : '') + value.toString()
            : acc
        )
      },
      '',
      functor
    )
  }
  throwFunctorError()
}

/** Returns a string made by inserting the `separator` between each element and
 * concatenating all the elements into a single string.
 * The functor may be array-like/iterable/iterat


; i<rpos-2;i++) rp=rp->next;
            ListNode*rn = rp->next;
            ListNode*rsave = rn->next;
            // swap
            lp->next = rn;
            rn->next = ln->next;
            rp->next = ln;
            ln->next = rsave;
            return head;
        }
    }
};// leetcode 676. Implement Magic Dictionary

class TrieNode{
    public:
    char data;
    unordered_map<char,TrieNode*>children;
    bool isTerminal;
    TrieNode(char ch): data(ch), isTerminal(false){};
};

class Trie{
    TrieNode*root;

    void insertUtil(TrieNode* root, string &word, int i = 0){
        if(i==word.size()){
            root->isTerminal = true;
            return;
        }
        if(root->children.find(word[i]) == root->children.end()){
            root->children[word[i]] = new TrieNode(word[i]);
        }
        insertUtil(root->children[word[i]], word, i+1);
    }

    bool searchUtil(TrieNode* root, string&word, int i = 0, bool mismatch = false){
        if(i == word.size()) return mismatch && root->isTerminal;

        auto ch = word[i];
        if(root->children.find(ch) != root->children.end()){
            // match till you can
            if(searchUtil(root->children[ch], word, i+1, mismatch)){
                return true;
            }
        }
        // if you are here means-> there is a mismatch
        if(!mismatch){
            for(auto &[childChar, childNode]: root->children){
                if(ch!=childChar && searchUtil(childNode, word, i+1, true)) return true;
            }
        }
        return false;
    }

public:
    Trie(){
        root = new TrieNode('\0');
    }
    void insert(string &word){
        insertUtil(root,word);
    }
    bool search(string &word){
        return searchUtil(root,word);
    }
};

class MagicDictionary {
    Trie trie;
public:
    MagicDictionary() {

    }

    void buildDict(vector<string> dictionary) {
        for(auto &word:dictionary){
            trie.insert(word);
        }
    }

    bool search(string searchWord) {
        return trie.search(searchWord);
    }
};

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary* obj = new MagicDictionary();
 * obj->buildDict(dictionary);
 * bool param_2 = obj->search(searchWord);
 */#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;

class TrieNode{
    public:
        char value;
        unordered_map<int,TrieNode*>children;
        bool isTerminal;

        TrieNode(char data){
            value = data;
            isTerminal = false;
        }
};

// insert
void insertIntoTrie(TrieNode* root, string word){
    // base case: string empty hojaye
    if(word.length() == 0){
        root->isTerminal = true;
        return;
    }

    // 1case: 1 character ko trie me insert krdo
    char ch = word[0];
    TrieNode* child;

    // present: waha chle jao
    // absent: create krdo
    if(root->children.count(ch) == 1){
        child = root->children[ch];
    }
    else{
        // absent
        child = new TrieNode(ch);
        // link new node
        root->children[ch] = child;
    }
    // baaki recurs


plainEojeol), arrayOf("f")))
            else this.eojeolList.toTypedArray()
    }

    /** 분석 수행 **/
    override fun morphAnalyze(ps: PlainSentence): SetOfSentences {
        val st = StringTokenizer(ps.sentence, " \t")
        val eojeolNum = st.countTokens()
        val plainEojeolArray = ArrayList<String>(eojeolNum)
        val eojeolSetArray = ArrayList<Array<Eojeol>>(eojeolNum)

        while (st.hasMoreTokens()) {
            val plainEojeol = st.nextToken()
            plainEojeolArray.add(plainEojeol)
            eojeolSetArray.add(this.processEojeol(plainEojeol))
        }

        return this.postProc.doPostProcessing(SetOfSentences(ps.documentID, ps.sentenceID,
                ps.isEndOfDocument, plainEojeolArray, eojeolSetArray)) ?: throw IllegalStateException()
    }

    /** 초기화 **/
    override fun initialize(configFile: String) {
        initialize(configFile, Configuration.hanBaseDir)
    }

    /** 초기화 **/
    override fun initialize(configFile: String?, dummy: String?) {
        Dictionary.loadDictionary()
    }
}

/**
 * 한나눔 구문구조 및 의존구문 분석기
 *
 * ## 참고
 * **구문구조 분석**은 문장의 구성요소들(어절, 구, 절)이 이루는 문법적 구조를 분석하는 방법입니다.
 * 예) '나는 밥을 먹었고, 영희는 짐을 쌌다'라는 문장에는
 * 2개의 절이 있습니다
 * * 나는 밥을 먹었고
 * * 영희는 짐을 쌌다
 * 각 절은 3개의 구를 포함합니다
 * * 나는, 밥을, 영희는, 짐을: 체언구
 * * 먹었고, 쌌다: 용언구
 *
 * 아래를 참고해보세요.
 * * [Word.getPhrase] 어절이 직접 속하는 가장 작은 구구조 [SyntaxTree]를 가져오는 API
 * * [kr.bydelta.koala.data.Sentence.getSyntaxTree] 전체 문장을 분석한 [SyntaxTree]를 가져오는 API
 * * [SyntaxTree] 구구조를 저장하는 형태
 * * [PhraseTag] 구구조의 형태 분류를 갖는 Enum 값
 *
 * **의존구조 분석**은 문장의 구성 어절들이 의존 또는 기능하는 관계를 분석하는 방법입니다.
 * 예) '나는 밥을 먹었고, 영희는 짐을 쌌다'라는 문장에는
 * 가장 마지막 단어인 '쌌다'가 핵심 어구가 되며,
 * * '먹었고'가 '쌌다'와 대등하게 연결되고
 * * '나는'은 '먹었고'의 주어로 기능하며
 * * '밥을'은 '먹었고'의 목적어로 기능합니다.
 * * '영희는'은 '쌌다'의 주어로 기능하고,
 * * '짐을'은 '쌌다'의 목적어로 기능합니다.
 *
 * 아래를 참고해보세요.
 * * [Word.getDependentEdges] 어절이 직접 지배하는


    } catch (ros::Exception& e) {
      setStatus(StatusProperty::Error, "Topic",
                QString("Error subscribing: ") + e.what());
    }
  }
}

void AerialMapDisplay::unsubscribe() {
  coord_sub_.shutdown();
  ROS_INFO("Unsubscribing.");
}

void AerialMapDisplay::updateDynamicReload() {
  // nothing to do here, when robot GPS updates the tiles will reload
}

void AerialMapDisplay::updateAlpha() {
  alpha_ = alpha_property_->getFloat();
  dirty_ = true;
  ROS_INFO("Changing alpha to %f", alpha_);
}

void AerialMapDisplay::updateFrame() {
  ROS_INFO_STREAM("Changing robot frame to " << frame_property_->getFrameStd());
  transformAerialMap();
}

void AerialMapDisplay::updateDrawUnder() {
  /// @todo: figure out why this property only applies to some objects
  draw_under_ = draw_under_property_->getValue().toBool();
  dirty_ = true;  //  force update
  ROS_INFO("Changing draw_under to %s", ((draw_under_) ? "true" : "false"));
}

void AerialMapDisplay::updateObjectURI() {
  object_uri_ = object_uri_property_->getStdString();
  loadImagery();  //  reload all imagery
}

void AerialMapDisplay::updateZoom() {
  const int zoom = std::max(0, std::min(kMaxZoom, zoom_property_->getInt()));
  if (zoom != zoom_) {
    zoom_ = zoom;
    loadImagery();
  }
}

void AerialMapDisplay::updateBlocks() {
  const int blocks =
      std::max(0, std::min(kMaxBlocks, blocks_property_->getInt()));
  if (blocks != blocks_) {
    blocks_ = blocks;
    loadImagery();
  }
}

void AerialMapDisplay::updateFrameConvention() { transformAerialMap(); }

void AerialMapDisplay::updateTopic() {
  unsubscribe();
  clear();
  subscribe();
}

void AerialMapDisplay::clear() {
  setStatus(StatusProperty::Warn, "Message", "No map received");
  clearGeometry();
  //  the user has cleared here
  received_msg_ = false;
  //  cancel current imagery, if any
  loader_.reset();
}

void AerialMapDisplay::clearGeometry() {
  for (MapObject& obj : objects_) {
    //  destroy object
    scene_node_->detachObject(obj.object);
    scene_manager_->destroyManualObject(obj.object);
    //  destroy texture
    if (!obj.texture.isNull()) {
      Ogre::TextureManager::getSingleton().remove(obj.texture->getName());
    }
    //  destroy material
    if (!obj.material.isNull()) {
      Ogre::MaterialManager::getSingleton().remove(obj.material->getName());
    }
  }
  objects_.clear();
}

void AerialMapDisplay::update(float, float) {
  //  creates all geometry, if necessary
  assembleScene();
  //  draw
  context_->queueRender();
}

void AerialMapDisplay::navFixCallback(
    const sensor_msgs::NavSatFixConstPtr& msg) {
  // If the new (lat,lon) falls into a different tile then we have some
  // reloading to do.
  if (!received_msg_ ||
      (loader_ && !loader_->insideCentreTile(msg->latitude, msg->longitude) &&
       dynamic_reload_property_->getValue().toBool())) {
    ref_fix_ = *msg;
    ROS_INFO("Reference point set to: %.12f, %.12f", ref_fix_.latitude,
             ref_fix_.longitude);
    setStatus(StatusProperty::Warn, "Message", "Loading map tiles.");

    //  re-load imagery
    received_msg_ = true;
    loadImagery();
    transformAerialMap();
  }
}

void AerialMapDisplay::loadImagery() {
  //  cancel current imagery, if any
  loader_.reset();

  if (!received_msg_)


3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),d.gfm.paragraph=c(d.paragraph)("(?!","(?!"+d.gfm.fences.source.replace("\\1","\\2")+"|"+d.list.source.replace("\\1","\\3")+"|")(),d.tables=f({},d.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/}),t.rules=d,t.lex=function(e,n){var r=new t(n);return r.lex(e)},t.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g,"    ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},t.prototype.token=function(e,t,n){for(var r,i,o,a,l,s,c,u,f,e=e.replace(/^ +$/gm,"");e;)if((o=this.rules.newline.exec(e))&&(e=e.substring(o[0].length),o[0].length>1&&this.tokens.push({type:"space"})),o=this.rules.code.exec(e))e=e.substring(o[0].length),o=o[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?o:o.replace(/\n+$/,"")});else if(o=this.rules.fences.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"code",lang:o[2],text:o[3]||""});else if(o=this.rules.heading.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"heading",depth:o[1].length,text:o[2]});else if(t&&(o=this.rules.nptable.exec(e))){for(e=e.substring(o[0].length),s={type:"table",header:o[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:o[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:o[3].replace(/\n$/,"").split("\n")},u=0;u<s.align.length;u++)/^ *-+: *$/.test(s.align[u])?s.align[u]="right":/^ *:-+: *$/.test(s.align[u])?s.align[u]="center":/^ *:-+ *$/.test(s.align[u])?s.align[u]="left":s.align[u]=null;for(u=0;u<s.cells.length;u++)s.cells[u]=s.cells[u].split(/ *\| */);this.tokens.push(s)}else if(o=this.rules.lheading.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"heading",depth:"="===o[2]?1:2,text:o[1]});else if(o=this.rules.hr.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"hr"});else if(o=this.rules.blockquote.exec(e))e=e.substring(o[0].length),this.tokens.push({type:"blockquote_start"}),o=o[0].replace(/^ *> ?/gm,""),this.token(o,t,!0),thi


#include <Efl_Ui.h>
#include "custom_recognizer.eo.h"
#include "custom_gesture.eo.h"
#include "custom_gesture.h"

#define MY_CLASS                       CUSTOM_RECOGNIZER_CLASS

typedef struct Custom_Recognizer_Data
{

} Custom_Recognizer_Data;

EOLIAN static const Efl_Class *
_custom_recognizer_efl_canvas_gesture_recognizer_type_get(const Eo *obj EINA_UNUSED, Custom_Recognizer_Data *pd EINA_UNUSED)
{
   return CUSTOM_GESTURE_CLASS;
}

EOLIAN static Eo *
_custom_recognizer_efl_object_finalize(Eo *obj, Custom_Recognizer_Data *pd EINA_UNUSED)
{
   efl_gesture_recognizer_custom_gesture_name_set(obj, "custom_gesture");
   return efl_finalize(efl_super(obj, MY_CLASS));
}

EOLIAN static Efl_Canvas_Gesture_Recognizer_Result
_custom_recognizer_efl_canvas_gesture_recognizer_recognize(Eo *obj EINA_UNUSED, Custom_Recognizer_Data *pd EINA_UNUSED,
                                                           Efl_Canvas_Gesture *gesture, Efl_Object *watched EINA_UNUSED,
                                                           Efl_Canvas_Gesture_Touch *event)
{
   const Efl_Gesture_Touch_Point_Data *data = efl_gesture_touch_current_data_get(event);
   Custom_Gesture_Data *gd;

   /* ignore multi-touch */
   if (data->id) return EFL_GESTURE_RECOGNIZER_RESULT_IGNORE;

   switch (efl_gesture_touch_state_get(event))
     {
      case EFL_GESTURE_TOUCH_STATE_BEGIN:
        return EFL_GESTURE_RECOGNIZER_RESULT_TRIGGER;
      case EFL_GESTURE_TOUCH_STATE_UPDATE:
        gd = efl_data_scope_get(gesture, CUSTOM_GESTURE_CLASS);
        gd->x_delta += data->cur.pos.x - data->prev.pos.x;
        gd->y_delta += data->cur.pos.y - data->prev.pos.y;
        return EFL_GESTURE_RECOGNIZER_RESULT_TRIGGER;
      case EFL_GESTURE_TOUCH_STATE_END:
        return EFL_GESTURE_RECOGNIZER_RESULT_FINISH;
      default:

        break;
     }

   return EFL_GESTURE_RECOGNIZER_RESULT_CANCEL;
}

#include "custom_recognizer.eo.c"


math.plex4.homology.zigzag.IntervalTracker;
import edu.stanford.math.primitivelib.autogen.algebraic.IntAbstractModule;
import edu.stanford.math.primitivelib.autogen.formal_sum.IntAlgebraicFreeModule;
import edu.stanford.math.primitivelib.autogen.formal_sum.IntSparseFormalSum;
import edu.stanford.math.primitivelib.autogen.functional.ObjectObjectFunction;
import edu.stanford.math.primitivelib.autogen.pair.ObjectObjectPair;
import gnu.trove.TObjectIntIterator;

public class InducedHomologyMappingUtility {

	public static <I extends Comparable<I>, U extends PrimitiveBasisElement> IntervalTracker<Integer, I, IntSparseFormalSum<U>>
	include(AbstractHomologyTracker<Integer, I, ?, IntSparseFormalSum<U>> X,
			AbstractHomologyTracker<Integer, I, ?, IntSparseFormalSum<U>> Z,
			AbstractHomologyTracker<Integer, I, ?, IntSparseFormalSum<U>> Y,
			final IntervalTracker<Integer, I, IntSparseFormalSum<U>> accumulator,
			IntAlgebraicFreeModule<U> chainModule,
			I X_index, I Y_index) {

		IntervalTracker<Integer, I, IntSparseFormalSum<U>> result = new IntervalTracker<Integer, I, IntSparseFormalSum<U>>();
		result.setUseLeftClosedIntervals(true);
		result.setUseRightClosedIntervals(true);
		ObjectObjectFunction<IntSparseFormalSum<U>, IntSparseFormalSum<U>> inclusionMap = InducedHomologyMappingUtility.getInclusionMap();

		Map<Integer, Integer> XZ_map = InducedHomologyMappingUtility.computeInducedMap(X.getState(), Z, chainModule, inclusionMap);
		Map<Integer, Integer> YZ_map = InducedHomologyMappingUtility.computeInducedMap(Y.getState(), Z, chainModule, inclusionMap);
		Map<Integer, List<Integer>> XY_map = new HashMap<Integer, List<Integer>>();

		Map<Integer, List<Integer>> ZY_map = reverse(YZ_map);

		for (Integer X_key: XZ_map.keySet()) {
			Integer Z_key = XZ_map.get(X_key);
			if (ZY_map.containsKey(Z_key)) {
				for (Integer Y_key: ZY_map.get(Z_key)) {
					if (!XY_map.containsKey(X_key)) {
						XY_map.put(X_key, new ArrayList<Integer>());
					}
					XY_map.get(X_key).add(Y_key);
				}
			}
		}

		Set<Integer> X_processedIndices = new HashSet<Integer>();
		Set<Integer> Y_processedIndices = new HashSet<Integer>();

		List<Integer> X_keys = new ArrayList<Integer>(XY_map.keySet());
		Collections.sort(X_keys);
		for (Integer X_key: X_keys) {
			List<Integer> Y_keys = XY_map.get(X_key);

			if (X_processedIndices.contains(X_key)) {
				continue;
			}

			if (Y_keys.size() > 0) {
				Integer Y_key = Y_keys.get(0);

				if (Y_processedIndices.contains(Y_key)) {
					continue;
				}

				X_processedIndices.add(X_key);
				Y_processedIndices.add(Y_key);

				IntervalDescriptor<I, IntSparseFormalSum<U>> X_descriptor = accumulator.getActiveGenerators().get(X_key);
				result.startInterval(Y_key, X_descriptor.getStart(), X_descriptor.getDimension(), X_descriptor.getGenerator());
			}
		}

		X_keys = new ArrayList<Integer>(accumulator.getActiveGenerators().keySet());
		Collections.sort(X_keys);
		for (Integer X_


err << "Error : Copy constructer of the class DoubleSparseSquareMatrix is not implemented." << std::endl;
	exit(1);
}

// Assignment operator
DoubleSparseSquareMatrix& DoubleSparseSquareMatrix::operator=(const DoubleSparseSquareMatrix& rhs){
	std::cerr << "Error : Assignment operator of the class DoubleSparseSquareMatrix is not implemented." << std::endl;
	exit(1);
}
//-------------------------------------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2021 Yoshiya Usui
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//-------------------------------------------------------------------------------------------------------
#include "Util.h"
#include "OutputFiles.h"

#include <stdio.h>
#include <math.h>
#include <vector>
#include <assert.h>

// Sort elements by its key value with quick sort
// cf) Numerical Recipes in C++ Second Edition, p336-p339.
// [Input]:
//   1) numOfIDs: Number of elements to be sorted
//   2)   values: Values of each element. Elements are sorted by this values.
// [Input/Output]:
//   1)      ids: Array of elements to be sorted
void quickSort( const int numOfIDs, int* ids, const double* values ){

	const int minimumSizeOfQuickSort = 7;
	std::vector< std::pair<int, int> > stack;

	//const int numOfIDs = sizeof( ids ) / sizeof( ids[0] );
	if( ids == NULL ){
		OutputFiles::m_logFile << "Error : ids is NULL in quickSort !!" << std::endl;
		exit(1);
	}
	if( values == NULL ){
		OutputFiles::m_logFile << "Error : values is NULL quickSort !!" << std::endl;
		exit(1);
	}
	if( numOfIDs <= 0 ){
		OutputFiles::m_logFile << "Error : numOfIDs is equal to or less than zero !!" << std::endl;
		exit(1);
	}
	int iLeft(0);
	int iRight(numOfIDs - 1);

	while(1){

		if( iRight - iLeft < minimumSizeOfQuickSort ){
			//----- Insertion sort >>>>>
			for( int j = iLeft + 1; j <= iRight; ++j ){
				const int moved = ids[j];
				const double valueOfElemnentMoved = values[moved];
				int i = j - 1;
				for( ; i >= iLeft; --i ){
					if( values[ids[i]] <= valueOfElemnentMoved ){
						break;
					}
					ids[i+1] = ids[i];
				}
				ids[i+1] = moved;
			}

			if( stack.empty() ){
				break;// Finish while loop
			}
			iLeft  = sta


'http://example.com/custom-property': {
      text: 'custom property',
      type: 'http://example.com/custom-property#type'
    }
  },
  // metadata of a selection
  21: {
    'http://example.com/selection-property': {
      text: 'selection property',
      type: 'http://example.com/selection-property#type'
    }
  }
}

const props = {
  'http://example.com/custom-property': { label: 'Non-template Property' },
  'http://example.com/photo-property': {
    id: 'http://example.com/photo-property',
    label: 'hello world'
  },
  'http://example.com/selection-property': { label: 'select prop' }
}

const photos = {
  11: { id: 11, path: '/path', width: 30, height: 40 },
  12: { id: 12, path: '/another', selections: [21], notes: [1] }
}

const vocab = {
  id: 'http://example.com/vocab',
  description: 'Description',
  prefix: 'vocab',
  seeAlso: 'http://example.com/seeAlso',
  title: 'Test Vocabulary',
  classes: ['http://example.com/class'],
  properties: ['http://example.com/photo-property'],
  datatypes: ['http://example.com/type']
}

const classes = {
  'http://example.com/class': {
    comment: 'comment',
    description: null,
    id: 'http://example.com/class',
    label: 'My Class'
  }
}

const datatypes = {
  'http://example.com/type': {
    id: 'http://example.com/type',
    comment: 'a custom datatype'
  }
}

const lists = {
  1: { name: 'list1' }
}

const tags = {
  1: { name: 'mytag' }
}

const notes = {
  1: {
    text: 'photo note',
    language: 'de',
    state: {
      doc: {
        type: 'doc',
        content: [{
          type: 'paragraph',
          content: [{
            type: 'text',
            text: 'photo note'
          }]
        }]
      }
    }
  },
  2: { text: 'selection note', state: {} }
}

const selections = {
  21: { x: 10, y: 20, width: 30, height: 40, notes: [2] }
}

const ontology = {
  class: classes,
  props,
  type: datatypes
}

export default {
  template,
  items,
  metadata,
  props,
  photos,
  vocab,
  classes,
  datatypes,
  lists,
  tags,
  notes,
  selections,
  ontology
}
import { LIST } from '#internal/constants/index.js'
import { items as itemsReducer } from '#internal/reducers/items.js'

describe('Items Reducer', () => {
  let state
  let action

  describe(LIST.ITEM.ADD, () => {
    beforeEach(() => {
      state = {
        1: { id: 1, lists: [] },
        2: { id: 2, lists: [1] }
      }

      action = {
        type: LIST.ITEM.ADD,
        payload: { id: 1, items: [1] },
        meta: {}
      }
    })

    it('skips unless the action has done', () => {
      expect(itemsReducer(state, action)).to.equal(state)
    })

    it('adds list to all items', () => {
      action.meta.done = true
      expect(itemsReducer(state,


\"2\"},\"rdfs:label\":\"Credential Rotation\"},{\"@id\":\"d3f:TokenBinding\",\"d3f:d3fend-id\":\"D3-TB\",\"d3f:definition\":\"Token binding is a security mechanism used to enhance the protection of tokens, such as cookies or OAuth tokens, by binding them to a specific connection.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"1\"},\"rdfs:label\":\"Token Binding\"}],\"d3f:d3fend-id\":\"D3-CH\",\"d3f:definition\":\"Credential Hardening techniques modify system or network properties in order to protect system or network/domain credentials.\",\"rdfs:label\":\"Credential Hardening\"},{\"@id\":\"d3f:MessageHardening\",\"children\":[{\"@id\":\"d3f:MessageAuthentication\",\"d3f:d3fend-id\":\"D3-MAN\",\"d3f:definition\":\"Authenticating the sender of a message and ensuring message integrity.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"2\"},\"rdfs:label\":\"Message Authentication\"},{\"@id\":\"d3f:MessageEncryption\",\"d3f:d3fend-id\":\"D3-MENCR\",\"d3f:definition\":\"Encrypting a message body using a cryptographic key.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"1\"},\"rdfs:label\":\"Message Encryption\"},{\"@id\":\"d3f:TransferAgentAuthentication\",\"d3f:d3fend-id\":\"D3-TAAN\",\"d3f:definition\":\"Validating that server components of a messaging infrastructure are authorized to send a particular message.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"3\"},\"rdfs:label\":\"Transfer Agent Authentication\"}],\"d3f:d3fend-id\":\"D3-MH\",\"d3f:definition\":\"Email or Messaging Hardening includes measures taken to ensure the confidentiality and integrity of user to user computer messages.\",\"rdfs:label\":\"Message Hardening\"},{\"@id\":\"d3f:SourceCodeHardening\",\"children\":[{\"@id\":\"d3f:IntegerRangeValidation\",\"d3f:d3fend-id\":\"D3-IRV\",\"d3f:definition\":\"Ensuring that an integer is within a valid range.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"1\"},\"rdfs:label\":\"Integer Range Validation\"},{\"@id\":\"d3f:PointerValidation\",\"children\":[{\"@id\":\"d3f:MemoryBlockStartValidation\",\"d3f:d3fend-id\":\"D3-MBSV\",\"d3f:definition\":\"Ensuring that a pointer accurately references the beginning of a designated memory block.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"1\"},\"rdfs:label\":\"Memory Block Start Validation\"},{\"@id\":\"d3f:NullPointerChecking\",\"d3f:d3fend-id\":\"D3-NPC\",\"d3f:definition\":\"Checking if a pointer is NULL.\",\"d3f:ref-count\":{\"@type\":\"http://www.w3.org/2001/XMLSchema#integer\",\"@value\":\"3\"},\"rdfs:label\":\"Null Pointer Checking\"}],\"d3f:d3fend-id\":\"D3-PV\",\"d3f:definition\":\"Ensuring that a pointer variable has the required properties for use.\",\"d3f:ref-count\":{\"@typ


# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""Simple test for 16x2 character lcd connected to an MCP23008 I2C LCD backpack."""
import time
import board
import busio
import adafruit_character_lcd.character_lcd_i2c as character_lcd

# Modify this if you have a different sized Character LCD
lcd_columns = 16
lcd_rows = 2

# Initialise I2C bus.
i2c = busio.I2C(board.SCL, board.SDA)

# Initialise the lcd class
lcd = character_lcd.Character_LCD_I2C(i2c, lcd_columns, lcd_rows)

# Turn backlight on
lcd.backlight = True
# Print a two line message
lcd.message = "Hello\nCircuitPython"
# Wait 5s
time.sleep(5)
lcd.clear()
# Print two line message right to left
lcd.text_direction = lcd.RIGHT_TO_LEFT
lcd.message = "Hello\nCircuitPython"
# Wait 5s
time.sleep(5)
# Return text direction to left to right
lcd.text_direction = lcd.LEFT_TO_RIGHT
# Display cursor
lcd.clear()
lcd.cursor = True
lcd.message = "Cursor! "
# Wait 5s
time.sleep(5)
# Display blinking cursor
lcd.clear()
lcd.blink = True
lcd.message = "Blinky Cursor!"
# Wait 5s
time.sleep(5)
lcd.blink = False
lcd.clear()
# Create message to scroll
scroll_msg = "<-- Scroll"
lcd.message = scroll_msg
# Scroll message to the left
for i in range(len(scroll_msg)):
    time.sleep(0.5)
    lcd.move_left()
lcd.clear()
lcd.message = "Going to sleep\nCya later!"
time.sleep(5)
# Turn backlight off
lcd.backlight = False
time.sleep(2)


r:     "#427dbd",
		BackgroundColor: "#427dbd",
	}
}
package api

import (
	"fmt"
	"net/http"
	"strconv"

	"github.com/TUM-Dev/gocast/dao"
	"github.com/TUM-Dev/gocast/model"
	"github.com/TUM-Dev/gocast/tools"
	"github.com/gin-gonic/gin"
)

func configMaintenanceRouter(router *gin.Engine, daoWrapper dao.DaoWrapper) {
	routes := maintenanceRoutes{DaoWrapper: daoWrapper}

	g := router.Group("/api/maintenance")
	g.Use(tools.Admin)
	{
		g.POST("/generateThumbnails", routes.generateThumbnails)
		g.GET("/generateThumbnails/status", routes.getThumbGenProgress)

		g.GET("/transcodingFailures", routes.getTranscodingFailures)
		g.DELETE("/transcodingFailures/:id", routes.deleteTranscodingFailure)

		g.GET("/emailFailures", routes.getEmailFailures)
		g.DELETE("/emailFailures/:id", routes.deleteEmailFailure)
	}

	cronGroup := g.Group("/cron")
	{
		cronGroup.GET("/available", routes.listCronJobs)
		cronGroup.POST("/run", routes.runCronJob)
	}
}

type maintenanceRoutes struct {
	dao.DaoWrapper

	thumbGenProgress float32
	thumbGenRunning  bool
}

func (r *maintenanceRoutes) generateThumbnails(c *gin.Context) {
	noFiles, err := r.FileDao.CountVoDFiles()
	if err != nil {
		_ = c.Error(tools.RequestError{
			Status:        http.StatusInternalServerError,
			CustomMessage: "can't find number of files",
			Err:           nil,
		})
		return
	}
	logger.Info("generating " + strconv.FormatInt(noFiles, 10) + " thumbs")
	go func() {
		courses, err := r.GetAllCourses()
		if err != nil {
			logger.Error("Can't get courses", "err", err)
		}
		processed := 0
		r.thumbGenRunning = true
		defer func() {
			r.thumbGenRunning = false
			r.thumbGenProgress = 0
		}()
		// Iterate over all courses. Some might already have a valid thumbnail.
		for _, course := range courses {
			for _, stream := range course.Streams {
				for _, file := range stream.Files {
					if file.Type != model.FILETYPE_VOD {
						continue
					}
					// Request thumbnail for VoD.
					err := RegenerateThumbs(dao.NewDaoWrapper(), file, &stream, &course)
					if err != nil {
						logger.Error(fmt.Sprintf(
							"Can't regenerate thumbnail for stream %d with file %s",
							stream.ID,
							file.Path,
						))
						continue
					}
					logger.Info("Processed thumbnail" + string(rune(processed)) + "of" + strconv.FormatInt(noFiles, 10))
					processed++
					r.thumbGenProgress = float32(processed) / float32(noFiles)
				}
			}
		}
	}()
}

func (r *maintenanceRoutes) getThumbGenProgress(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"running":  r.thumbGenRunning,
		"progress": r.thumbGenProgress,
	})
}

func (r *maintenanceRoutes) listCronJobs(c *gin.Context) {
	c.JSON(http.StatusOK, tools.Cron.ListCronJobs())
}

func (r *maintenanceRoutes) runCronJob(c *gin.Context) {
	err := c.Request.ParseForm()
	if err != nil {
		_ = c.Error(tools.RequestError{
			Status:        http.StatusBadRequest,
			CustomMessage: "Can't read request",
			Err:           err,
		})


/b> (<var>_Decimal64 a</var>)<var></var>

— Runtime Function: long __dpd_fixtddi (<var>_Decimal128 a</var>)<var></var>

— Runtime Function: long __bid_fixtddi (<var>_Decimal128 a</var>)<var></var>

These functions convert <var>a</var> to a signed long.

— Runtime Function: unsigned int __dpd_fixunssdsi (<var>_Decimal32 a</var>)<var></var>

— Runtime Function: unsigned int __bid_fixunssdsi (<var>_Decimal32 a</var>)<var></var>

— Runtime Function: unsigned int __dpd_fixunsddsi (<var>_Decimal64 a</var>)<var></var>

— Runtime Function: unsigned int __bid_fixunsddsi (<var>_Decimal64 a</var>)<var></var>

— Runtime Function: unsigned int __dpd_fixunstdsi (<var>_Decimal128 a</var>)<var></var>

— Runtime Function: unsigned int __bid_fixunstdsi (<var>_Decimal128 a</var>)<var></var>

These functions convert <var>a</var> to an unsigned integer.  Negative values all become zero.

— Runtime Function: unsigned long __dpd_fixunssddi (<var>_Decimal32 a</var>)<var></var>

— Runtime Function: unsigned long __bid_fixunssddi (<var>_Decimal32 a</var>)<var></var>

— Runtime Function: unsigned long __dpd_fixunsdddi (<var>_Decimal64 a</var>)<var></var>

— Runtime Function: unsigned long __bid_fixunsdddi (<var>_Decimal64 a</var>)<var></var>

— Runtime Function: unsigned long __dpd_fixunstddi (<var>_Decimal


A06-9A0C, U+9A10-9A15, U+9A17-9A18, U+9A1A-9A2A, U+9A2C, U+9A2F, U+9A31-9A35,
    U+9A39-9A3D, U+9A3F, U+9A46-9A49, U+9A4B-9A4C, U+9A4E, U+9A50-9A54, U+9A56, U+9A58-9A59, U+9A5C-9A5E, U+9A60-9A61,
    U+9A63, U+9A66-9A69, U+9A6B, U+9A72, U+9A83, U+9A89, U+9A8D-9A8E, U+9A94-9A95;
}
@font-face {
  font-family: 'Xiaolai';
  src:
    local('Xiaolai'),
    url('./27fec93b7ffb48398518f704ea19e5a3.woff2') format('woff2');
  font-style: normal;
  font-display: swap;
  font-weight: 400;
  unicode-range:
    U+9836, U+983A, U+983C-9845, U+9847-984B, U+9850-9852, U+9854-9857, U+985A, U+985C-985D, U+985F-9861, U+9863-9864,
    U+9866, U+9868-986A, U+986D-986E, U+9872, U+988B, U+988E, U+9892, U+9895, U+9899, U+98A3, U+98A9-98AD, U+98B0-98B5,
    U+98B7-98BB, U+98BD-98C3, U+98C5, U+98C7, U+98C9-98CD, U+98CF-98D0, U+98D4, U+98D6-98D7, U+98DC-98DD, U+98E1,
    U+98E3-98E6, U+98EC, U+98EE, U+98F0-98F1, U+98F3, U+98F5-98FB, U+98FF-9902, U+9904, U+9906-9907, U+990B,
    U+990E-990F, U+9914-9917, U+9919, U+991C-991D, U+991F-9920, U+9922-9927, U+9929-992D, U+992F-9930, U+9932,
    U+9934-9936, U+9938-993B, U+993D, U+9940-9942, U+9944, U+9946-9947, U+994D-9951, U+9953, U+9956, U+9958-995B,
    U+995D, U+995F-9961, U+9964, U+9966, U+9973, U+9978-9979, U+997B;
}
@font-face {
  font-family: 'Xiaolai';
  src:
    local('Xiaolai'),
    url('./44084d52e186a66ff03f6e9f7371d806.woff2') format('woff2');
  font-style: normal;
  font-display: swap;
  font-weight: 400;
  unicode-range:
    U+973A-973C, U+973F-9741, U+9743, U+9745-9747, U+9749-9751, U+9754


:             env.MustNewMnemonic(),
		NumValidators:        numValidators,
		ValidatorsPerGroup:   1,
		NumDeveloperAccounts: numExternal,
	}
}

// BuildConfig generates genesis and eth config instances, that can be modified
// before passing to NewNetwork or NewNode.
//
// NOTE: Do not edit the Istanbul field of the returned genesis config it will
// be overwritten with the corresponding config from the Istanbul field of the
// returned eth config.
func BuildConfig(accounts *env.AccountsConfig, gingerbreadBlock, l2MigrationBlock *big.Int) (*genesis.Config, *ethconfig.Config, error) {
	gc, err := genesis.CreateCommonGenesisConfig(
		big.NewInt(1),
		accounts.AdminAccount().Address,
		params.IstanbulConfig{},
		gingerbreadBlock,
	)
	if err != nil {
		return nil, nil, err
	}

	genesis.FundAccounts(gc, accounts.DeveloperAccounts())

	// copy the base eth config, so we can modify it without damaging the
	// original.
	ec := &eth.Config{}
	err = copyObject(BaseEthConfig, ec)
	ec.L2MigrationBlock = l2MigrationBlock
	return gc, ec, err
}

// GenerateGenesis checks that the contractsBuildPath exists and if so proceeds to generate the genesis.
func GenerateGenesis(accounts *env.AccountsConfig, gc *genesis.Config, contractsBuildPath string) (*core.Genesis, error) {
	// Check for the existence of the compiled-system-contracts dir
	_, err := os.Stat(contractsBuildPath)
	if errors.Is(err, os.ErrNotExist) {
		abs, err := filepath.Abs(contractsBuildPath)
		if err != nil {
			panic(fmt.Sprintf("failed to get abs path for %s, error: %v", contractsBuildPath, err))
		}
		return nil, fmt.Errorf("Could not find dir %s, try running 'make prepare-system-contracts' and then re-running the test", abs)

	}
	return genesis.GenerateGenesis(accounts, gc, contractsBuildPath)
}

// NewNetwork generates a network of nodes that are running and mining. For
// each provided validator account a corresponding node is created and each
// node is also assigned a developer account, there must be at least as many
// developer accounts provided as validator accounts. A shutdown function is
// also returned which will shutdown and clean up the network when called.  In
// the case that an error is returned the shutdown function will be nil and so
// no attempt should be made to call it.
func NewNetwork(accounts *env.AccountsConfig, gc *genesis.Config, ec *eth.Config) (Network, func(), error) {

	// Copy eth istanbul config fields to the genesis istanbul config.
	// There is a ticket to remove this duplication of config.
	// https://github.com/celo-org/celo-blockchain/issues/1693
	gc.Istanbul = params.IstanbulConfig{
		Epoch:          ec.Istanbul.Epoch,
		ProposerPolicy: uint64(ec.Istanbul.ProposerPolicy),
		LookbackWindow: ec.Istanbul.DefaultLookbackWindow,
		BlockPeriod:    ec.Istanbul.BlockPeriod,
		RequestTimeout: ec.Istanbul.RequestTimeout,
	}

	genesis, err := GenerateGenesis(accounts, gc, "../compiled-system-contracts")
	if err != nil {
		return nil, nil, fmt.Errorf("failed to generate genesis: %v", err)
	}

	va := accounts.ValidatorAccounts()
	var network Network = make([]*Node, len(va))

	for i := range va {
		n, err := NewNode(&va[i], baseNodeConfig, ec, genesis)
		if err != nil {
			return nil, nil, fmt.Errorf("failed to build node for network: %v", err)
		}
		network[i] = n


isEqual ? getStartOfDay(date).getTime() >= getStartOfDay(after).getTime() : getStartOfDay(date).getTime() > getStartOfDay(after).getTime();
}

export function isDateBefore(date: Date, before: Date, isEqual: boolean = false): boolean {
    return isEqual ? getStartOfDay(date).getTime() <= getStartOfDay(before).getTime() : getStartOfDay(date).getTime() < getStartOfDay(before).getTime();
}

/**
 * Export an array of all the available months
 */
export const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
export const monthsShort = getShortMonthNames();

function getShortMonthNames(): string[] {
    return months.map(month => month.substring(0, 3));
}

/**
 * Export an array of all the available days of the week
 */
export const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
export const weekdaysShort = getShortWeekdayNames();
export const meridians = ['AM', 'PM'];

function getShortWeekdayNames(): string[] {
    return weekdays.map(weekday => weekday.substring(0, 3));
}

/** Export the default set of time zone */
export const timezones: DateTimePickerTimezone[] = [
    { name: 'GMT-11', offset: 660 },
    { name: 'GMT-10', offset: 600 },
    { name: 'GMT-9', offset: 540 },
    { name: 'GMT-8', offset: 480 },
    { name: 'GMT-7', offset: 420 },
    { name: 'GMT-6', offset: 360 },
    { name: 'GMT-5', offset: 300 },
    { name: 'GMT-4', offset: 240 },
    { name: 'GMT-3', offset: 180 },
    { name: 'GMT-2', offset: 120 },
    { name: 'GMT-1', offset: 60 },
    { name: 'GMT', offset: 0 },
    { name: 'GMT+1', offset: -60 },
    { name: 'GMT+2', offset: -120 },
    { name: 'GMT+3', offset: -180 },
    { name: 'GMT+4', offset: -240 },
    { name: 'GMT+5', offset: -300 },
    { name: 'GMT+6', offset: -360 },
    { name: 'GMT+7', offset: -420 },
    { name: 'GMT+8', offset: -480 },
    { name: 'GMT+9', offset: -540 },
    { name: 'GMT+10', offset: -600 },
    { name: 'GMT+11', offset: -660 },
    { name: 'GMT+12', offset: -720 }
];

export interface DateTimePickerTimezone {
    name: string;
    offset: number;
}
/**
 * A valid JavaScript Object Notation (JSON) value type.
 */
export type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
import {BuildOptions, DataTypes, Model, Sequelize} from 'sequelize';

export interface IPricing extends Model {
  readonly id: string;
  readonly name: string;
  readonly description: string;
  readonly price: number;
  readonly isDefault: boolean;
  readonly order: number;

  readonly createdAt: Date;
  readonly updatedAt: Date;
}

export type PricingModelStatic = typeof Model & {
  new (values?: object, options?: BuildOptions): IPricing;
};

export function getPricing(sequelize: Sequelize): PricingModelStatic {
  return <PricingModelStatic>sequelize.define(
    'Pricing',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      name: {
        type: DataTypes.STRING,
      },
      description: {
        type: DataTypes.STRING,
      },
      price: {
        type: DataTypes.FLOAT,
      },


# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from aliyunsdkcore.request import RpcRequest
from aliyunsdksas.endpoint import endpoint_data

class ListAgentlessRegionRequest(RpcRequest):

	def __init__(self):
		RpcRequest.__init__(self, 'Sas', '2018-12-03', 'ListAgentlessRegion','sas')
		self.set_method('POST')

		if hasattr(self, "endpoint_map"):
			setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
		if hasattr(self, "endpoint_regional"):
			setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())


return
	}

	// Otherwise, answer the request as normal, making sure to unlock the moment we're
	// no longer using stuff from PluginManager
	serveKey := pm.start
	if overlay, ok := r.Header["X-Heedy-Overlay"]; ok {
		if len(overlay) != 1 {
			pm.RUnlock()
			rest.WriteJSONError(w, r, http.StatusBadRequest, errors.New("plugin_error: invalid overlay"))
			return
		}
		if overlay[0] == "none" {
			serveKey = "none"
		}
		if overlay[0] == "next" {
			// The overlay is next, so find which plugin we're coming from
			serveKey = pm.Plugins[ctx.Plugin].Next

		}
	}

	// The object manager gives the full API, with all objects well-defined
	if serveKey == "none" {
		var sm http.Handler = pm.ObjectManager
		if sm == nil {
			sm = pm.Handler
		}
		pm.RUnlock()
		sm.ServeHTTP(w, r)
		return
	}
	// If serveKey is not none, serve the given plugin
	pmux := pm.Plugins[pm.start].Plugin.Mux
	pm.RUnlock()

	// Delete the overlay header if we're going to pass through plugins
	delete(r.Header, "X-Heedy-Overlay")
	pmux.ServeHTTP(w, r)

}
package updater

import (
	"encoding/json"
	"errors"
	"io"
	"os"
	"path"

	"io/ioutil"

	"github.com/heedy/heedy/backend/assets"
	"github.com/sirupsen/logrus"
)

type UpdateInfo struct {
	Heedy   bool           `json:"heedy"`
	Config  bool           `json:"config"`
	Plugins []string       `json:"plugins"`
	Options *UpdateOptions `json:"options"`
}

func GetInfo(configDir string) (ui UpdateInfo, err error) {
	updateDir := path.Join(configDir, "updates")
	_, err = os.Stat(path.Join(updateDir, "heedy.conf"))
	ui.Config = err == nil
	_, err = os.Stat(path.Join(updateDir, "heedy"))
	ui.Heedy = err == nil

	var d []os.FileInfo
	d, err = ioutil.ReadDir(path.Join(updateDir, "plugins"))
	if err != nil {
		ui.Plugins = make([]string, 0)
	} else {
		s := make([]string, len(d))
		for i := range d {
			s[i] = d[i].Name()
		}
		ui.Plugins = s
	}
	ui.Options, err = ReadOptions(configDir)
	return
}

func ClearUpdates(configDir string) error {
	updateDir := path.Join(configDir, "updates")
	return os.RemoveAll(updateDir)
}

func Available(configDir string) bool {
	updateDir := path.Join(configDir, "updates")
	_, err := os.Stat(updateDir)
	return err == nil
}

func ReadConfigFile(configDir string) ([]byte, error) {
	b, err := ioutil.ReadFile(path.Join(configDir, "updates", "heedy.conf"))
	if err == nil {
		return b, err
	}
	return ioutil.ReadFile(path.Join(configDir, "heedy.conf"))
}

func ModifyConfigFile(configDir string, c *assets.Configuration) error {
	configHeedy := path.Join(configDir, "heedy.conf")
	updateHeedy := path.Join(configDir, "updates", "heedy.conf")

	if _, err := os.Stat(updateHeedy); os.IsNotExist(err) {
		// The file does not exist, copy over heedy.conf
		err = CopyFile(configHeedy, updateHeedy)
		if err != nil {
			return err


(gpbuttons[16].Pressed)
                buttons |= Buttons.BigButton;

            GamePadDPad dPad = new GamePadDPad(
                (gpbuttons[12].Pressed) ? ButtonState.Pressed : ButtonState.Released, // DPadUp
                (gpbuttons[13].Pressed) ? ButtonState.Pressed : ButtonState.Released, // DpadDown
                (gpbuttons[14].Pressed) ? ButtonState.Pressed : ButtonState.Released, // DpadLeft
                (gpbuttons[15].Pressed) ? ButtonState.Pressed : ButtonState.Released  // DpadRight
            );

            int packetNumber = gamepad.Timestamp;

            state = base.CreateGamePadState(thumbSticks, triggers, new GamePadButtons(buttons), dPad,
                                                       packetNumber: packetNumber);
            return state;
        }

        private GamePadCapabilities CreateCapabilities(Gamepad gamepad)
        {
            //--
            GamePadType gamePadType = GamePadType.Unknown;
            string displayName = String.Empty;
            string identifier = String.Empty;
            bool isConnected = false;
            Buttons buttons = (Buttons)0;
            bool hasLeftVibrationMotor = false;
            bool hasRightVibrationMotor = false;
            bool hasVoiceSupport = false;
            //--

            {
                displayName = gamepad.Id;

                isConnected = true;
                if (gamepad.Mapping == "standard")
                    gamePadType = GamePadType.GamePad;
                buttons |= Buttons.A;
                buttons |= Buttons.B;
                buttons |= Buttons.X;
                buttons |


		// the stack, but put it in gp.stack before mstart,
		// so the logic above hasn't set osStack yet.
		osStack = true
	}
	mexit(osStack)
}

// The go:noinline is to guarantee the getcallerpc/getcallersp below are safe,
// so that we can set up g0.sched to return to the call of mstart1 above.
//
//go:noinline
func mstart1() {
	gp := getg()

	if gp != gp.m.g0 {
		throw("bad runtime·mstart")
	}

	// Set up m.g0.sched as a label returning to just
	// after the mstart1 call in mstart0 above, for use by goexit0 and mcall.
	// We're never coming back to mstart1 after we call schedule,
	// so other calls can reuse the current frame.
	// And goexit0 does a gogo that needs to return from mstart1
	// and let mstart0 exit the thread.
	gp.sched.g = guintptr(unsafe.Pointer(gp))
	gp.sched.pc = getcallerpc()
	gp.sched.sp = getcallersp()

	asminit()
	minit()

	// Install signal handlers; after minit so that minit can
	// prepare the thread to be able to handle the signals.
	if gp.m == &m0 {
		mstartm0()
	}

	if fn := gp.m.mstartfn; fn != nil {
		fn()
	}

	if gp.m != &m0 {
		acquirep(gp.m.nextp.ptr())
		gp.m.nextp = 0
	}
	schedule()
}

// mstartm0 implements part of mstart1 that only runs on the m0.
//
// Write barriers are allowed here because we know the GC can't be
// running yet, so they'll be no-ops.
//
//go:yeswritebarrierrec
func mstartm0() {
	// Create an extra M for callbacks on threads not created by Go.
	// An extra M is also needed on Windows for callbacks created by
	// syscall.NewCallback. See issue #6751 for details.
	if (iscgo || GOOS == "windows") && !cgoHasExtraM {
		cgoHasExtraM = true
		newextram()
	}
	initsig(false)
}

// mPark causes a thread to park itself, returning once woken.
//
//go:nosplit
func mPark() {
	gp := getg()
	notesleep(&gp.m.park)
	noteclear(&gp.m.park)
}

// mexit tears down and exits the current thread.
//
// Don't call this directly to exit the thread, since it must run at
// the top of the thread stack. Instead, use gogo(&gp.m.g0.sched) to
// unwind the stack to the point that exits the thread.
//
// It is entered with m.p != nil, so write barriers are allowed. It
// will release the P before exiting.
//
//go:yeswritebarrierrec
func mexit(osStack bool) {
	mp := getg().m

	if mp == &m0 {
		// This is the main thread. Just wedge it.
		//
		// On Linux, exiting the main thread puts the process
		// into a non-waitable zombie state. On Plan 9,
		// exiting the main thread unblocks wait even though
		// other threads are still running. On Solaris we can
		// neither exitThread nor return from mstart. Other
		// bad things probably happen on other platforms.
		//
		// We could try to clean up this M more before wedging
		// it, but that complicates signal handling.
		handoffp(releasep())
		lock(&sched.lock)
		sched.nmfreed++
		checkdead()
		unlock(&sched.lock)
		mPark()
		throw("locked m0 woke up")
	}

	sigblock(true)
	unminit()

	// Free the gsignal stack.
	if mp.


mr r5, r3
/* 80380534 0037D334  48 05 1B 89 */	bl PSVECSubtract
/* 80380538 0037D338  38 7B 00 7C */	addi r3, r27, 0x7c
/* 8038053C 0037D33C  38 81 00 08 */	addi r4, r1, 8
/* 80380540 0037D340  7C 65 1B 78 */	mr r5, r3
/* 80380544 0037D344  48 05 1B 79 */	bl PSVECSubtract
/* 80380548 0037D348  38 7B 00 70 */	addi r3, r27, 0x70
/* 8038054C 0037D34C  38 81 00 08 */	addi r4, r1, 8
/* 80380550 0037D350  7C 65 1B 78 */	mr r5, r3
/* 80380554 0037D354  48 05 1B 69 */	bl PSVECSubtract
/* 80380558 0037D358  38 80 00 00 */	li r4, 0
/* 8038055C 0037D35C  38 00 00 01 */	li r0, 1
/* 80380560 0037D360  B0 9B 00 1C */	sth r4, 0x1c(r27)
/* 80380564 0037D364  7F 63 DB 78 */	mr r3, r27
/* 80380568 0037D368  C0 02 E5 B4 */	lfs f0, lbl_805E4CB4@sda21(r2)
/* 8038056C 0037D36C  B0 9B 00 1A */	sth r4, 0x1a(r27)
/* 80380570 0037D370  98 1B 00 18 */	stb r0, 0x18(r27)
/* 80380574 0037D374  98 9B 00 55 */	stb r4, 0x55(r27)
/* 80380578 0037D378  D0 1B 00 44 */	stfs f0, 0x44(r27)
/* 8038057C 0037D37C  D0 1B 00 38 */	stfs f0, 0x38(r27)
/* 80380580 0037D380  D0 1B 00 2C */	stfs f0, 0x2c(r27)
/* 80380584 0037D384  D0 1B 00 48 */	stfs f0, 0x48(r27)
/* 80380588 0037D388  D0 1B 00 3C */	stfs f0, 0x3c(r27)
/* 8038058C 0037D38C  D0 1B 00 30 */	stfs f0, 0x30(r27)
/* 80380590 0037D390  D0 1B 00 4C */	stfs f0, 0x4c(r27)
/* 80380594 0037D394  D0 1B 00 40 */	stfs f0, 0x40(r27)
/* 80380598 0037D398  D0 1B 00 34 */	stfs f0, 0x34(r27)
/* 8038059C 0037D39C  39 61 00 30 */	addi r11, r1, 0x30
/* 803805A0 0037D3A0  48 02 D6 01 */	bl _restgpr_27
/* 803805A4 0037D3A4  80 01 00 34 */	lwz r0, 0x34(r1)
/* 803805A8 0037D3A8  7C 08 03 A6 */	mtlr r0
/* 803805AC 0037D3AC  38 21 00 30 */	addi r1, r1, 0x30
/* 803805B0 0037D3B0  4E 80 00 20 */	blr

.global func_803805B4
func_803805B4:
/* 803805B4 0037D3B4  94 21 FF F0 */	stwu r1, -0x10(r1)
/* 803805


 register value		; 4
	sta	MOCK_6522_ORA2		; put value on PA2		; 4
	lda	#MOCK_AY_WRITE		;				; 2
	sta	MOCK_6522_ORB2		; write on PB2			; 4
	lda	#MOCK_AY_INACTIVE	; go inactive			; 2
	sta	MOCK_6522_ORB2						; 4

mb_no_write_right:
	inx				; point to next register	; 2
	cpx	#12			; if 12 we're done		; 2
	bmi	mb_write_loop		; otherwise, loop		; 3/2nt

	;=====================================
	; Copy registers to old
	;=====================================
	ldx	#13							; 2
mb_reg_copy:
	lda	REGISTER_DUMP,X	; load register value			; 4
	sta	REGISTER_OLD,X	; compare with old values		; 4
	lda	REGISTER_DUMP2,X; load register value			; 4
	sta	REGISTER_OLD2,X	; compare with old values		; 4
	dex								; 2
	bpl	mb_reg_copy						; 2nt/3

	;===================================
	; Load all 14 registers in advance
	;===================================
	; note, assuming not cross page boundary, not any slower
	; then loading from zero page?

mb_load_values:

	ldx	#0		; set up reg count			; 2
	ldy	MB_CHUNK_OFFSET	; get chunk offset			; 3
								;=============
								;	5

mb_load_loop:
	lda	(INL),y		; load register value			; 5

	cpx	#11
	bne	mb_load12
mb_load11:
	sta	REGISTER_DUMP2+2
	jmp	mb_done_load
mb_load12:
	cpx	#12
	bne	mb_load13
	sta	REGISTER_DUMP2+3
	jmp	mb_done_load
mb_load13:
	cpx	#13
	bne	mb_regular_load
	sta	REGISTER_DUMP2+9
	jmp	mb_done_load
mb_regular_load:
	sta	REGISTER_DUMP,X						; 4
	sta	REGISTER_DUMP2,X

mb_done_load:

	;====================
	; point to next page
	;====================

	clc				; point to next interleaved	; 2
	lda	INH			; page by adding CHUNKSIZE (3/1); 3
	adc	CHUNKSIZE						; 3
	sta	INH							; 3

	inx				; point to next register	; 2
	cpx	#14			; if 14 we're done		; 2
	bmi	mb_load_loop		; otherwise, loop		; 3/2nt
								;============
								; 	18

	;=========================================
	; if A_COARSE_TONE is $ff then we are done

	lda	A_COARSE_TONE						; 3
	bpl	mb_not_done						; 3/2nt

quiet_exit:
	lda	#1		; set done playing			; 2
	sta	DONE_PLAYING
	jsr	clear_ay_both

	;=====================================
	; clear register area
	;=====================================
	ldx	#13							; 2
	lda	#0							; 2
mb_clear_reg:
	sta	REGISTER_DUMP,X ; clear register value			; 4
	sta	REGISTER_OLD,X	; clear old values			; 4
	dex								; 2
	bpl	mb_clear_reg						; 2nt/3

	jmp	exit_interrupt

mb_not_done:

	;==============================================
	; incremement offset.  If 0 move to next chunk
	;==============================================

increment_offset:

	inc	MB_CHUNK_OFFSET		;


olate));
}

i::Address* HandleScope::CreateHandle(i::Isolate* isolate, i::Address value) {
  return i::HandleScope::CreateHandle(isolate, value);
}

EscapableHandleScope::EscapableHandleScope(Isolate* v8_isolate) {
  i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
  escape_slot_ =
      CreateHandle(isolate, i::ReadOnlyRoots(isolate).the_hole_value().ptr());
  Initialize(v8_isolate);
}

i::Address* EscapableHandleScope::Escape(i::Address* escape_value) {
  i::Heap* heap = reinterpret_cast<i::Isolate*>(GetIsolate())->heap();
  Utils::ApiCheck(i::Object(*escape_slot_).IsTheHole(heap->isolate()),
                  "EscapableHandleScope::Escape", "Escape value set twice");
  if (escape_value == nullptr) {
    *escape_slot_ = i::ReadOnlyRoots(heap).undefined_value().ptr();
    return nullptr;
  }
  *escape_slot_ = *escape_value;
  return escape_slot_;
}

void* EscapableHandleScope::operator new(size_t) { base::OS::Abort(); }
void* EscapableHandleScope::operator new[](size_t) { base::OS::Abort(); }
void EscapableHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
void EscapableHandleScope::operator delete[](void*, size_t) {
  base::OS::Abort();
}

SealHandleScope::SealHandleScope(Isolate* isolate)
    : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
  i::HandleScopeData* current = isolate_->handle_scope_data();
  prev_limit_ = current->limit;
  current->limit = current->next;
  prev_sealed_level_ = current->sealed_level;
  current->sealed_level = current->level;
}

SealHandleScope::~SealHandleScope() {
  i::HandleScopeData* current = isolate_->handle_scope_data();
  DCHECK_EQ(current->next, current->limit);
  current->limit = prev_limit_;
  DCHECK_EQ(current->level, current->sealed_level);
  current->sealed_level = prev_sealed_level_;
}

void* SealHandleScope::operator new(size_t) { base::OS::Abort(); }
void* SealHandleScope::operator new[](size_t) { base::OS::Abort(); }
void SealHandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
void SealHandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }

void Context::Enter() {
  i::Handle<i::Context> env = Utils::OpenHandle(this);
  i::Isolate* isolate = env->GetIsolate();
  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
  i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
  impl->EnterContext(*env);
  impl->SaveContext(isolate->context());
  isolate->set_context(*env);
}

void Context::Exit() {
  i::Handle<i::Context> env = Utils::OpenHandle(this);
  i::Isolate* isolate = env->GetIsolate();
  ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
  i::HandleScopeImplementer* impl = isolate->handle_scope_implementer();
  if (!Utils::ApiCheck(impl->LastEnteredContextWas(*env), "v8::Context::Exit()",
                       "Cannot exit non-entered context")) {
    return;
  }
  impl->LeaveContext();
  isolate->set_context(impl->RestoreContext());
}

Context::BackupIncumbentScope::BackupIncumbentScope(
    Local<Context> backup_incumbent_context)
    : backup_incumbent_context_(backup_incumbent_context) {
  DCHECK(!backup_incumbent_context_.IsEmpty());


# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Implementation of managed-folders remove-iam-policy-binding command."""

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from googlecloudsdk.api_lib.storage import api_factory
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.iam import iam_util
from googlecloudsdk.command_lib.storage import errors_util
from googlecloudsdk.command_lib.storage import iam_command_util
from googlecloudsdk.command_lib.storage import storage_url
from googlecloudsdk.command_lib.storage.tasks import set_iam_policy_task

@base.UniverseCompatible
class RemoveIamPolicyBinding(base.Command):
  """Remove an IAM policy binding from a managed folder."""

  detailed_help = {
      'DESCRIPTION': """
      Remove a policy binding from the IAM policy of a managed folder, given a managed folder
      URL and the binding. For more information, see [Cloud
      Identity and Access
      Management](https://cloud.google.com/storage/docs/access-control/iam).
      """,
      'EXAMPLES': """
      To remove an IAM policy binding from the role of
      roles/storage.objectCreator for the user john.doe@example.com on a managed folder `managed-folder` in a bucket `bucket`:

        $ {command} gs://bucket/managed-folder --member=user:john.doe@example.com --role=roles/storage.objectCreator
      """,
  }

  @staticmethod
  def Args(parser):
    parser.add_argument(
        'url', help='URL of managed folder to remove IAM policy binding from.'
    )
    iam_util.AddArgsForRemoveIamPolicyBinding(parser, add_condition=True)

  def Run(self, args):
    url = storage_url.storage_url_from_string(args.url)
    errors_util.raise_error_if_not_gcs_folder_type(args.command_path, url)
    policy = api_factory.get_api(url.scheme).get_managed_folder_iam_policy(
        url.bucket_name, url.resource_name
    )
    return iam_command_util.remove_iam_binding_from_resource(
        args,
        url,
        policy,
        set_iam_policy_task.SetManagedFolderIamPolicyTask,
    )


= MenuNodeMainGui or class(MenuNodeGui)

function MenuNodeMainGui:_setup_item_rows(node)
	MenuNodeMainGui.super._setup_item_rows(self, node)
	self:_add_version_string()
	managers.features:announce_feature("short_heists_available")
end

function MenuNodeMainGui:set_visible(visible)
	MenuNodeMainGui.super.set_visible(self, visible)
	self:_add_version_string()
end

function MenuNodeMainGui:_add_version_string()
	if alive(self._version_string) then
		self._version_string:parent():remove(self._version_string)
		self._version_string = nil
	end
	if Application:debug_enabled() or SystemInfo:platform() == Idstring("WIN32") then
		local version = Application:version()
		self._version_string = self.ws:panel():text({
			name = "version_string",
			text = version,
			font = tweak_data.menu.pd2_small_font,
			font_size = tweak_data.menu.pd2_small_font_size,
			align = "left",
			vertical = "bottom",
			alpha = 0.5
		})
		local fade_in = function(o)
			local from = Color(0, 1, 1, 1)
			local to = Color(1, 1, 1, 1)
			local t = 0
			o:set_color(from)
			while t < 4 do
				local dt = coroutine.yield()
				t = t + dt
			end
			t = 0
			while t < 1 do
				local dt = coroutine.yield()
				t = t + dt
				o:set_color(from * (1 - t) + to * t)
			end
			o:set_color(to)
		end
		self._version_string:animate(fade_in)
	end
end


alpha(opacity=20)}.close:hover,.close:focus{color:#ffffff;text-decoration:none;cursor:pointer;opacity:0.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal-open{overflow:hidden}.modal{display:none;overflow:hidden;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translate(0, -25%);-ms-transform:translate(0, -25%);-o-transform:translate(0, -25%);transform:translate(0, -25%);-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0, 0);-ms-transform:translate(0, 0);-o-transform:translate(0, 0);transform:translate(0, 0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#ffffff;border:1px solid #999999;border:1px solid rgba(0,0,0,0.2);border-radius:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,0.5);box-shadow:0 3px 9px rgba(0,0,0,0.5);-webkit-background-clip:padding-box;background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:0.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.4}.modal-body{position:relative;padding:20px}.modal-footer{padding:20px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,0.5);box-shadow:0 5px 15px rgba(0,0,0,0.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-style:normal;font-weight:normal;letter-spacing:normal;line-break:auto;line-height:1.4;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;white-space:normal;word-break:normal;word-spacing:normal;word-wrap:normal;font-size:12px;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:0.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.too


"""Test for Unicode title bug in from_dict"""

import sys
sys.path.insert(0, '/root/hypothesis-llm/envs/troposphere_env/lib/python3.13/site-packages')

import troposphere.codepipeline as cp

# Test 1: Direct construction with Unicode title fails
print("Test 1: Direct construction with Unicode title")
try:
    artifact = cp.ArtifactDetails(
        title='µ',
        MaximumCount=1,
        MinimumCount=0
    )
    print("  SUCCESS: Created with Unicode title")
except ValueError as e:
    print(f"  FAILED: {e}")

# Test 2: from_dict with Unicode title also fails
print("\nTest 2: from_dict with Unicode title")
try:
    artifact = cp.ArtifactDetails.from_dict('µ', {
        'MaximumCount': 1,
        'MinimumCount': 0
    })
    print("  SUCCESS: Created from dict with Unicode title")
except ValueError as e:
    print(f"  FAILED: {e}")

# Test 3: What if we bypass validation?
print("\nTest 3: Bypassing validation")
try:
    artifact = cp.ArtifactDetails(
        title='µ',
        MaximumCount=1,
        MinimumCount=0,
        validation=False
    )
    print(f"  SUCCESS: Created with validation=False, title='{artifact.title}'")

    # Can we convert to dict?
    dict_repr = artifact.to_dict(validation=False)
    print(f"  SUCCESS: Converted to dict: {dict_repr}")

    # Can we reconstruct from dict?
    reconstructed = cp.ArtifactDetails.from_dict('µ', dict_repr)
    print(f"  SUCCESS: Reconstructed from dict")
except Exception as e:
    print(f"  FAILED: {e}")

# Test 4: Test that the error message is misleading
print("\nTest 4: Error message accuracy")
unicode_char = 'µ'
print(f"  Character '{unicode_char}':")
print(f"    - Python's isalnum(): {unicode_char.isalnum()}")
print(f"    - Python's isalpha(): {unicode_char.isalpha()}")
print(f"    - Unicode category: {__import__('unicodedata').category(unicode_char)}")
print(f"    - troposphere error: 'not alphanumeric' (but it IS alphanumeric!)")


using FluentResults;
using MainCore.Errors;
using MainCore.Helper.Interface;
using MainCore.Parsers.Interface;
using MainCore.Services.Interface;
using Microsoft.EntityFrameworkCore;
using OpenQA.Selenium;
using System.Linq;

namespace MainCore.Helper.Implementations.Base
{
    public sealed class LoginHelper : ILoginHelper
    {
        private readonly IChromeManager _chromeManager;

        private readonly IGeneralHelper _generalHelper;
        private readonly IUpdateHelper _updateHelper;
        private readonly IDbContextFactory<AppDbContext> _contextFactory;

        private readonly ISystemPageParser _systemPageParser;

        public LoginHelper(IChromeManager chromeManager, IGeneralHelper generalHelper, IDbContextFactory<AppDbContext> contextFactory, ISystemPageParser systemPageParser, IUpdateHelper updateHelper)
        {
            _chromeManager = chromeManager;
            _generalHelper = generalHelper;
            _contextFactory = contextFactory;
            _systemPageParser = systemPageParser;
            _updateHelper = updateHelper;
        }

        public Result Execute(int accountId)
        {
            var result = AcceptCookie(accountId);
            if (result.IsFailed) return result.WithError(new Trace(Trace.TraceMessage()));

            result = Login(accountId);
            if (result.IsFailed) return result.WithError(new Trace(Trace.TraceMessage()));

            _updateHelper.Update(accountId);
            return Result.Ok();
        }

        private Result AcceptCookie(int accountId)
        {
            var chromeBrowser = _chromeManager.Get(accountId);
            var html = chromeBrowser.GetHtml();

            if (html.DocumentNode.Descendants("a").Any(x => x.HasClass("cmpboxbtn") && x.HasClass("cmpboxbtnyes")))
            {
                var result = _generalHelper.Click(accountId, B


timer = null;
  }

  /// Stop animating the progress indicator.
  ///
  /// This will continue running the stopwatch so that the full time can be
  /// logged in [stop].
  void stopAnimating() {
    if (_timer == null) return;

    // Erase the time indicator so that we don't leave a misleading
    // half-complete time indicator on the console.
    stdout.writeln('\b' * _timeLength);
    _timeLength = 0;
    _timer!.cancel();
    _timer = null;
  }

  /// Refreshes the progress line.
  void _update() {
    if (log.isMuted) return;

    // Show the time only once it gets noticeably long.
    if (_stopwatch.elapsed.inSeconds == 0) return;

    // Erase the last time that was printed. Erasing just the time using `\b`
    // rather than using `\r` to erase the entire line ensures that we don't
    // spam progress lines if they're wider than the terminal width.
    stdout.write('\b' * _timeLength);
    final time = _time;
    _timeLength = time.length;
    stdout.write(log.gray(time));
  }
}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';

import 'package:glob/glob.dart';
import 'package:glob/list_local_fs.dart';
import 'package:path/path.dart' as p;
import 'package:pub_semver/pub_semver.dart';

import 'exceptions.dart';
import 'git.dart' as git;
import 'ignore.dart';
import 'io.dart';
import 'language_version.dart';
import 'log.dart' as log;
import 'package_name.dart';
import 'pubspec.dart';
import 'utils.dart';

/// A Package is a [Pubspec] and a directory where it belongs that can be used
/// for version solving or as a node in a package graph.
class Package {
  /// Compares [a] and [b] orders them by name then version number.
  ///
  /// This is normally used as a [Comparator] to pass to sort. This does not
  /// take a package's description or root directory into account, so multiple
  /// distinct packages may order the same.
  static int orderByNameAndVersion(Package a, Package b) {
    final name = a.name.compareTo(b.name);
    if (name != 0) return name;

    return a.version.compareTo(b.version);
  }

  /// The path to the directory containing the package.
  final String dir;

  /// A version of [dir] adapted for presenting in the terminal.
  ///
  /// If [dir] is just a parent directory like ../.. it gets replaced with
  /// the absolute dir.
  late final String presentationDir =
      p.isWithin(dir, '.') ? p.normalize(p.absolute(dir)) : dir;

  /// The name of the package.
  String get name => pubspec.name;

  /// The package's version.
  Version get version => pubspec.version;

  /// The parsed pubspec associated with this package.
  final Pubspec pubspec;

  /// The path to the entrypoint package's pubspec.
  String get pubspecPath => p.normalize(p.join(dir, 'pubspec.yaml'));

  /// The path to the entrypoint package's pubspec overrides file.
  String get pubspecOverridesPath =>
      p.normalize(p.join(dir, 'pubspec_overrides.yaml'));

  /// The (non-transitive) workspace packages.
  final List<Package> workspaceChildren;

  /// The transitive closure of [workspaceChildren] rooted at this package.
  ///
  /// Includes this package.
  Iterable<Package> get transitiveWorkspace sync* {
    final stack = [this];

    while (stack.isNotEmpty) {
      final current = stack.remove


 */
package me.ahoo.wow.messaging.function

import me.ahoo.wow.api.messaging.Message
import me.ahoo.wow.api.messaging.function.FunctionInfo
import me.ahoo.wow.api.messaging.function.FunctionKind
import me.ahoo.wow.api.modeling.NamedAggregate
import me.ahoo.wow.api.naming.NamedBoundedContext
import me.ahoo.wow.api.naming.QualifiedNamed
import me.ahoo.wow.infra.reflection.AnnotationScanner.scanAnnotation
import me.ahoo.wow.messaging.handler.MessageExchange

interface MessageFunction<P : Any, in M : MessageExchange<*, *>, out R> : QualifiedNamed, FunctionInfo {

    /**
     * Message body types supported by the message function.
     */
    val supportedType: Class<*>

    /**
     * @see me.ahoo.wow.api.annotation.OnEvent.value
     * @see me.ahoo.wow.api.annotation.OnStateEvent.value
     */
    val supportedTopics: Set<NamedAggregate>
    val processor: P
    override val processorName: String
        get() = processor::class.java.simpleName

    /**
     * The fully qualified name of the function.
     */
    override val qualifiedName: String
        get() = "$processorName.$name(${supportedType.simpleName})"

    fun <M> supportMessage(message: M): Boolean
        where M : Message<*, Any>, M : NamedBoundedContext, M : NamedAggregate {
        return supportedType.isInstance(message.body) &&
            supportedTopics.any {
                it.isSameAggregateName(message)
            }
    }

    fun <A : Annotation> getAnnotation(annotationClass: Class<A>): A?
    operator fun invoke(exchange: M): R

    fun handle(exchange: M): R {
        return invoke(exchange)
    }
}

interface MessageFunctionAccessor<P : Any, in M : MessageExchange<*, *>, out R> : MessageFunction<P, M, R> {
    val metadata: FunctionAccessorMetadata<P, R>
    override val contextName: String get() = metadata.contextName
    override val supportedTopics: Set<NamedAggregate> get() = metadata.supportedTopics
    override val functionKind: FunctionKind get() = metadata.functionKind
    override val supportedType: Class<*> get() = metadata.supportedType
    override val processorName: String get() = metadata.processorName
    override val name: String get() = metadata.name

    override fun <A : Annotation> getAnnotation(annotationClass: Class<A>): A? {
        return metadata.accessor.function.scanAnnotation(annotationClass.kotlin)
    }
}

fun <P : Any, M : MessageExchange<*, *>, R> FunctionAccessorMetadata<P, R>.toMessageFunction(processor: P): MessageFunctionAccessor<P, M, R> {
    return if (injectParameterLength == 0) {
        SimpleMessageFunctionAccessor(processor, this)
    } else {
        InjectableMessageFunctionAccessor(processor, this)
    }
}
/*
 * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package me.ahoo.wow.command.wait

import me.ahoo.wow.api.messaging.function.FunctionInfo
import me.ahoo.wow.api.messaging.function.NamedFunctionInfo
import me.ahoo.wow.infra.ifNotBlank

fun NamedFunctionInfo?.isWaitingForFunction(function


lines(True)
                colno = i - reduce(lambda x,y: x+y, (len(z) for z in lines))
                lineno = len(lines)

                raise ValueError('Invalid format string: line %d, col %d' %
                                 (lineno, colno))

        d = code_formatter.pattern.sub(convert, format)
        self._append(d)

__all__ = [ "code_formatter" ]

if __name__ == '__main__':
    from .code_formatter import code_formatter
    f = code_formatter()

    class Foo(dict):
        def __init__(self, **kwargs):
            self.update(kwargs)
        def __getattr__(self, attr):
            return self[attr]

    x = "this is a test"
    l = [ [Foo(x=[Foo(y=9)])] ]

    y = code_formatter()
    y('''
{
    this_is_a_test();
}
''')
    f('    $y')
    f('''$__file__:$__line__
{''')
    f("${{', '.join(str(x) for x in range(4))}}")
    f('${x}')
    f('$x')
    f.indent()
    for i in range(5):
        f('$x')
        f('$i')
        f('$0', "zero")
        f('$1 $0', "zero", "one")
        f('${0}', "he went")
        f('${0}asdf', "he went")
    f.dedent()

    f('''
    ${{l[0][0]["x"][0].y}}
}
''', 1, 9)

    print(f, end=' ')


	}

	pcmd.AddOutputFlag(cmd)

	return cmd
}

func (c invitationCommand) listInvitations(cmd *cobra.Command, _ []string) error {
	invitations, err := c.V2Client.ListIamInvitations()
	if err != nil {
		return err
	}

	list := output.NewList(cmd)
	for _, invitation := range invitations {
		var name string
		if user, err := c.V2Client.GetIamUserById(invitation.User.GetId()); err == nil {
			name = user.GetFullName()
		}

		list.Add(&invitationOut{
			Id:     invitation.GetId(),
			Name:   name,
			Email:  invitation.GetEmail(),
			UserId: invitation.User.GetId(),
			Status: invitation.GetStatus(),
		})
	}
	return list.Print()
}
package iam

import (
	"fmt"
	"net/http"

	"github.com/spf13/cobra"

	pcmd "github.com/confluentinc/cli/v4/pkg/cmd"
	"github.com/confluentinc/cli/v4/pkg/errors"
	"github.com/confluentinc/cli/v4/pkg/examples"
)

func (c *roleBindingCommand) newCreateCommand() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "create",
		Short: "Create a role binding.",
		Args:  cobra.NoArgs,
		RunE:  c.create,
	}

	var exs []examples.Example

	if c.cfg.IsCloudLogin() {
		exs = append(exs,
			examples.Example{
				Text: `Grant the role "CloudClusterAdmin" to the principal "User:u-123456" in the environment "env-123456" for the cloud cluster "lkc-123456":`,
				Code: "confluent iam rbac role-binding create --principal User:u-123456 --role CloudClusterAdmin --environment env-123456 --cloud-cluster lkc-123456",
			},
			examples.Example{
				Text: `Grant the role "ResourceOwner" to the principal "User:u-123456", in the environment "env-123456" for the Kafka cluster "lkc-123456" on the resource "Topic:my-topic":`,
				Code: "confluent iam rbac role-binding create --principal User:u-123456 --role ResourceOwner --resource Topic:my-topic --environment env-123456 --cloud-cluster lkc-123456 --kafka-cluster lkc-123456",
			},
			examples.Example{
				Text: `Grant the role "MetricsViewer" to service account "sa-123456":`,
				Code: "confluent iam rbac role-binding create --principal User:sa-123456 --role MetricsViewer",
			},
			examples.Example{
				Text: `Grant the "ResourceOwner" role to principal "User:u-123456" and all subjects for Schema Registry cluster "lsrc-123456" in environment "env-123456":`,
				Code: `confluent iam rbac role-binding create --principal User:u-123456 --role ResourceOwner --environment env-123456 --schema-registry-cluster lsrc-123456 --resource "Subject:*"`,
			},
			examples.Example{
				Text: `Grant the "ResourceOwner" role to principal "User:u-123456" and subject "test" for the Schema Registry cluster "lsrc-123456" in the environment "env-123456":`,
				Code: `confluent iam rbac role-binding create --principal User:u-123456 --role ResourceOwner --environment env-123456 --schema-registry-cluster lsrc-123456 --resource "Subject:test"`,
			},
			examples.Example{
				Text: `Grant the "ResourceOwner" role to principal "User:u-123456" and all subjects in schema context "schema_context" for Schema Registry cluster "lsrc-123456" in the environment "env-123456":`,
				Code: `confluent iam rbac role-binding create --principal User:u


For Mac

          For Mac

          Source Code

          Source Code

          Source code docs

          Manual

          Change Log

          Report a Bug

  The source code version works on all supported platforms, including Linux, but it requires Python 2.6, or 2.7 (recommended).
  It runs on Windows and most Unix systems, including Linux and BSD.

Instructions

After download, unzip it and click on web2py.exe (windows) or web2py.app (osx).
  To run from source, type:

{{=CODE("python2.7 web2py.py", language=None, counter='>', _class='boxCode')}}

or for more info type:

{{=CODE("python2.7 web2py.py -h", language=None, counter='>', _class='boxCode')}}

Caveats

After installation, every time you run it, web2py asks you to choose a password. This password is your administrative password. If the password is left blank, the administrative interface is disabled. The administrative interface /admin/default/index is only accessible via localhost and always requires a password.

Any url /a/b/c maps into a call to application a, controller b.py and function c in that controller.

You are strongly advised to also use Apache with mod_proxy or mod_wsgi to access applications in the framework. This allows better security and concurrency.

License

Web2py code is released under LGPLv3 License. This license does not extend to third party libraries distributed with web2py (which can be MIT, BSD or Apache type licenses) nor does it extend to applications built with web2py (under the terms of the LGPL.

Applications built with web2py can be released


a label %w", err)
		}
	}
	if ds.Structure != nil && ds.Structure.Path != "" {
		err := info.AddLabelByID("st", dsfs.GetHashBase(ds.Structure.Path))
		if err != nil {
			return nil, fmt.Errorf("adding structure label: %w", err)
		}
	}
	if ds.Stats != nil && ds.Stats.Path != "" {
		err := info.AddLabelByID("sa", dsfs.GetHashBase(ds.Stats.Path))
		if err != nil {
			return nil, fmt.Errorf("adding stats label: %w", err)
		}
	}
	if ds.Commit != nil && ds.Commit.Path != "" {
		err := info.AddLabelByID("cm", dsfs.GetHashBase(ds.Commit.Path))
		if err != nil {
			return nil, fmt.Errorf("adding commit label: %w", err)
		}
	}

	if label != "" {
		return info.InfoAtLabel(label)
	}
	return info, nil
}

// newNodeGetter generates an ipld.NodeGetter from a QriNode
func newNodeGetter(node *QriNode) (ipld.NodeGetter, error) {
	capi, err := node.IPFSCoreAPI()
	if err != nil {
		return nil, err
	}
	return dag.NewNodeGetter(capi.Dag()), nil
}
package cmd

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"

	"github.com/qri-io/ioes"
	"github.com/qri-io/qri/base/params"
	"github.com/qri-io/qri/dsref"
	"github.com/qri-io/qri/errors"
	"github.com/qri-io/qri/lib"
	"github.com/qri-io/qri/repo"
	"github.com/spf13/cobra"
)

// NewLogCommand creates a new `qri log` cobra command
func NewLogCommand(f Factory, ioStreams ioes.IOStreams) *cobra.Command {
	o := &LogOptions{IOStreams: ioStreams}
	cmd := &cobra.Command{
		Use:     "log [DATASET]",
		Aliases: []string{"history"},
		Short:   "show log of dataset commits",
		Long: "`qri log`" + ` lists dataset commits over time. Each entry in the log is a
snapshot of a dataset taken at the moment it was saved that keeps exact details
about how that dataset looked at at that point in time.

We call these snapshots versions. Each version has an author (the peer that
created the version) and a message explaining what changed. Log prints these
details in order of occurrence, starting with the most recent known version,
working backwards in time.

The log command can get the list of versions for a local dataset or a dataset
on the network at a remote.
`,
		Example: `  # Show log for the local dataset b5/precip:
  $ qri log b5/precip

  # Show log for a dataset on the Qri Cloud registry called ramfox/league_stats
  $ qri log ramfox/league_stats

  # Show log for a dataset chriswhong/nyc_parking_tickets on a remote named "nycdatacollection"
  $ qri log chriswhong/nyc_parking_tickets --source nycdatacollection`,
		Annotations: map[string]string{
			"group": "dataset",
		},
		Args: cobra.MaximumNArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			if err := o.Complete(f, args); err != nil {
				return err
			}
			return o.Run()
		},


��在的グロース”として再評価余地が大きい。

④ 半導体・グリーントランスフォーメーション
　・熊本の TSMC 新工場稼働は 24 年末。装置・素材・人材供給網を持つ日本企業に追い風。
　・GX 債 20 兆円と税制優遇が「重電×素材×再エネ」の三位一体投資を呼び込み、指数インパクトは 25 年から顕在化。

⑤ インド・ASEAN・中東シフト
　・日系企業の FDI が 23 年比 15％増。海外売上比率 50％超の銘柄は為替耐性と成長弾力が高く、TOPIX より日経平均に寄与しやすい。

⑥ スタートアップ資金循環
　・政府系ファンドと GPIF が 24～26 年に 2 兆円規模で VC・PE 枠を拡充。
　・東証 Prime／Standard への「スピンオフ上場」が進み、指数の新陳代謝が PER を押し上げる。

⑦ 地政学リスク管理
　・WTI 原油 95 ドルを超える局面では、輸送コスト転嫁のできない内需小型が脆弱。
　・台湾有事シナリオでは半導体供給の途絶リスクを織り込み、指数は瞬間 10〜15％の調整を想定。

⑧ 財政規律と増税議論
　・防衛・社会保障費の拡張で国債発行残高は 1,100 兆円へ。増税議論が表面化する 25 年度予算案はセンチメントの波乱要因。

◆取るべき布陣――「四つの備え」
一、キャッシュフローと海外売上比率を兼備する“攻守両用”を主軸に据える。
二、PBR 1 倍割れだが改善計画に実行 KPI を明示した企業を拾い、成果確認で段階的に兵力を増す。
三、半導体・再エネ・医療テックのサプライチェーン上で相互補完する企業群を組み合わせ、「産業間連携 ETF」的ポートフォリオを構築。
四、急変動の狼煙が上がれば、指数連動先物／インバースの“伏兵”で守りを固め、現物の撤退を避ける。

◆結言――「臥龍、筆を擱く」
日経平均の行路は、まさに蜀・魏・呉の勢力均衡と同じく、外部要因と内部改革が絡み合う合


�信息，请参阅 PreTrainedTokenizer.encode()和 PreTrainedTokenizer.`call`()。

    什么是输入 ID？

+   `attention_mask`（形状为`(batch_size, sequence_length)`的`torch.FloatTensor`，*可选*）-用于避免在填充令牌索引上执行注意力的掩码。掩码值在`[0, 1]`中选择：

    +   对于被`masked`的令牌，为 1，

    +   对于被`masked`的令牌，为 0。

    什么是注意力掩码？

+   `token_type_ids`（形状为`(batch_size, sequence_length)`的`torch.LongTensor`，*可选*）-段标记索引，指示输入的第一部分和第二部分。索引在`[0, 1]`中选择：

    +   0 对应于*句子 A*令牌，

    +   1 对应于*句子 B*令牌。

    令牌类型 ID 是什么？

+   `position_ids`（形状为`(batch_size, sequence_length)`的`torch.LongTensor`，*可选*）-输入序列标记的位置在位置嵌入中的索引。在范围`[0, config.max_position_embeddings - 1]`中选择。

    什么是位置 ID？

+   `head_mask`（形状为`(num_heads,)`或`(num_layers, num_heads)`的`torch.FloatTensor`，*可选*）-用于使自注意力模块的选定头部无效的掩码。掩码值在`[0, 1]`中选择：

    +   1 表示头部未被`masked`，

    +   0 表示头部被`masked`。

+   `inputs_embeds`（形状为`(batch_size, sequence_length, hidden_size)`的`torch.FloatTensor`，*可选*）-可选地，您可以选择直接传递嵌入表示，而不是传递`input_ids`。如果您想要更多控制如何将*input_ids*索引转换为相关向量，而不是使用模型的内部嵌入查找矩阵，则这很有用。

+   `output_attentions`（`bool`，*可选*）-是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量下的`attentions`。

+   `output_hidden_states`（`bool`，*可选*）-是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量下的`hidden_states`。

+   `return_dict`（`bool`，*可选*）-是否返回 ModelOutput 而不是普通元组。

+   `start_positions` (`torch.LongTensor`，形状为`(batch_size,)`，*可选*) — 用于计算标记跨度起始位置的位置（索引）标签，以计算标记分类损失。位置被夹紧到序列的长度(`sequence_length`)。超出序列范围的位置不会被考虑在内计算损失。

+   `end_positions` (`torch.LongTensor`，形状为`(batch_size,)`，*可选*) — 用于计算标记跨度结束位置的位置（索引）标签。位置被夹紧到序列的长度(`sequence_length`)。超出序列范围的位置不会被考虑在内计算损失。

返回值

transformers.modeling_outputs.QuestionAnsweringModelOutput 或 `tuple(torch.FloatTensor)`

一个 transformers.modeling_outputs.Quest


[cfg(not(target_os = "wasi"))]
use super::super::offset::libc_mmap;
use super::super::offset::{libc_pread, libc_pwrite};
#[cfg(not(target_os = "redox"))]
use super::super::offset::{libc_preadv, libc_pwritev};
#[cfg(all(target_os = "linux", target_env = "gnu"))]
use super::super::offset::{libc_preadv2, libc_pwritev2};
use crate::fd::{AsFd, BorrowedFd, RawFd};
#[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))]
use crate::ffi::ZStr;
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
use crate::io::Advice;
#[cfg(target_os = "linux")]
use crate::io::MremapFlags;
#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "wasi")))]
use crate::io::PipeFlags;
use crate::io::{self, IoSlice, IoSliceMut, OwnedFd, PollFd};
#[cfg(not(target_os = "wasi"))]
use crate::io::{DupFlags, MapFlags, MprotectFlags, MsyncFlags, ProtFlags, Termios, Winsize};
#[cfg(any(target_os = "android", target_os = "linux"))]
use crate::io::{EventfdFlags, MlockFlags, ReadWriteFlags, UserfaultfdFlags};
use core::cmp::min;
use core::convert::TryInto;
use core::mem::MaybeUninit;
use errno::errno;

pub(crate) fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> io::Result<usize> {
    let nread = unsafe {
        ret_ssize_t(c::read(
            borrowed_fd(fd),
            buf.as_mut_ptr().cast(),
            min(buf.len(), READ_LIMIT),
        ))?
    };
    Ok(nread as usize)
}

pub(crate) fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> io::Result<usize> {
    let nwritten = unsafe {
        ret_ssize_t(c::write(
            borrowed_fd(fd),
            buf.as_ptr().cast(),
            min(buf.len(), READ_LIMIT),
        ))?
    };
    Ok(nwritten as usize)
}

pub(crate) fn pread(fd: BorrowedFd<'_>, buf: &mut [u8], offset: u64) -> io::Result<usize> {
    let len = min(buf.len(), READ_LIMIT);

    // Silently cast; we'll get `EINVAL` if the value is negative.
    let offset = offset as i64;

    let nread = unsafe {
        ret_ssize_t(libc_pread(
            borrowed_fd(fd),
            buf.as_mut_ptr().cast(),
            len,
            offset,
        ))?
    };
    Ok(nread as usize)
}

pub(crate) fn pwrite(fd: BorrowedFd<'_>, buf: &[u8], offset: u64) -> io::Result<usize> {
    let len = min(buf.len(), READ_LIMIT);

    // Silently cast; we'll get `EINVAL` if the value is negative.
    let offset = offset as i64;

    let nwritten = unsafe {
        ret_ssize_t(libc_pwrite(
            borrowed_fd(fd),
            buf.as_ptr().cast(),
            len,
            offset,
        ))?
    };
    Ok(nwritten as usize)
}

pub(crate) fn readv(fd: BorrowedFd<'_>, bufs: &mut [


obalBind("mousemove.vol",function(e){var t=e.target;c&&(t===m||t.closest("vertical"===s?"."+a.options.classPrefix+"volume-slider":"."+a.options.classPrefix+"horizontal-volume-slider"))&&E(e)}),a.globalBind("mouseup.vol",function(){c=!1,f||"vertical"!==s||(m.style.display="none")}),c=!0,e.preventDefault(),e.stopPropagation()}),o.addEventListener("volumechange",function(e){var t;c||b(),t=Math.floor(100*o.volume),m.setAttribute("aria-valuenow",t),m.setAttribute("aria-valuetext",t+"%")});var S=!1;o.addEventListener("rendererready",function(){p||setTimeout(function(){S=!0,(0===e.options.startVolume||o.originalNode.muted)&&o.setMuted(!0),o.setVolume(e.options.startVolume),a.setControlsSize()},250)}),o.addEventListener("loadedmetadata",function(){setTimeout(function(){p||S||((0===e.options.startVolume||o.originalNode.muted)&&o.setMuted(!0),0===e.options.startVolume&&(e.options.startVolume=0),o.setVolume(e.options.startVolume),a.setControlsSize()),S=!1},250)}),(0===e.options.startVolume||o.originalNode.muted)&&(o.setMuted(!0),0===e.options.startVolume&&(e.options.startVolume=0),b()),a.getElement(a.container).addEventListener("controlsresize",function(){b()})}}})},{16:16,2:2,25:25,26:26,27:27,5:5}],15:[function(e,t,n){"use strict";Object.defineProperty(n,"__esModule",{value:!0});n.EN={"mejs.plural-form":1,"mejs.download-file":"Download File","mejs.install-flash":"You are using a browser that does not have Flash player enabled or installed. Please turn on your Flash player plugin or download the latest version from https://get.adobe.com/flashplayer/","mejs.fullscreen":"Fullscreen","mejs.play":"Play","mejs.pause":"Pause","mejs.time-slider":"Time Slider","mejs.time-help-text":"Use Left/Right Arrow keys to advance one second, Up/Down arrows to advance ten seconds.","mejs.live-broadcast":"Live Broadcast","mejs.volume-help-text":"Use Up/Down Arrow keys to increase or decrease volume.","mejs.unmute":"Unmute","mejs.mute":"Mute","mejs.volume-slider":"Volume Slider","mejs.video-player":"Video Player","mejs.audio-player":"Audio Player","mejs.captions-subtitles":"Captions/Subtitles","mejs.captions-chapters":"Chapters","mejs.none":"None","mejs.afrikaans":"Afrikaans","mejs.albanian":"Albanian","mejs.arabic":"Arabic","mejs.belarusian":"Belarusian","mejs.bulgarian":"Bulgarian","mejs.catalan":"Catalan","mejs.chinese":"Chinese","mejs.chinese-simplified":"Chinese (Simplified)","mejs.chinese-traditional":"Chinese (Traditional)","mejs.croatian":"Croatian","mejs.czech":"Czech","mejs.danish":"Danish","mejs.dutch":"Dutch","mejs.english":"English","mejs.estonian":"Estonian","mejs.filipino":"Filipino","mejs.finnish":"Finnish","mejs.french":"French","mejs.galician":"Galician","mejs.german":"German","mejs.greek":"Greek","mejs


include "64cube.inc"

ENUM $0
    screen dw 1
    pointer dw 1
    counter db 1
    tiley db 1
    tile db 1
    offset db 1
    row db 1
    savey db 1
    size db 1
    temp db 1
    flicker db 1
    ready db 1
ENDE

    org $200
Boot:
    sei
    _setb $d,COLORS
    _setb $f,VIDEO
    _setw IRQ, VBLANK_IRQ

    SIGN EQU #$d12
    jsr BuildTiles
    cli

; MAIN LOOP
Main:
    lda ready
    beq Main

    ; COPY TILES TO SCREEN
        _setb #64,size
        _setw $e000,pointer
        _setw $f000,screen
        jsr DrawTile

    ; DRAW CAR
        _setw $1800,pointer
        _setw $f9c0,screen
        jsr DrawCar

        jsr Move ;MOVE CAR
        jsr Flicker ;FLICKER SIGN

    lda #0
    sta ready
    jmp Main

IRQ:
    jsr Update

    lda #1
    sta ready
    rti

Update:
    lda counter
    cmp #10
    bne ++

    lda flicker
    cmp #32
    bcc +
    lda #0
    sta flicker
+
    inc flicker

    lda #0
    sta counter
++
    inc counter
    rts

Flicker:
    ldy flicker
    lda Pattern,y
    beq +

    lda #$ff
    sta SIGN
    sta SIGN+2
    jmp ++
+
    lda #0
    sta SIGN
    sta SIGN+2
++
    rts

Move:
    _setw $1801,pointer
    _setw $1800,screen
    ldx #0
--
    ldy #0
-
    lda (pointer),y
    sta (screen),y
    iny
    cpy #63
    bne -
    _addwb pointer,#64,pointer
    _addwi screen,#64,screen
    inx
    cpx #8
    bne --
    _setw $1800,pointer
    _setw $183f,screen
    ldy #0
-
    lda (pointer),y
    sta (screen),y
    _addwi pointer,#63,pointer
    _addwi screen,#63,screen
    iny
    cpy #8
    bne -
+
    rts

; CALCULATE AND
; DRAW EACH TILE
; FROM ATLAS AND MAP
; ONCE INTO 0xe000
BuildTiles:
    ldy #0
-
    _setb #8,size


Flag(true);
			break;
		case vncDesktop::TIMER_BLANK_SCREEN:
			if (_this->m_server->GetBlankScreen())
				_this->BlankScreen(TRUE);
			break;
		case vncDesktop::TIMER_RESTORE_SCREEN:
			_this->BlankScreen(FALSE);
			break;
		}
		return 0;

		// CLIPBOARD MESSAGES

	case WM_CHANGECBCHAIN:
		// The clipboard chain has changed - check our nextviewer handle
		if ((HWND)wParam == _this->m_hnextviewer)
			_this->m_hnextviewer = (HWND)lParam;
		else
			if (_this->m_hnextviewer != NULL)
				SendMessage(_this->m_hnextviewer,
							WM_CHANGECBCHAIN,
							wParam, lParam);

		return 0;

	case WM_DRAWCLIPBOARD:
		// The clipboard contents have changed
		if((GetClipboardOwner() != _this->Window()) &&
		    _this->m_initialClipBoardSeen &&
			_this->m_clipboard_active)
		{
			LPSTR cliptext = NULL;

			// Open the clipboard
			if (OpenClipboard(_this->Window()))
			{
				// Get the clipboard data
				HGLOBAL cliphandle = GetClipboardData(CF_TEXT);
				if (cliphandle != NULL)
				{
					LPSTR clipdata = (LPSTR) GlobalLock(cliphandle);

					// Copy it into a new buffer
					if (clipdata == NULL)
						cliptext = NULL;
					else
						cliptext = strdup(clipdata);

					// Release the buffer and close the clipboard
					GlobalUnlock(cliphandle);
				}

				CloseClipboard();
			}

			if (cliptext != NULL)
			{
				size_t cliplen = strlen(cliptext);
				LPSTR unixtext = (char *)malloc(cliplen+1);

				// Replace CR-LF with LF - never send CR-LF on the wire,
				// since Unix won't like it
				int unixpos=0;
				for (size_t x=0; x<cliplen; x++)
				{
					if (cliptext[x] != '\x0d')
					{
						unixtext[unixpos] = cliptext[x];
						unixpos++;
					}
				}
				unixtext[unixpos] = 0;

				// Free the clip text
				free(cliptext);
				cliptext = NULL;

				// Now send the unix text to the server
				_this->m_server->UpdateClipText(unixtext);

				free(unixtext);
			}
		}

		_this->m_initialClipBoardSeen = TRUE;

		if (_this->m_hnextviewer != NULL)
		{
			// Pass the message to the next window in clipboard viewer chain.
			return SendMessage(_this->m_hnextviewer, WM_DRAWCLIPBOARD, 0,0);
		}

		return 0;

	default:
		return DefWindowProc(hwnd, iMsg, wParam, lParam);
	}
}

BOOL vncDesktop::CheckUpdates()
{
#ifndef _DEBUG
	try
	{
#endif
		// Re-install polling timer if necessary
		if (m_server->PollingCycleChanged())
		{
			SetPollingTimer();
			m_server->PollingCycleChanged(false);
		}

		// Update the state of blank screen timer
		UpdateBlankScreenTimer();

		// Has the display resolution or desktop changed?
		if (m_displaychanged || !vncService::InputDesktopSelected() || !inConsoleSession())
		{

			rfbServerInitMsg oldscrinfo = m_scrinfo;
			m_displaychanged = FALSE;

			// Attempt to close the old hooks
			if (!Shutdown())
			{

				m_server->KillAuthClients();
				return FALSE;


e CSP."
    );

    let (key_id2, _public_key) = csp_vault2
        .gen_key_pair(AlgorithmId::Ed25519)
        .expect("Test setup failed: Failed to generate keys");
    assert!(
        key_id1 != key_id2,
        "Test failure: Key IDs from different CSPs were the same.  Check random number generation."
    );
    assert!(
        csp_vault2.sks_contains(&key_id2).expect("SKS call failed"),
        "Key should be present in the CSP that generated it."
    );
    assert!(
        !csp_vault2.sks_contains(&key_id1).expect("SKS call failed"),
        "The second CSP should not contain thekeys of the first."
    );
    assert!(
        !csp_vault1.sks_contains(&key_id2).expect("SKS call failed"),
        "Key first CSP should not contain the keys of the second."
    );
}
use crate::config::{Config, DeliveryConfig};
use crate::delivery_result::DeliveryResult;
use crate::prepared_email::PreparedEmail;
use lettre::smtp::authentication::Credentials;
use lettre::smtp::client::net::ClientTlsParameters;
use lettre::smtp::error::Error as LettreSmtpError;
use lettre::smtp::extension::ClientId;
use lettre::smtp::response::Severity;
use lettre::smtp::{ClientSecurity, SmtpClient};
use lettre::Transport;
use native_tls::{TlsConnector, Protocol};
use std::net::ToSocketAddrs;
use std::time::Duration;
use std::io::ErrorKind;

// Deliver an email to an SMTP server
pub fn smtp_delivery(
    prepared_email: &PreparedEmail,
    smtp_server_domain: &str,
    port: u16,
    config: &Config
) -> DeliveryResult {

    // lettre::EmailAddress checks validity.  But we checked that when we created
    // PreparedEmail so this conversion should always pass.
    let sendable_email = match prepared_email.as_sendable_email() {
        Ok(se) => se,
        Err(e) => {
            warn!("Invalid email address error: {:?}", e);
            return DeliveryResult::Failed(format!("Invalid email address error: {:?}", e));
        }
    };

    let tls_builder = match TlsConnector::builder()
        .min_protocol_version(Some(Protocol::Tlsv12))
        .build()
    {
        Ok(connector) => connector,
        Err(e) => {
            info!("(worker) failed to create TLS Connector: {:?}", e);
            return DeliveryResult::Failed(format!("Failed to create TLS connector: {:?}", e));
        }
    };

    let client_security = if let DeliveryConfig::Relay(ref rc) = config.delivery {
        if rc.use_tls {
            let tls_parameters =
                ClientTlsParameters::new(smtp_server_domain.to_owned(), tls_builder);
            if config.require_tls {
                ClientSecurity::Required(tls_parameters)
            } else {
                ClientSecurity::Opportunistic(tls_parameters)
            }
        } else {
            ClientSecurity::None
        }
    } else {
        let tls_parameters =
            ClientTlsParameters::new(smtp_server_domain.to_owned(), tls_builder);

        if config.require_tls {
            ClientSecurity::Required(tls_parameters)
        } else {
            ClientSecurity::Opportunistic(tls_parameters)
        }