text:
@implementation NSString (HDAdditions)
- (CGFloat)computTextHeightFont:(UIFont *)font width:(CGFloat)width {
    CGSize titleSize = [self sizeWithFont:font constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    return titleSize.height > 34 ? titleSize.height : 34;
}

- (NSInteger)computTextWidthFont:(UIFont *)font {
    CGSize titleSize = [self sizeWithFont:font constrainedToSize:CGSizeMake(MAXFLOAT, 30)];
    NSInteger width = titleSize.width;
    return (width > 200 ? 200 : width);
}

+ (NSString *)getTemporaryPath
{
    return NSTemporaryDirectory();
}

+ (NSString *)getCachePath
{
    NSArray *CachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString  *directory = [CachePaths objectAtIndex:0];

    return directory;
}

@end

redpajama_set_name: RedPajamaGithub


text:
namespace MusicShopManager.Engine
{
    using System;

    internal static class EngineConstants
    {
        #region Commands
        internal const string CreateMusicShopCommand = "CreateMusicShop";
        internal const string CreateMicrophoneCommand = "CreateMicrophone";
        internal const string CreateDrumsCommand = "CreateDrums";
        internal const string CreateElectricGuitarCommand = "CreateElectricGuitar";
        internal const string CreateAcousticGuitarCommand = "CreateAcousticGuitar";
        internal const string CreateBassGuitarCommand = "CreateBassGuitar";
        internal const string AddArticleToShopCommand = "AddArticleToShop";
        internal const string RemoveArticleFromShopCommand = "RemoveArticleFromShop";
        internal const string ListArticlesCommand = "ListArticles";
        #endregion

        #region Error messages
        internal const string InvalidCommandMessage = "Invalid command name: {0}";
        internal const string MusicShopExistsMessage = "The music shop {0} already exists";
        internal const string ArticleExistsMessage = "The article {0} already exists";
        internal const string ArticleExistsInShopMessage = "The article {0} already exists in shop {1}";
        internal const string ArticleDoesNotExistInShopMessage = "The article {0} does not exist in shop {1}";
        internal const string MusicShopDoesNotExistMessage = "The music shop {0} does not exist";
        internal const string ArticleDoesNotExistMessage = "The article {0} does not exist";
        #endregion

        #region Success messages
        internal const string MusicShopCreatedMessage = "Music shop {0} created";
        internal const string ArticleCreatedMessage = "{0} {1} created";
        internal const string ArticleAddedMessage = "Article {0} successfully added to music shop {1}";
        internal const string ArticleRemovedMessage = "Article {0} successfully removed from music shop {1}";
        #endregion
    }
}


text:
package com.board.gd.exception;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * Created by gd.godong9 on 2017. 4. 20.
 */

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class StockException extends RuntimeException {
    private String message = "종목 처리 중 에러가 발생하였습니다.";
}


text:
package de.peeeq.wurstscript.types;

import de.peeeq.wurstscript.ast.TypeParamDef;
import de.peeeq.wurstscript.attributes.CompileError;
import io.vavr.Tuple2;
import io.vavr.collection.List;
import io.vavr.collection.Set;
import io.vavr.collection.HashMap;
import io.vavr.control.Option;
import org.jetbrains.annotations.NotNull;

import java.util.Iterator;

/**
 * VariableBinding
 */
public class VariableBinding implements Iterable<Tuple2<TypeParamDef, WurstTypeBoundTypeParam>> {
    public static final VariableBinding EMPTY_MAPPING = new VariableBinding(HashMap.empty(), List.empty(), List.empty());
    private final HashMap<TypeParamDef, WurstTypeBoundTypeParam> binding;
    private final List<TypeParamDef> typeVariablesLeft;
    private final List<CompileError> errors;

    public VariableBinding(HashMap<TypeParamDef, WurstTypeBoundTypeParam> binding, List<TypeParamDef> typeVariablesLeft, List<CompileError> errors) {
        this.binding = binding;
        this.typeVariablesLeft = typeVariablesLeft;
        this.errors = errors;
    }

    @NotNull
    public static VariableBinding emptyMapping() {
        return EMPTY_MAPPING;
    }

    public boolean contains(TypeParamDef v) {
        return binding.containsKey(v);
    }

    public Option<WurstTypeBoundTypeParam> get(TypeParamDef v) {
        return binding.get(v);
    }

    public VariableBinding set(TypeParamDef v, WurstTypeBoundTypeParam b) {
        return new VariableBinding(binding.put(v, b), typeVariablesLeft.removeAll(v::equals), errors);
    }

    public boolean isEmpty() {
        return binding.isEmpty();
    }

    public VariableBinding union(VariableBinding other) {
        if (this.isEmpty() && this.errors.isEmpty()) {
            return other;
        } else if (other.isEmpty() && other.errors.isEmpty()) {
            return this;
        }
        VariableBinding res = new VariableBinding(binding, typeVariablesLeft, errors.appendAll(other.errors));
        for (Tuple2<TypeParamDef, WurstTypeBoundTypeParam> e : other.binding) {
            res = res.set(e._1(), e._2());
        }
        return res;
    }

    public Set<TypeParamDef> keys() {
        return binding.keySet();
    }

    @NotNull
    @Override
    public Iterator<Tuple2<TypeParamDef, WurstTypeBoundTypeParam>> iterator() {
        return binding.iterator();
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        boolean first;
        if (hasUnboundTypeVars()) {
            s.append("<");
            first = true;
            for (TypeParamDef t : typeVariablesLeft) {
                if (!first) {
                    s.append(", ");
                }
                s.append(t.getName()).append(" line ").append(t.getSource().getLine());
                first = false;
            }
            s.append(">");
        }

        s.append("[");
        first = true;
        for (Tuple2<TypeParamDef, WurstTypeBoundTypeParam> e : binding) {
            if (!first) {
                s.append(", ");
            }
            s.append(e._1().getName());
            s.append(" -> ");
            s.append(e._2().getBaseType());
            first = false;
        }
        s.append("]");
        if (!errors.isEmpty()) {
            s.append("{");
            for (CompileError error : errors) {
                s.append(error);
            }
            s.append("}");
        }
        return s.toString();
    }

    public VariableBinding withTypeVariables(Iterable<TypeParamDef> vars) {
        return new VariableBinding(binding, typeVariablesLeft.appendAll(vars), errors);
    }

    public boolean isVar(TypeParamDef def) {
        return typeVariablesLeft.exists(def::equals);
    }

    public boolean hasUnboundTypeVars() {
        return !typeVariablesLeft.isEmpty();
    }

    public String printUnboundTypeVars() {
        StringBuilder res = new StringBuilder();
        for (TypeParamDef t : typeVariablesLeft) {
            if (res.length() > 0) {
                res.append(", ");
            }
            res.append(t.getName());
        }
        return res.toString();
    }

    public VariableBinding withError(CompileError err) {
        return new VariableBinding(binding, typeVariablesLeft, errors.prepend(err));
    }

    public List<CompileError> getErrors() {
        return errors;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="photos/bro-logo2.png">

    <title>Thank You</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-switch.css" rel="stylesheet">

    <link href="assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <link href="mainstyle.css" rel="stylesheet">

                            <button  class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                                Toggle navigation

                            </button>

Home

Want a Ticket?

Become A Patron

                                    Want more Info?

Hot off the Press

Our Legacy

Honorary Members

Say Cheese

                                    Members Only

Want to Join?

Staff Room

Rules and Regulations

Report

Contact Us

Thank You!!

Your generosity means that we can continue to entertain the Townsville region for years to come.

You might now want to see our Upcomming Events!

If you have any questions click HERE!

Check out Our New Events!

                Home

            	Want a Ticket?

            Become A Patron

            Want to Join the Band?

Back to top

© 2016 , Barrier Reef Orchestra. - Contact Us!

    <textarea id="ta"></textarea >
    <audio id="myMusic">
    <source src="photos/Kevin_MacLeod.mp3" />
	</audio>


text:
#include "gtest/gtest.h"
#include "application_manager/commands/hmi/activate_app_request.h"
#include "utils/shared_ptr.h"
#include "smart_objects/smart_object.h"
#include "application_manager/mock_application.h"
#include "application_manager/commands/command_impl.h"
#include "commands/commands_test.h"

namespace test {
namespace components {
namespace commands_test {
namespace hmi_commands_test {
namespace activate_app_request {

using ::testing::_;
namespace am = ::application_manager;
namespace strings = ::application_manager::strings;
using am::commands::MessageSharedPtr;
using am::commands::ActivateAppRequest;
using am::commands::CommandImpl;

typedef ::utils::SharedPtr<ActivateAppRequest> ActivateAppRequestPtr;

MATCHER_P(CheckMessage, level, "") {
  return level ==
         static_cast<mobile_apis::HMILevel::eType>(
             (*arg)[strings::msg_params][strings::activate_app_hmi_level]
                 .asInt());
}

namespace {
const uint32_t kAppId = 1u;
const uint32_t kCorrelationId = 2u;
}  // namespace

class ActivateAppRequestTest : public CommandsTest<CommandsTestMocks::kIsNice> {
 public:
  MessageSharedPtr CreateMsgParams() {
    MessageSharedPtr msg = CreateMessage(smart_objects::SmartType_Map);
    smart_objects::SmartObject msg_params =
        smart_objects::SmartObject(smart_objects::SmartType_Map);
    msg_params[strings::app_id] = kAppId;
    msg_params[strings::correlation_id] = kCorrelationId;
    (*msg)[strings::msg_params] = msg_params;
    (*msg)[strings::params][strings::app_id] = kAppId;
    (*msg)[strings::params][strings::correlation_id] = kCorrelationId;
    (*msg)[strings::app_id] = kAppId;
    return msg;
  }
};

TEST_F(ActivateAppRequestTest, Run_SUCCESS) {
  MessageSharedPtr msg = CreateMsgParams();

  MockAppPtr mock_app = CreateMockApp();
  EXPECT_CALL(app_mngr_, application(kAppId)).WillOnce(Return(mock_app));
// TODO(OKozlov) Invastigate and fix issue with using log
#ifdef ENABLE_LOG
  (*msg)[strings::msg_params][strings::activate_app_hmi_level] =
      mobile_apis::HMILevel::HMI_FULL;
#endif
  ActivateAppRequestPtr command(CreateCommand<ActivateAppRequest>(msg));

  EXPECT_CALL(app_mngr_, set_application_id(kCorrelationId, kAppId));
#ifdef ENABLE_LOG
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(CheckMessage(mobile_apis::HMILevel::HMI_FULL)));
#else
  EXPECT_CALL(app_mngr_,
              SendMessageToHMI(msg)));
#endif
  command->Run();

#ifndef ENABLE_LOG
  EXPECT_EQ(CommandImpl::hmi_protocol_type_,
            (*msg)[strings::params][strings::protocol_type].asInt());
  EXPECT_EQ(CommandImpl::protocol_version_,
            (*msg)[strings::params][strings::protocol_version].asInt());
#endif
}

}  // namespace activate_app_request
}  // namespace hmi_commands_test
}  // namespace commands_test
}  // namespace components
}  // namespace test


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using RabbitMQ.Client;

namespace EasyNetQ.Producer
{
    /// <summary>
    /// An abstraction on top of channel which manages its persistence and invokes an action on it
    /// </summary>
    public interface IPersistentChannel : IDisposable
    {
        /// <summary>
        /// Invoke an action on channel
        /// </summary>
        /// <param name="channelAction">The action to invoke</param>
        /// <param name="cancellationToken">The cancellation token</param>
        Task<T> InvokeChannelActionAsync<T>(Func<IModel, T> channelAction, CancellationToken cancellationToken = default);
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ad extends Admin_Controller {

	function __construct(){
        parent::__construct();
        $this->data['ad_type'] = array('image'=>'图片','text'=>'文字');
    }

    public function index(){
        $this->image();
    }

    public function image(){
        $this->data['item_list'] = $this->db->order_by('id desc')->where_in('type',array('text','image'))->get('ad')->result_array();
        $this->load->view('ad/image_list',$this->data);
    }

    public function image_add($id=''){
        if($id){
             $this->data['item'] = $this->db->where('id',$id)->get('ad')->row_array();
             $this->load->view('ad/image_edit',$this->data);
        }else{
            $this->load->view('ad/image_add',$this->data);
        }
    }

    public function rotation(){
        $this->data['item_list'] = $this->db->order_by('id desc')->where('type','rotation')->get('ad')->result_array();
        $this->load->view('ad/rotation',$this->data);
    }

    public function rotation_add($id=''){
        if($id){
             $this->data['item'] = $this->db->where('id',$id)->get('ad')->row_array();
        }
        $this->load->view('ad/rotation_add',$this->data);
    }

    public function rotation_item($id){
        $this->data['item'] = $this->db->where('id',$id)->get('ad')->row_array();
        $this->data['item_list'] = $this->db->where('ad_id',$id)->get('ad_rotation')->result_array();
        $this->load->view('ad/rotation_item',$this->data);
    }

    public function rotation_item_add($ad_id, $id=''){
        if($id){
             $this->data['item'] = $this->db->where('id',$id)->get('ad_rotation')->row_array();
        }
        $this->data['ad'] = $this->db->where('id',$ad_id)->get('ad')->row_array();
        $this->load->view('ad/rotation_item_add',$this->data);
    }
 }


text:
import {
    UTIL_LAUNCH_TEXT_EDIT,
    UTIL_LAUNCH_RENAME_FILE,
    UTIL_LAUNCH_SHARING_SETTINGS,
    UTIL_LAUNCH_IMPORT_TO_INVENTORY,
    UTIL_LAUNCH_IMPORT_TO_SPACE,
    UTIL_LAUNCH_ENTITY_EDITOR,
    UTIL_LAUNCH_INVENTORY_EXPORT,
    UTIL_LAUNCH_COMPONENT_EDITOR,
    UTIL_LAUNCH_ATTRIBUTE_EDITOR,
    UTIL_CLOSE_TEXT_EDIT,
    UTIL_CLOSE_RENAME_FILE,
    UTIL_CLOSE_SHARING_SETTINGS,
    UTIL_CLOSE_IMPORT_TO_INVENTORY,
    UTIL_CLOSE_IMPORT_TO_SPACE,
    UTIL_CLOSE_ENTITY_EDITOR,
    UTIL_CLOSE_INVENTORY_EXPORT,
    UTIL_CLOSE_COMPONENT_EDITOR,
    UTIL_CLOSE_ATTRIBUTE_EDITOR,
    UTIL_LAUNCH_EDIT_LOADED_ITEM,
    UTIL_ACTIVATE_MODAL
} from '../constants';

export default function app (state: any = {
    textEdit: {
        windowsOpen: 0,
        activated: false,
        username: "",
        filename: "",
        dir: ""
    },
    renameFile: {
        windowsOpen: 0,
        activated: false,
        username: "",
        filename: "",
        target: "",
        dir: ""
    },
    sharingSettings: {
        windowsOpen: 0,
        activated: false,
        username: "",
        filename: "",
        dir: ""
    },
    importToSpace: {
        windowsOpen: 0,
        activated: false,
        username: "",
        itemData: false,
        itemIndex: -1
    },
    importToInventory: {
        windowsOpen: 0,
        activated: false,
        username: "",
        filename: "",
        dir: ""
    },
    entityEdit: {
        windowsOpen: 0,
        activated: false,
        username: "",
        category: "",
        itemId: "",
        source: "inventory"
    },
    inventoryExport: {
        windowsOpen: 0,
        activated: false,
        username: "",
        category: "",
        itemId: ""
    },
    componentEdit: {
        windowsOpen: 0,
        activated: false,
        username: "",
        itemId: "",
        source: "inventory"
    },
    attributeEdit: {
        windowsOpen: 0,
        activated: false,
        username: "",
        itemId: "",
        source: "inventory"
    },
    loadedItemEdit: {
        windowsOpen: 0,
        activated: {
            entity: false,
            component: false,
            attribute: false
        },
        username: "",
        category: "",
        index: -1,
        data: {
            entity: false,
            component: false,
            attribute: false
        },
        source: {
            entity: "inventory",
            component: "inventory",
            attribute: "inventory"
        }
    }
}, action: any) {
  switch ( action.type ) {
    case UTIL_ACTIVATE_MODAL:
        let newState: any = {...state }
        switch( action.modalType ) {
            case "textEdit":
                newState = {
                    ...newState,
                    textEdit: {
                        ...newState.textEdit,
                        windowsOpen: newState.textEdit.windowsOpen + 1
                    }
                }
            break;
            case "renameFile":
                newState = {
                    ...newState,
                    renameFile: {
                        ...newState.renameFile,
                        windowsOpen: newState.renameFile.windowsOpen + 1
                    }
                }
            break;
            case "sharingSettings":
                newState = {
                    ...newState,
                    sharingSettings: {
                        ...newState.sharingSettings,
                        windowsOpen: newState.sharingSettings.windowsOpen + 1
                    }
                }
            break;
            case "importToSpace":
                newState = {
                    ...newState,
                    importToSpace: {
                        ...newState.importToSpace,
                        windowsOpen: newState.importToSpace.windowsOpen + 1
                    }
                }
            break;
            case "importToInventory":
                newState = {
                    ...newState,
                    importToInventory: {
                        ...newState.importToInventory,
                        windowsOpen: newState.importToInventory.windowsOpen + 1
                    }
                }
            break;
            case "entityEdit":
                newState = {
                    ...newState,
                    entityEdit: {
                        ...newState.entityEdit,
                        windowsOpen: newState.entityEdit.windowsOpen + 1
                    }
                }
            break;
            case "inventoryExport":
                newState = {
                    ...newState,
                    inventoryExport: {
                        ...newState.inventoryExport,
                        windowsOpen: newState.inventoryExport.windowsOpen + 1
                    }
                }
            break;
            case "componentEdit":
                newState = {
                    ...newState,
                    componentEdit: {
                        ...newState.componentEdit,
                        windowsOpen: newState.componentEdit.windowsOpen + 1
                    }
                }
            break;
            case "attributeEdit":
                newState = {
                    ...newState,
                    attributeEdit: {
                        ...newState.attributeEdit,
                        windowsOpen: newState.attributeEdit.windowsOpen + 1
                    }
                }
            break;

        }
        return newState
    case UTIL_LAUNCH_TEXT_EDIT:
        return {
            ...state,
            textEdit: {
                ...state.textEdit,
                windowsOpen: state.textEdit.windowsOpen + 1,
                activated: true,
                username: action.username,
                filename: action.filename,
                dir: action.dir
            }
        }
    case UTIL_LAUNCH_RENAME_FILE:
        return {
            ...state,
            renameFile: {
                ...state.renameFile,
                windowsOpen: state.renameFile.windowsOpen + 1,
                activated: true,
                username: action.username,
                filename: action.filename,
                dir: action.dir
            }
        }
    case UTIL_LAUNCH_SHARING_SETTINGS:
        return {
            ...state,
            sharingSettings: {
                ...state.sharingSettings,
                windowsOpen: state.sharingSettings.windowsOpen + 1,
                activated: true,
                username: action.username,
                filename: action.filename,
                dir: action.dir
            }
        }
    case UTIL_LAUNCH_IMPORT_TO_INVENTORY:
        return {
            ...state,
            importToInventory: {
                ...state.importToInventory,
                windowsOpen: state.importToInventory.windowsOpen + 1,
                activated: true,
                username: action.username,
                filename: action.filename,
                dir: action.dir
            }
        }
    case UTIL_LAUNCH_IMPORT_TO_SPACE:
        return {
            ...state,
            importToSpace: {
                ...state.importToSpace,
                windowsOpen: state.textEdit.windowsOpen + 1,
                activated: true,
                username: action.username,
                itemData: action.itemData,
                itemIndex: action.itemIndex
            }
        }
    case UTIL_LAUNCH_INVENTORY_EXPORT:
        return {
            ...state,
            inventoryExport: {
                ...state.inventoryExport,
                windowsOpen: state.inventoryExport.windowsOpen + 1,
                activated: true,
                username: action.username,
                category: action.category,
                itemIndex: action.itemIndex,
                itemData: action.itemData,
                itemId: action.itemId
            }
        }
    case UTIL_LAUNCH_ENTITY_EDITOR:
        return {
            ...state,
            entityEdit: {
                ...state.entityEdit,
                windowsOpen: state.entityEdit.windowsOpen + 1,
                activated: true,
                username: action.username,
                category: action.category,
                itemId: action.itemId,
                source: action.source
            }
        }
     case UTIL_LAUNCH_COMPONENT_EDITOR:
        return {
            ...state,
            componentEdit: {
                ...state.componentEdit,
                windowsOpen: state.componentEdit.windowsOpen + 1,
                activated: true,
                username: action.username,
                itemId: action.itemId,
                source: action.source
            }
        }
    case UTIL_LAUNCH_ATTRIBUTE_EDITOR:
        return {
            ...state,
            attributeEdit: {
                ...state.attributeEdit,
                windowsOpen: state.attributeEdit.windowsOpen + 1,
                activated: true,
                username: action.username,
                itemId: action.itemId,
                source: action.source
            }
        }
    case UTIL_LAUNCH_EDIT_LOADED_ITEM:

        let data = {...state.loadedItemEdit.data },
            activated = {...state.loadedItemEdit.activated },
            source = {...state.loadedItemEdit.source }

        switch( action.category ) {
            case "Entities":
                data.entity = action.data
                activated.entity = true
                source.entity = action.source
            break
            case "Components":
                data.component = action.data
                activated.component = true
                source.component = action.source
            break
            case "Properties":
                data.attribute = action.data
                activated.attribute = true
                source.attribute = action.source
            break
        }

        return {
            ...state,
            loadedItemEdit: {
                ...state.loadedItemEdit,
                activated,
                data,
                username: action.username,
                index: action.index,
                category: action.category,
                source
            }
        }
    case UTIL_CLOSE_TEXT_EDIT:
        return {
            ...state,
            textEdit: {
                ...state.textEdit,
                windowsOpen: state.textEdit.windowsOpen - 1,
                activated: false,
                username: "",
                filename: "",
                dir: ""
            }
        }
    case UTIL_CLOSE_RENAME_FILE:
        return {
            ...state,
            renameFile: {
                ...state.renameFile,
                windowsOpen: state.renameFile.windowsOpen - 1,
                activated: false,
                username: "",
                filename: "",
                target: "",
                dir: ""
            }
        }
    case UTIL_CLOSE_SHARING_SETTINGS:
        return {
            ...state,
            sharingSettings: {
                ...state.sharingSettings,
                windowsOpen: state.sharingSettings.windowsOpen - 1,
                activated: false
            }
        }
    case UTIL_CLOSE_IMPORT_TO_INVENTORY:
        return {
            ...state,
            importToInventory: {
                ...state.importToInventory,
                windowsOpen: state.importToInventory.windowsOpen - 1,
                activated: false
            }
        }
    case UTIL_CLOSE_IMPORT_TO_SPACE:
        return {
            ...state,
            importToSpace: {
                ...state.importToSpace,
                windowsOpen: state.importToSpace.windowsOpen - 1,
                activated: false
            }
        }
    case UTIL_CLOSE_ENTITY_EDITOR:
        return {
            ...state,
            entityEdit: {
                ...state.entityEdit,
                windowsOpen: state.entityEdit.windowsOpen - 1,
                activated: false
            },
            loadedItemEdit: {
                ...state.loadedItemEdit,
                windowsOpen: state.loadedItemEdit.windowsOpen - 1,
                data: {
                    ...state.loadedItemEdit.data,
                    entity: null
                }
            }
        }
    case UTIL_CLOSE_INVENTORY_EXPORT:
        return {
            ...state,
            inventoryExport: {
                ...state.inventoryExport,
                windowsOpen: state.inventoryExport.windowsOpen - 1,
                activated: false
            }
        }
    case UTIL_CLOSE_COMPONENT_EDITOR:
        return {
            ...state,
            componentEdit: {
                ...state.componentEdit,
                windowsOpen: state.componentEdit.windowsOpen - 1,
                activated: false
            },
            loadedItemEdit: {
                ...state.loadedItemEdit,
                windowsOpen: state.loadedItemEdit.windowsOpen - 1,
                data: {
                    ...state.loadedItemEdit.data,
                    component: null
                }
            }
        }
    case UTIL_CLOSE_ATTRIBUTE_EDITOR:
        return {
            ...state,
            attributeEdit: {
                ...state.attributeEdit,
                windowsOpen: state.attributeEdit.windowsOpen - 1,
                activated: false
            },
            loadedItemEdit: {
                ...state.loadedItemEdit,
                windowsOpen: state.loadedItemEdit.windowsOpen - 1,
                data: {
                    ...state.loadedItemEdit.data,
                    attribute: null
                }
            }
        }
    default:
      return state;
  }
};


text:
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#include "elf-bfd.h"
#include "elf/sparc.h"
#include "opcode/sparc.h"
#include "elfxx-sparc.h"

/* In case we're on a 32-bit machine, construct a 64-bit "-1" value.  */
#define MINUS_ONE (~ (bfd_vma) 0)

/* Due to the way how we handle R_SPARC_OLO10, each entry in a SHT_RELA
   section can represent up to two relocs, we must tell the user to allocate
   more space.  */

static long
elf64_sparc_get_reloc_upper_bound (bfd *abfd ATTRIBUTE_UNUSED, asection *sec)
{
  return (sec->reloc_count * 2 + 1) * sizeof (arelent *);
}

static long
elf64_sparc_get_dynamic_reloc_upper_bound (bfd *abfd)
{
  return _bfd_elf_get_dynamic_reloc_upper_bound (abfd) * 2;
}

/* Read  relocations for ASECT from REL_HDR.  There are RELOC_COUNT of
   them.  We cannot use generic elf routines for this,  because R_SPARC_OLO10
   has secondary addend in ELF64_R_TYPE_DATA.  We handle it as two relocations
   for the same location,  R_SPARC_LO10 and R_SPARC_13.  */

static bfd_boolean
elf64_sparc_slurp_one_reloc_table (bfd *abfd, asection *asect,
				   Elf_Internal_Shdr *rel_hdr,
				   asymbol **symbols, bfd_boolean dynamic)
{
  void * allocated = NULL;
  bfd_byte *native_relocs;
  arelent *relent;
  unsigned int i;
  int entsize;
  bfd_size_type count;
  arelent *relents;

  allocated = bfd_malloc (rel_hdr->sh_size);
  if (allocated == NULL)
    goto error_return;

  if (bfd_seek (abfd, rel_hdr->sh_offset, SEEK_SET) != 0
      || bfd_bread (allocated, rel_hdr->sh_size, abfd) != rel_hdr->sh_size)
    goto error_return;

  native_relocs = (bfd_byte *) allocated;

  relents = asect->relocation + canon_reloc_count (asect);

  entsize = rel_hdr->sh_entsize;
  BFD_ASSERT (entsize == sizeof (Elf64_External_Rela));

  count = rel_hdr->sh_size / entsize;

  for (i = 0, relent = relents; i < count;
       i++, relent++, native_relocs += entsize)
    {
      Elf_Internal_Rela rela;
      unsigned int r_type;

      bfd_elf64_swap_reloca_in (abfd, native_relocs, &rela);

      /* The address of an ELF reloc is section relative for an object
	 file, and absolute for an executable file or shared library.
	 The address of a normal BFD reloc is always section relative,
	 and the address of a dynamic reloc is absolute..  */
      if ((abfd->flags & (EXEC_P | DYNAMIC)) == 0 || dynamic)
	relent->address = rela.r_offset;
      else
	relent->address = rela.r_offset - asect->vma;

      if (ELF64_R_SYM (rela.r_info) == STN_UNDEF)
	relent->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
      else
	{
	  asymbol **ps, *s;

	  ps = symbols + ELF64_R_SYM (rela.r_info) - 1;
	  s = *ps;

	  /* Canonicalize ELF section symbols.  FIXME: Why?  */
	  if ((s->flags & BSF_SECTION_SYM) == 0)
	    relent->sym_ptr_ptr = ps;
	  else
	    relent->sym_ptr_ptr = s->section->symbol_ptr_ptr;
	}

      relent->addend = rela.r_addend;

      r_type = ELF64_R_TYPE_ID (rela.r_info);
      if (r_type == R_SPARC_OLO10)
	{
	  relent->howto = _bfd_sparc_elf_info_to_howto_ptr (R_SPARC_LO10);
	  relent[1].address = relent->address;
	  relent++;
	  relent->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
	  relent->addend = ELF64_R_TYPE_DATA (rela.r_info);
	  relent->howto = _bfd_sparc_elf_info_to_howto_ptr (R_SPARC_13);
	}
      else
	relent->howto = _bfd_sparc_elf_info_to_howto_ptr (r_type);
    }

  canon_reloc_count (asect) += relent - relents;

  if (allocated != NULL)
    free (allocated);

  return TRUE;

 error_return:
  if (allocated != NULL)
    free (allocated);
  return FALSE;
}

/* Read in and swap the external relocs.  */

static bfd_boolean
elf64_sparc_slurp_reloc_table (bfd *abfd, asection *asect,
			       asymbol **symbols, bfd_boolean dynamic)
{
  struct bfd_elf_section_data * const d = elf_section_data (asect);
  Elf_Internal_Shdr *rel_hdr;
  Elf_Internal_Shdr *rel_hdr2;
  bfd_size_type amt;

  if (asect->relocation != NULL)
    return TRUE;

  if (! dynamic)
    {
      if ((asect->flags & SEC_RELOC) == 0
	  || asect->reloc_count == 0)
	return TRUE;

      rel_hdr = d->rel.hdr;
      rel_hdr2 = d->rela.hdr;

      BFD_ASSERT ((rel_hdr && asect->rel_filepos == rel_hdr->sh_offset)
		  || (rel_hdr2 && asect->rel_filepos == rel_hdr2->sh_offset));
    }
  else
    {
      /* Note that ASECT->RELOC_COUNT tends not to be accurate in this
	 case because relocations against this section may use the
	 dynamic symbol table, and in that case bfd_section_from_shdr
	 in elf.c does not update the RELOC_COUNT.  */
      if (asect->size == 0)
	return TRUE;

      rel_hdr = &d->this_hdr;
      asect->reloc_count = NUM_SHDR_ENTRIES (rel_hdr);
      rel_hdr2 = NULL;
    }

  amt = asect->reloc_count;
  amt *= 2 * sizeof (arelent);
  asect->relocation = (arelent *) bfd_alloc (abfd, amt);
  if (asect->relocation == NULL)
    return FALSE;

  /* The elf64_sparc_slurp_one_reloc_table routine increments
     canon_reloc_count.  */
  canon_reloc_count (asect) = 0;

  if (rel_hdr
      && !elf64_sparc_slurp_one_reloc_table (abfd, asect, rel_hdr, symbols,
					     dynamic))
    return FALSE;

  if (rel_hdr2
      && !elf64_sparc_slurp_one_reloc_table (abfd, asect, rel_hdr2, symbols,
					     dynamic))
    return FALSE;

  return TRUE;
}

/* Canonicalize the relocs.  */

static long
elf64_sparc_canonicalize_reloc (bfd *abfd, sec_ptr section,
				arelent **relptr, asymbol **symbols)
{
  arelent *tblptr;
  unsigned int i;
  const struct elf_backend_data *bed = get_elf_backend_data (abfd);

  if (! bed->s->slurp_reloc_table (abfd, section, symbols, FALSE))
    return -1;

  tblptr = section->relocation;
  for (i = 0; i < canon_reloc_count (section); i++)
    *relptr++ = tblptr++;

  *relptr = NULL;

  return canon_reloc_count (section);
}

/* Canonicalize the dynamic relocation entries.  Note that we return
   the dynamic relocations as a single block, although they are
   actually associated with particular sections; the interface, which
   was designed for SunOS style shared libraries, expects that there
   is only one set of dynamic relocs.  Any section that was actually
   installed in the BFD, and has type SHT_REL or SHT_RELA, and uses
   the dynamic symbol table, is considered to be a dynamic reloc
   section.  */

static long
elf64_sparc_canonicalize_dynamic_reloc (bfd *abfd, arelent **storage,
					asymbol **syms)
{
  asection *s;
  long ret;

  if (elf_dynsymtab (abfd) == 0)
    {
      bfd_set_error (bfd_error_invalid_operation);
      return -1;
    }

  ret = 0;
  for (s = abfd->sections; s != NULL; s = s->next)
    {
      if (elf_section_data (s)->this_hdr.sh_link == elf_dynsymtab (abfd)
	  && (elf_section_data (s)->this_hdr.sh_type == SHT_RELA))
	{
	  arelent *p;
	  long count, i;

	  if (! elf64_sparc_slurp_reloc_table (abfd, s, syms, TRUE))
	    return -1;
	  count = canon_reloc_count (s);
	  p = s->relocation;
	  for (i = 0; i < count; i++)
	    *storage++ = p++;
	  ret += count;
	}
    }

  *storage = NULL;

  return ret;
}

/* Write out the relocs.  */

static void
elf64_sparc_write_relocs (bfd *abfd, asection *sec, void * data)
{
  bfd_boolean *failedp = (bfd_boolean *) data;
  Elf_Internal_Shdr *rela_hdr;
  bfd_vma addr_offset;
  Elf64_External_Rela *outbound_relocas, *src_rela;
  unsigned int idx, count;
  asymbol *last_sym = 0;
  int last_sym_idx = 0;

  /* If we have already failed, don't do anything.  */
  if (*failedp)
    return;

  if ((sec->flags & SEC_RELOC) == 0)
    return;

  /* The linker backend writes the relocs out itself, and sets the
     reloc_count field to zero to inhibit writing them here.  Also,
     sometimes the SEC_RELOC flag gets set even when there aren't any
     relocs.  */
  if (sec->reloc_count == 0)
    return;

  /* We can combine two relocs that refer to the same address
     into R_SPARC_OLO10 if first one is R_SPARC_LO10 and the
     latter is R_SPARC_13 with no associated symbol.  */
  count = 0;
  for (idx = 0; idx < sec->reloc_count; idx++)
    {
      bfd_vma addr;

      ++count;

      addr = sec->orelocation[idx]->address;
      if (sec->orelocation[idx]->howto->type == R_SPARC_LO10
	  && idx < sec->reloc_count - 1)
	{
	  arelent *r = sec->orelocation[idx + 1];

	  if (r->howto->type == R_SPARC_13
	      && r->address == addr
	      && bfd_is_abs_section ((*r->sym_ptr_ptr)->section)
	      && (*r->sym_ptr_ptr)->value == 0)
	    ++idx;
	}
    }

  rela_hdr = elf_section_data (sec)->rela.hdr;

  rela_hdr->sh_size = rela_hdr->sh_entsize * count;
  rela_hdr->contents = bfd_alloc (abfd, rela_hdr->sh_size);
  if (rela_hdr->contents == NULL)
    {
      *failedp = TRUE;
      return;
    }

  /* Figure out whether the relocations are RELA or REL relocations.  */
  if (rela_hdr->sh_type != SHT_RELA)
    abort ();

  /* The address of an ELF reloc is section relative for an object
     file, and absolute for an executable file or shared library.
     The address of a BFD reloc is always section relative.  */
  addr_offset = 0;
  if ((abfd->flags & (EXEC_P | DYNAMIC)) != 0)
    addr_offset = sec->vma;

  /* orelocation has the data, reloc_count has the count...  */
  outbound_relocas = (Elf64_External_Rela *) rela_hdr->contents;
  src_rela = outbound_relocas;

  for (idx = 0; idx < sec->reloc_count; idx++)
    {
      Elf_Internal_Rela dst_rela;
      arelent *ptr;
      asymbol *sym;
      int n;

      ptr = sec->orelocation[idx];
      sym = *ptr->sym_ptr_ptr;
      if (sym == last_sym)
	n = last_sym_idx;
      else if (bfd_is_abs_section (sym->section) && sym->value == 0)
	n = STN_UNDEF;
      else
	{
	  last_sym = sym;
	  n = _bfd_elf_symbol_from_bfd_symbol (abfd, &sym);
	  if (n < 0)
	    {
	      *failedp = TRUE;
	      return;
	    }
	  last_sym_idx = n;
	}

      if ((*ptr->sym_ptr_ptr)->the_bfd != NULL
	  && (*ptr->sym_ptr_ptr)->the_bfd->xvec != abfd->xvec
	  && ! _bfd_elf_validate_reloc (abfd, ptr))
	{
	  *failedp = TRUE;
	  return;
	}

      if (ptr->howto->type == R_SPARC_LO10
	  && idx < sec->reloc_count - 1)
	{
	  arelent *r = sec->orelocation[idx + 1];

	  if (r->howto->type == R_SPARC_13
	      && r->address == ptr->address
	      && bfd_is_abs_section ((*r->sym_ptr_ptr)->section)
	      && (*r->sym_ptr_ptr)->value == 0)
	    {
	      idx++;
	      dst_rela.r_info
		= ELF64_R_INFO (n, ELF64_R_TYPE_INFO (r->addend,
						      R_SPARC_OLO10));
	    }
	  else
	    dst_rela.r_info = ELF64_R_INFO (n, R_SPARC_LO10);
	}
      else
	dst_rela.r_info = ELF64_R_INFO (n, ptr->howto->type);

      dst_rela.r_offset = ptr->address + addr_offset;
      dst_rela.r_addend = ptr->addend;

      bfd_elf64_swap_reloca_out (abfd, &dst_rela, (bfd_byte *) src_rela);
      ++src_rela;
    }
}

/* Hook called by the linker routine which adds symbols from an object
   file.  We use it for STT_REGISTER symbols.  */

static bfd_boolean
elf64_sparc_add_symbol_hook (bfd *abfd, struct bfd_link_info *info,
			     Elf_Internal_Sym *sym, const char **namep,
			     flagword *flagsp ATTRIBUTE_UNUSED,
			     asection **secp ATTRIBUTE_UNUSED,
			     bfd_vma *valp ATTRIBUTE_UNUSED)
{
  static const char *const stt_types[] = { "NOTYPE", "OBJECT", "FUNCTION" };

  if ((abfd->flags & DYNAMIC) == 0
      && (ELF_ST_TYPE (sym->st_info) == STT_GNU_IFUNC
	  || ELF_ST_BIND (sym->st_info) == STB_GNU_UNIQUE))
    elf_tdata (info->output_bfd)->has_gnu_symbols = TRUE;

  if (ELF_ST_TYPE (sym->st_info) == STT_REGISTER)
    {
      int reg;
      struct _bfd_sparc_elf_app_reg *p;

      reg = (int)sym->st_value;
      switch (reg & ~1)
	{
	case 2: reg -= 2; break;
	case 6: reg -= 4; break;
	default:
          (*_bfd_error_handler)
            (_("%B: Only registers %%g[2367] can be declared using STT_REGISTER"),
             abfd);
	  return FALSE;
	}

      if (info->output_bfd->xvec != abfd->xvec
	  || (abfd->flags & DYNAMIC) != 0)
        {
	  /* STT_REGISTER only works when linking an elf64_sparc object.
	     If STT_REGISTER comes from a dynamic object, don't put it into
	     the output bfd.  The dynamic linker will recheck it.  */
	  *namep = NULL;
	  return TRUE;
        }

      p = _bfd_sparc_elf_hash_table(info)->app_regs + reg;

      if (p->name != NULL && strcmp (p->name, *namep))
	{
          (*_bfd_error_handler)
            (_("Register %%g%d used incompatibly: %s in %B, previously %s in %B"),
             abfd, p->abfd, (int) sym->st_value,
             **namep ? *namep : "#scratch",
             *p->name ? p->name : "#scratch");
	  return FALSE;
	}

      if (p->name == NULL)
	{
	  if (**namep)
	    {
	      struct elf_link_hash_entry *h;

	      h = (struct elf_link_hash_entry *)
		bfd_link_hash_lookup (info->hash, *namep, FALSE, FALSE, FALSE);

	      if (h != NULL)
		{
		  unsigned char type = h->type;

		  if (type > STT_FUNC)
		    type = 0;
		  (*_bfd_error_handler)
		    (_("Symbol `%s' has differing types: REGISTER in %B, previously %s in %B"),
		     abfd, p->abfd, *namep, stt_types[type]);
		  return FALSE;
		}

	      p->name = bfd_hash_allocate (&info->hash->table,
					   strlen (*namep) + 1);
	      if (!p->name)
		return FALSE;

	      strcpy (p->name, *namep);
	    }
	  else
	    p->name = "";
	  p->bind = ELF_ST_BIND (sym->st_info);
	  p->abfd = abfd;
	  p->shndx = sym->st_shndx;
	}
      else
	{
	  if (p->bind == STB_WEAK
	      && ELF_ST_BIND (sym->st_info) == STB_GLOBAL)
	    {
	      p->bind = STB_GLOBAL;
	      p->abfd = abfd;
	    }
	}
      *namep = NULL;
      return TRUE;
    }
  else if (*namep && **namep
	   && info->output_bfd->xvec == abfd->xvec)
    {
      int i;
      struct _bfd_sparc_elf_app_reg *p;

      p = _bfd_sparc_elf_hash_table(info)->app_regs;
      for (i = 0; i < 4; i++, p++)
	if (p->name != NULL && ! strcmp (p->name, *namep))
	  {
	    unsigned char type = ELF_ST_TYPE (sym->st_info);

	    if (type > STT_FUNC)
	      type = 0;
	    (*_bfd_error_handler)
	      (_("Symbol `%s' has differing types: %s in %B, previously REGISTER in %B"),
	       abfd, p->abfd, *namep, stt_types[type]);
	    return FALSE;
	  }
    }
  return TRUE;
}

/* This function takes care of emitting STT_REGISTER symbols
   which we cannot easily keep in the symbol hash table.  */

static bfd_boolean
elf64_sparc_output_arch_syms (bfd *output_bfd ATTRIBUTE_UNUSED,
			      struct bfd_link_info *info,
			      void * flaginfo,
			      int (*func) (void *, const char *,
					   Elf_Internal_Sym *,
					   asection *,
					   struct elf_link_hash_entry *))
{
  int reg;
  struct _bfd_sparc_elf_app_reg *app_regs =
    _bfd_sparc_elf_hash_table(info)->app_regs;
  Elf_Internal_Sym sym;

  /* We arranged in size_dynamic_sections to put the STT_REGISTER entries
     at the end of the dynlocal list, so they came at the end of the local
     symbols in the symtab.  Except that they aren't STB_LOCAL, so we need
     to back up symtab->sh_info.  */
  if (elf_hash_table (info)->dynlocal)
    {
      bfd * dynobj = elf_hash_table (info)->dynobj;
      asection *dynsymsec = bfd_get_linker_section (dynobj, ".dynsym");
      struct elf_link_local_dynamic_entry *e;

      for (e = elf_hash_table (info)->dynlocal; e ; e = e->next)
	if (e->input_indx == -1)
	  break;
      if (e)
	{
	  elf_section_data (dynsymsec->output_section)->this_hdr.sh_info
	    = e->dynindx;
	}
    }

  if (info->strip == strip_all)
    return TRUE;

  for (reg = 0; reg < 4; reg++)
    if (app_regs [reg].name != NULL)
      {
	if (info->strip == strip_some
	    && bfd_hash_lookup (info->keep_hash,
				app_regs [reg].name,
				FALSE, FALSE) == NULL)
	  continue;

	sym.st_value = reg < 2 ? reg + 2 : reg + 4;
	sym.st_size = 0;
	sym.st_other = 0;
	sym.st_info = ELF_ST_INFO (app_regs [reg].bind, STT_REGISTER);
	sym.st_shndx = app_regs [reg].shndx;
	sym.st_target_internal = 0;
	if ((*func) (flaginfo, app_regs [reg].name, &sym,
		     sym.st_shndx == SHN_ABS
		     ? bfd_abs_section_ptr : bfd_und_section_ptr,
		     NULL) != 1)
	  return FALSE;
      }

  return TRUE;
}

static int
elf64_sparc_get_symbol_type (Elf_Internal_Sym *elf_sym, int type)
{
  if (ELF_ST_TYPE (elf_sym->st_info) == STT_REGISTER)
    return STT_REGISTER;
  else
    return type;
}

/* A STB_GLOBAL,STT_REGISTER symbol should be BSF_GLOBAL
   even in SHN_UNDEF section.  */

static void
elf64_sparc_symbol_processing (bfd *abfd ATTRIBUTE_UNUSED, asymbol *asym)
{
  elf_symbol_type *elfsym;

  elfsym = (elf_symbol_type *) asym;
  if (elfsym->internal_elf_sym.st_info
      == ELF_ST_INFO (STB_GLOBAL, STT_REGISTER))
    {
      asym->flags |= BSF_GLOBAL;
    }
}

/* Functions for dealing with the e_flags field.  */

/* Merge backend specific data from an object file to the output
   object file when linking.  */

static bfd_boolean
elf64_sparc_merge_private_bfd_data (bfd *ibfd, bfd *obfd)
{
  bfd_boolean error;
  flagword new_flags, old_flags;
  int new_mm, old_mm;

  if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour
      || bfd_get_flavour (obfd) != bfd_target_elf_flavour)
    return TRUE;

  new_flags = elf_elfheader (ibfd)->e_flags;
  old_flags = elf_elfheader (obfd)->e_flags;

  if (!elf_flags_init (obfd))   /* First call, no flags set */
    {
      elf_flags_init (obfd) = TRUE;
      elf_elfheader (obfd)->e_flags = new_flags;
    }

  else if (new_flags == old_flags)      /* Compatible flags are ok */
    ;

  else                                  /* Incompatible flags */
    {
      error = FALSE;

#define EF_SPARC_ISA_EXTENSIONS \
  (EF_SPARC_SUN_US1 | EF_SPARC_SUN_US3 | EF_SPARC_HAL_R1)

      if ((ibfd->flags & DYNAMIC) != 0)
	{
	  /* We don't want dynamic objects memory ordering and
	     architecture to have any role. That's what dynamic linker
	     should do.  */
	  new_flags &= ~(EF_SPARCV9_MM | EF_SPARC_ISA_EXTENSIONS);
	  new_flags |= (old_flags
			& (EF_SPARCV9_MM | EF_SPARC_ISA_EXTENSIONS));
	}
      else
	{
	  /* Choose the highest architecture requirements.  */
	  old_flags |= (new_flags & EF_SPARC_ISA_EXTENSIONS);
	  new_flags |= (old_flags & EF_SPARC_ISA_EXTENSIONS);
	  if ((old_flags & (EF_SPARC_SUN_US1 | EF_SPARC_SUN_US3))
	      && (old_flags & EF_SPARC_HAL_R1))
	    {
	      error = TRUE;
	      (*_bfd_error_handler)
		(_("%B: linking UltraSPARC specific with HAL specific code"),
		 ibfd);
	    }
	  /* Choose the most restrictive memory ordering.  */
	  old_mm = (old_flags & EF_SPARCV9_MM);
	  new_mm = (new_flags & EF_SPARCV9_MM);
	  old_flags &= ~EF_SPARCV9_MM;
	  new_flags &= ~EF_SPARCV9_MM;
	  if (new_mm < old_mm)
	    old_mm = new_mm;
	  old_flags |= old_mm;
	  new_flags |= old_mm;
	}

      /* Warn about any other mismatches */
      if (new_flags != old_flags)
        {
          error = TRUE;
          (*_bfd_error_handler)
            (_("%B: uses different e_flags (0x%lx) fields than previous modules (0x%lx)"),
             ibfd, (long) new_flags, (long) old_flags);
        }

      elf_elfheader (obfd)->e_flags = old_flags;

      if (error)
        {
          bfd_set_error (bfd_error_bad_value);
          return FALSE;
        }
    }
  return _bfd_sparc_elf_merge_private_bfd_data (ibfd, obfd);
}

/* MARCO: Set the correct entry size for the .stab section.  */

static bfd_boolean
elf64_sparc_fake_sections (bfd *abfd ATTRIBUTE_UNUSED,
			   Elf_Internal_Shdr *hdr ATTRIBUTE_UNUSED,
			   asection *sec)
{
  const char *name;

  name = bfd_get_section_name (abfd, sec);

  if (strcmp (name, ".stab") == 0)
    {
      /* Even in the 64bit case the stab entries are only 12 bytes long.  */
      elf_section_data (sec)->this_hdr.sh_entsize = 12;
    }

  return TRUE;
}

/* Print a STT_REGISTER symbol to file FILE.  */

static const char *
elf64_sparc_print_symbol_all (bfd *abfd ATTRIBUTE_UNUSED, void * filep,
			      asymbol *symbol)
{
  FILE *file = (FILE *) filep;
  int reg, type;

  if (ELF_ST_TYPE (((elf_symbol_type *) symbol)->internal_elf_sym.st_info)
      != STT_REGISTER)
    return NULL;

  reg = ((elf_symbol_type *) symbol)->internal_elf_sym.st_value;
  type = symbol->flags;
  fprintf (file, "REG_%c%c%11s%c%c    R", "GOLI" [reg / 8], '0' + (reg & 7), "",
		 ((type & BSF_LOCAL)
		  ? (type & BSF_GLOBAL) ? '!' : 'l'
	          : (type & BSF_GLOBAL) ? 'g' : ' '),
	         (type & BSF_WEAK) ? 'w' : ' ');
  if (symbol->name == NULL || symbol->name [0] == '\0')
    return "#scratch";
  else
    return symbol->name;
}

static enum elf_reloc_type_class
elf64_sparc_reloc_type_class (const struct bfd_link_info *info ATTRIBUTE_UNUSED,
			      const asection *rel_sec ATTRIBUTE_UNUSED,
			      const Elf_Internal_Rela *rela)
{
  switch ((int) ELF64_R_TYPE (rela->r_info))
    {
    case R_SPARC_RELATIVE:
      return reloc_class_relative;
    case R_SPARC_JMP_SLOT:
      return reloc_class_plt;
    case R_SPARC_COPY:
      return reloc_class_copy;
    default:
      return reloc_class_normal;
    }
}

/* Relocations in the 64 bit SPARC ELF ABI are more complex than in
   standard ELF, because R_SPARC_OLO10 has secondary addend in
   ELF64_R_TYPE_DATA field.  This structure is used to redirect the
   relocation handling routines.  */

const struct elf_size_info elf64_sparc_size_info =
{
  sizeof (Elf64_External_Ehdr),
  sizeof (Elf64_External_Phdr),
  sizeof (Elf64_External_Shdr),
  sizeof (Elf64_External_Rel),
  sizeof (Elf64_External_Rela),
  sizeof (Elf64_External_Sym),
  sizeof (Elf64_External_Dyn),
  sizeof (Elf_External_Note),
  4,		/* hash-table entry size.  */
  /* Internal relocations per external relocations.
     For link purposes we use just 1 internal per
     1 external, for assembly and slurp symbol table
     we use 2.  */
  1,
  64,		/* arch_size.  */
  3,		/* log_file_align.  */
  ELFCLASS64,
  EV_CURRENT,
  bfd_elf64_write_out_phdrs,
  bfd_elf64_write_shdrs_and_ehdr,
  bfd_elf64_checksum_contents,
  elf64_sparc_write_relocs,
  bfd_elf64_swap_symbol_in,
  bfd_elf64_swap_symbol_out,
  elf64_sparc_slurp_reloc_table,
  bfd_elf64_slurp_symbol_table,
  bfd_elf64_swap_dyn_in,
  bfd_elf64_swap_dyn_out,
  bfd_elf64_swap_reloc_in,
  bfd_elf64_swap_reloc_out,
  bfd_elf64_swap_reloca_in,
  bfd_elf64_swap_reloca_out
};

#define TARGET_BIG_SYM	bfd_elf64_sparc_vec
#define TARGET_BIG_NAME	"elf64-sparc"
#define ELF_ARCH	bfd_arch_sparc
#define ELF_MAXPAGESIZE 0x100000
#define ELF_COMMONPAGESIZE 0x2000

/* This is the official ABI value.  */
#define ELF_MACHINE_CODE EM_SPARCV9

/* This is the value that we used before the ABI was released.  */
#define ELF_MACHINE_ALT1 EM_OLD_SPARCV9

#define elf_backend_reloc_type_class \
  elf64_sparc_reloc_type_class
#define bfd_elf64_get_reloc_upper_bound \
  elf64_sparc_get_reloc_upper_bound
#define bfd_elf64_get_dynamic_reloc_upper_bound \
  elf64_sparc_get_dynamic_reloc_upper_bound
#define bfd_elf64_canonicalize_reloc \
  elf64_sparc_canonicalize_reloc
#define bfd_elf64_canonicalize_dynamic_reloc \
  elf64_sparc_canonicalize_dynamic_reloc
#define elf_backend_add_symbol_hook \
  elf64_sparc_add_symbol_hook
#define elf_backend_get_symbol_type \
  elf64_sparc_get_symbol_type
#define elf_backend_symbol_processing \
  elf64_sparc_symbol_processing
#define elf_backend_print_symbol_all \
  elf64_sparc_print_symbol_all
#define elf_backend_output_arch_syms \
  elf64_sparc_output_arch_syms
#define bfd_elf64_bfd_merge_private_bfd_data \
  elf64_sparc_merge_private_bfd_data
#define elf_backend_fake_sections \
  elf64_sparc_fake_sections
#define elf_backend_size_info \
  elf64_sparc_size_info

#define elf_backend_plt_sym_val	\
  _bfd_sparc_elf_plt_sym_val
#define bfd_elf64_bfd_link_hash_table_create \
  _bfd_sparc_elf_link_hash_table_create
#define bfd_elf64_bfd_link_hash_table_free \
  _bfd_sparc_elf_link_hash_table_free
#define elf_info_to_howto \
  _bfd_sparc_elf_info_to_howto
#define elf_backend_copy_indirect_symbol \
  _bfd_sparc_elf_copy_indirect_symbol
#define bfd_elf64_bfd_reloc_type_lookup \
  _bfd_sparc_elf_reloc_type_lookup
#define bfd_elf64_bfd_reloc_name_lookup \
  _bfd_sparc_elf_reloc_name_lookup
#define bfd_elf64_bfd_relax_section \
  _bfd_sparc_elf_relax_section
#define bfd_elf64_new_section_hook \
  _bfd_sparc_elf_new_section_hook

#define elf_backend_create_dynamic_sections \
  _bfd_sparc_elf_create_dynamic_sections
#define elf_backend_relocs_compatible \
  _bfd_elf_relocs_compatible
#define elf_backend_check_relocs \
  _bfd_sparc_elf_check_relocs
#define elf_backend_adjust_dynamic_symbol \
  _bfd_sparc_elf_adjust_dynamic_symbol
#define elf_backend_omit_section_dynsym \
  _bfd_sparc_elf_omit_section_dynsym
#define elf_backend_size_dynamic_sections \
  _bfd_sparc_elf_size_dynamic_sections
#define elf_backend_relocate_section \
  _bfd_sparc_elf_relocate_section
#define elf_backend_finish_dynamic_symbol \
  _bfd_sparc_elf_finish_dynamic_symbol
#define elf_backend_finish_dynamic_sections \
  _bfd_sparc_elf_finish_dynamic_sections

#define bfd_elf64_mkobject \
  _bfd_sparc_elf_mkobject
#define elf_backend_object_p \
  _bfd_sparc_elf_object_p
#define elf_backend_gc_mark_hook \
  _bfd_sparc_elf_gc_mark_hook
#define elf_backend_gc_sweep_hook \
  _bfd_sparc_elf_gc_sweep_hook
#define elf_backend_init_index_section \
  _bfd_elf_init_1_index_section

#define elf_backend_can_gc_sections 1
#define elf_backend_can_refcount 1
#define elf_backend_want_got_plt 0
#define elf_backend_plt_readonly 0
#define elf_backend_want_plt_sym 1
#define elf_backend_got_header_size 8
#define elf_backend_rela_normal 1

/* Section 5.2.4 of the ABI specifies a 256-byte boundary for the table.  */
#define elf_backend_plt_alignment 8

#include "elf64-target.h"

/* FreeBSD support */
#undef  TARGET_BIG_SYM
#define TARGET_BIG_SYM bfd_elf64_sparc_freebsd_vec
#undef  TARGET_BIG_NAME
#define TARGET_BIG_NAME "elf64-sparc-freebsd"
#undef	ELF_OSABI
#define	ELF_OSABI ELFOSABI_FREEBSD

#undef  elf64_bed
#define elf64_bed				elf64_sparc_fbsd_bed

#include "elf64-target.h"

/* Solaris 2.  */

#undef	TARGET_BIG_SYM
#define	TARGET_BIG_SYM				bfd_elf64_sparc_sol2_vec
#undef	TARGET_BIG_NAME
#define	TARGET_BIG_NAME				"elf64-sparc-sol2"

/* Restore default: we cannot use ELFOSABI_SOLARIS, otherwise ELFOSABI_NONE
   objects won't be recognized.  */
#undef	ELF_OSABI

#undef elf64_bed
#define elf64_bed				elf64_sparc_sol2_bed

/* The 64-bit static TLS arena size is rounded to the nearest 16-byte
   boundary.  */
#undef elf_backend_static_tls_alignment
#define elf_backend_static_tls_alignment	16

#include "elf64-target.h"


text:
package disconnectionist.www.borrower;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by jameshudson on 24/2/17.
 */

    public class BorrowItem implements Serializable {
        String user;
        String item;
        Date date;
    }


text: Guías de soporte para código rápido


text:
#include <unordered_map>
#include "Trie.h"

using namespace std;

Trie::Trie(){
	root = new Node();
}

Trie::~Trie(){
	remove(root);
}

void Trie::remove(Node *n){
    // Loop thru every child node visiting it recursivelly
    for(pair<char,Node*> p: n->children)
        remove(p.second);
    // Delete current node
    delete n;
}

void Trie::insert(string str){
    Node* node = root; // Current node being visited
    // Loop thru every letter on the String
    for(char c: str){
        // Adds a children node if it doesn't find any with that key
        if(node->children.find(c) == node->children.end()){
            node->children[c] = new Node();
            node->isLeaf = false;
        }
        // Visit next node
        node = node->children[c];
    }
    // Sets the end of the word
    node->endOfWord = true;
}

bool Trie::search(string str){
    Node *node = root; // Current node
    // Loop thru every character on the string
    for(char c:str){
        // Return false if key is not found or reach a leaf node
        if(node->children.find(c) == node->children.end() || node->isLeaf)
            return false;
        // Visit next node
        node = node->children[c];
    }
    // Once all charachters matched, returns true
    return true;
}


text:
require 'xmlsimple'
require 'aliyun/oss'

# Using Aliyun OSS Ruby SDK
AliyunOssSdk= Aliyun::OSS

module Fog
  module Aliyun
    class Storage < Fog::Service
      COMPLIANT_BUCKET_NAMES = /^(?:[a-z]|\d(?!\d{0,2}(?:\.\d{1,3}){3}$))(?:[a-z0-9]|\.(?![\.\-])|\-(?![\.])){1,61}[a-z0-9]$/
      DEFAULT_REGION = 'cn-hangzhou'

      DEFAULT_SCHEME = 'https'
      DEFAULT_SCHEME_PORT = {
        'http' => 80,
        'https' => 443
      }.freeze

      recognizes :aliyun_oss_endpoint,
                 :aliyun_oss_location,
                 :aliyun_region_id,
                 :aliyun_oss_sdk_log_path

      requires :aliyun_accesskey_id,
               :aliyun_accesskey_secret,
               :aliyun_oss_bucket

      model_path 'fog/aliyun/models/storage'
      model :directory
      collection :directories
      model :file
      collection :files

      request_path 'fog/aliyun/requests/storage'
      request :copy_object
      request :delete_bucket
      request :delete_object
      request :delete_multiple_objects
      request :get_bucket
      request :get_bucket_location
      request :get_object
      request :get_object_acl
      request :get_object_http_url
      request :get_object_https_url
      request :head_object
      request :put_bucket
      request :put_object
      request :get_service
      request :list_buckets
      request :list_objects
      request :initiate_multipart_upload
      request :upload_part
      request :complete_multipart_upload
      request :abort_multipart_upload

      class Real
        # Initialize connection to OSS
        #
        # ==== Notes
        # options parameter must include values for :aliyun_accesskey_id, :aliyun_secret_access_key and :aliyun_oss_bucket in order to create a connection.
        # :aliyun_oss_location will be replaced by :aliyun_region_id, and it has a default value cn-hangzhou
        # if :aliyun_oss_endpoint is not specified, it will be generated by method region_to_endpoint
        #
        # ==== Examples
        #   sdb = Fog::Storage.new(:provider=>'aliyun',
        #    :aliyun_accesskey_id => your_:aliyun_accesskey_id,
        #    :aliyun_secret_access_key => your_aliyun_secret_access_key
        #   )
        #
        # ==== Parameters
        # * options<~Hash> - config arguments for connection.  Defaults to {}.
        #
        # ==== Returns
        # * OSS object with connection to aliyun.
        attr_reader :aliyun_accesskey_id
        attr_reader :aliyun_accesskey_secret
        attr_reader :aliyun_oss_endpoint
        attr_reader :aliyun_region_id
        attr_reader :aliyun_oss_bucket
        attr_reader :aliyun_oss_sdk_log_path

        def initialize(options = {})
          # initialize the parameters
          @aliyun_region_id = options[:aliyun_region_id] || options[:aliyun_oss_location] || DEFAULT_REGION
          @aliyun_oss_endpoint = options[:aliyun_oss_endpoint] || region_to_endpoint(@aliyun_region_id)
          @aliyun_accesskey_id = options[:aliyun_accesskey_id]
          @aliyun_accesskey_secret = options[:aliyun_accesskey_secret]
          @aliyun_oss_bucket = options[:aliyun_oss_bucket]
          @aliyun_oss_sdk_log_path=options[:aliyun_oss_sdk_log_path]
          if @aliyun_oss_sdk_log_path && !::File.exist?(@aliyun_oss_sdk_log_path)
            `touch #{@aliyun_oss_sdk_log_path}`
          end
          ENV["ALIYUN_OSS_SDK_LOG_PATH"] = @aliyun_oss_sdk_log_path
          # check for the parameters
          missing_credentials = []
          missing_credentials << :aliyun_oss_bucket unless @aliyun_oss_bucket
          missing_credentials << :aliyun_accesskey_id unless @aliyun_accesskey_id
          missing_credentials << :aliyun_accesskey_secret unless @aliyun_accesskey_secret
          raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty?

          @connection_options = options[:connection_options] || {}

          endpoint = @aliyun_oss_endpoint

          @aliyun_oss_endpoint = "#{DEFAULT_SCHEME}://#{endpoint}" unless endpoint.start_with?(DEFAULT_SCHEME)

          uri = URI.parse(@aliyun_oss_endpoint)
          @host = uri.host
          @path = uri.path
          @scheme = uri.scheme || DEFAULT_SCHEME
          @port = uri.port || DEFAULT_SCHEME_PORT[@scheme]

          @persistent = options[:persistent] || false
          @oss_client = AliyunOssSdk::Client.new(
                                     :endpoint => @aliyun_oss_endpoint,
                                     :access_key_id => @aliyun_accesskey_id,
                                     :access_key_secret => @aliyun_accesskey_secret
          )

          # initiate a aliyun oss ruby sdk config and using sdk http to invoke the OSS openapi
          @oss_config = AliyunOssSdk::Config.new(
              :endpoint => @aliyun_oss_endpoint,
              :access_key_id => @aliyun_accesskey_id,
              :access_key_secret => @aliyun_accesskey_secret
          )
          @oss_http = AliyunOssSdk::HTTP.new(@oss_config)
          @oss_protocol = AliyunOssSdk::Protocol.new(@oss_config)
        end

        def reload
          @connection.reset
        end

        def region_to_endpoint(region = nil)
          case region.to_s
          when ''
            "oss-#{DEFAULT_REGION}.aliyuncs.com"
          else
            "oss-#{region}.aliyuncs.com"
          end
        end

        def object_to_path(object_name=nil)
          '/' + escape(object_name.to_s).gsub('%2F','/')
        end

        def escape(string)
          string.gsub(/([^a-zA-Z0-9_.\-~\/]+)/) {
            "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase
          }
        end

        def request(params)
          method = params[:method]
          time = Time.new.utc
          date = time.strftime('%a, %d %b %Y %H:%M:%S GMT')

          bucket = params[:bucket]
          tmpHost = if bucket
                      bucket + '.' + @host
                    else
                      @host
                    end

          @connection = Fog::Core::Connection.new("#{@scheme}://#{tmpHost}", @persistent, @connection_options)
          contentType = params[:contentType]

          begin
            headers = ''
            if params[:headers]
              params[:headers].each do |k, v|
              headers += "#{k}:#{v}\n" if k != 'Range'
              end
            end
            signature = sign(method, date, contentType, params[:resource], headers)
            response = @connection.request(params.merge(headers: {
              'Content-Type' => contentType,
              'Authorization' => 'OSS ' + @aliyun_accesskey_id + ':' + signature,
              'Date' => date
            }.merge!(params[:headers] || {}),
                                                        path: "#{@path}/#{params[:path]}",
                                                        query: params[:query]))
          rescue Excon::Errors::HTTPStatusError => error
            raise case error
                  when Excon::Errors::NotFound
                    Fog::Aliyun::Storage::NotFound.slurp(error)
                  else
                    error
                  end
          end

          response
        end

        # copmute signature
        def sign(method, date, contentType, resource = nil, headers = nil)
          contentmd5 = ''

          canonicalizedResource = if resource
                                    '/' + resource
                                  else
                                    '/'
                                  end

          canonicalizedOSSHeaders = headers || ''

          contentTypeStr = contentType || ''

          stringToSign = method + "\n" + contentmd5 + "\n" + contentTypeStr + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource

          digVer = OpenSSL::Digest.new('sha1')
          digest = OpenSSL::HMAC.digest(digVer, @aliyun_accesskey_secret, stringToSign)
          signature = Base64.encode64(digest)
          signature[-1] = ''

          signature
        end
      end

      class Mock
        def initialize(options = {})
          @aliyun_oss_endpoint = options[:aliyun_oss_endpoint]
          @aliyun_region_id = options[:aliyun_region_id]
          @aliyun_accesskey_id = options[:aliyun_accesskey_id]
          @aliyun_accesskey_secret = options[:aliyun_accesskey_secret]
          @aliyun_oss_bucket = options[:aliyun_oss_bucket]

          @connection_options = options[:connection_options] || {}
        end
      end
    end
  end
end


text:
"""Test for Aladdin Connect init logic."""
from unittest.mock import patch

from homeassistant.components.aladdin_connect.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry

YAML_CONFIG = {"username": "test-user", "password": "test-password"}

async def test_entry_password_fail(hass: HomeAssistant):
    """Test password fail during entry."""
    entry = MockConfigEntry(
        domain=DOMAIN,
        data={"username": "test-user", "password": "test-password"},
    )
    entry.add_to_hass(hass)

    with patch(
        "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.login",
        return_value=False,
    ):

        await hass.config_entries.async_setup(entry.entry_id)
        await hass.async_block_till_done()
        assert entry.state is ConfigEntryState.SETUP_ERROR

async def test_load_and_unload(hass: HomeAssistant) -> None:
    """Test loading and unloading Aladdin Connect entry."""
    config_entry = MockConfigEntry(
        domain=DOMAIN,
        data=YAML_CONFIG,
        unique_id="test-id",
    )
    config_entry.add_to_hass(hass)
    with patch(
        "homeassistant.components.aladdin_connect.cover.AladdinConnectClient.login",
        return_value=True,
    ):

        await hass.config_entries.async_setup(config_entry.entry_id)
        await hass.async_block_till_done()

    assert config_entry.state == ConfigEntryState.LOADED
    assert len(hass.config_entries.async_entries(DOMAIN)) == 1

    assert await config_entry.async_unload(hass)
    await hass.async_block_till_done()
    assert config_entry.state == ConfigEntryState.NOT_LOADED


text:
require 'rho/rhocontroller'
require 'json'
require 'helpers/application_helper'
require 'helpers/browser_helper'

class ApplicationtestController < Rho::RhoController

def minimize
  Rho::Application.minimize
end

def restore
  Rho::Application.restore
end

def quit
  Rho::Application.quit
end

def start_original
  Rho::Application.startURI= '/app/index.html'
end

def start_local
  Rho::Application.startURI= '/app/loading.html'
end

def start_web
  Rho::Application.startURI= 'http://www.google.com'
end

def start_null
  Rho::Application.startURI= ''
end

def start_invalid
  Rho::Application.startURI= '/app/idontExist.html'
end

def set_title
  if @params['empty']
    Rho::Application.title =''
  else
    Rho::Application.title ='MyTitle'
  end
end

# callback method
def menu_callback
  Rho::Log.info("menu_callback", "LOG_TEST")
end

def menu_test
  Rho::Application.nativeMenu = [
    {:label=>'Home', :action=>'Home'},
    {:label=>'separator', :action=>'separator'},
    {:label=>'Options', :action=>'options'},
    {:label=>'Log', :action=>'log'},
    {:label=>'Exit', :action=>'exit'},
    {:label=>'Refresh', :action=>'refresh'},
    {:label=>'Callback', :action=> url_for(:action => :menu_callback)}
  ]
end

def menu_default
  Rho::Application.nativeMenu = Rho::Application.defaultNativeMenu
end

def menu_reservedItem
  Rho::Application.nativeMenu = [
    {:label=>'Options', :action=> 'Options'},
    {:label=>'Exit', :action=> 'exit'},
    {:label=>'Log', :action=> 'Log'},
    {:label=>'Refresh', :action=> 'Refresh'},
    {:label=>'Home', :action=> 'Home'},
    {:label=>'Load a page', :action=> '/app/loading.html'}
  ]
end

def menu_jscall
  Rho::Application.nativeMenu = [
    {:label=>'Log', :action=> 'Log'},
    {:label=>'fullscreen', :action=> 'fullscreen'},
    {:label=>'Exit', :action=>'javascript=>onQuit()'},
    {:label=>'separator', :action=> 'separator '},
    {:label=>'Refresh', :action=> 'Refresh'},
    { :label=>'Home', :action=> 'Home'},
    {:label=>'Load a page', :action=> '/app/loading.html'}
  ]
end

def badlink_uri
  @data1 = Rho::Application.badLinkURI
  if @data1
    @data = @data1.gsub(/(?=\W)/, '\\').to_s
  else
    @data = ''
  end
  Rho::WebView.executeJavascript('document.getElementById("verificationResult").innerHTML= "'+@data+'";')
end

def securitytoken
  @data1 = Rho::Application.securityTokenNotPassed
  @data = @data1.to_s
  Rho::WebView.executeJavascript('document.getElementById("verificationResult").innerHTML= "'+@data+'";')
end

def start_uri
  @data = Rho::Application.startURI
  Rho::WebView.executeJavascript('document.getElementById("verificationResult").innerHTML= "'+@data+'";')
end

def database_file
  local = Rho::Application.databaseFilePath('local')
  filepath = Rho::Application.relativeDatabaseBlobFilePath(local)
  data = Rho::Application.expandDatabaseBlobFilePath(filepath)
  Rho::WebView.executeJavascript('document.getElementById("verificationResult").innerHTML= "'+data+'";')
end

end


text:
import { PassengerPlus16 } from "../../";

export = PassengerPlus16;


text:
package pkg03.console.applications;

import java.util.Scanner;

public class Task4b_PrintZfigure {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int input = Integer.parseInt(scanner.nextLine());
//        Use two nested loops to print the Z figure
        for (int row = 0; row < input; row++) {
            for (int column = 0; column < input; column++) {
                if (row == 0 || row == input - 1 || column == input - 1 - row) {
                    System.out.print("* ");
                } else {
                    System.out.print(" ");
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.polylineEventPropTypes = exports.polylineDefaultPropTypes = exports.polylineControlledPropTypes = undefined;

var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of");

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require("babel-runtime/helpers/createClass");

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn");

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require("babel-runtime/helpers/inherits");

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require("react");

var _react2 = _interopRequireDefault(_react);

var _PolylineEventList = require("../eventLists/PolylineEventList");

var _PolylineEventList2 = _interopRequireDefault(_PolylineEventList);

var _eventHandlerCreator2 = require("../utils/eventHandlerCreator");

var _eventHandlerCreator3 = _interopRequireDefault(_eventHandlerCreator2);

var _defaultPropsCreator = require("../utils/defaultPropsCreator");

var _defaultPropsCreator2 = _interopRequireDefault(_defaultPropsCreator);

var _composeOptions = require("../utils/composeOptions");

var _composeOptions2 = _interopRequireDefault(_composeOptions);

var _componentLifecycleDecorator = require("../utils/componentLifecycleDecorator");

var _componentLifecycleDecorator2 = _interopRequireDefault(_componentLifecycleDecorator);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var polylineControlledPropTypes = exports.polylineControlledPropTypes = {
  // NOTICE!!!!!!
  //
  // Only expose those with getters & setters in the table as controlled props.
  //
  // [].map.call($0.querySelectorAll("tr>td>code"), function(it){ return it.textContent; })
  //    .filter(function(it){ return it.match(/^set/) && !it.match(/^setMap/); })
  //
  // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline
  draggable: _react.PropTypes.bool,
  editable: _react.PropTypes.bool,
  options: _react.PropTypes.object,
  path: _react.PropTypes.any,
  visible: _react.PropTypes.bool
};

var polylineDefaultPropTypes = exports.polylineDefaultPropTypes = (0, _defaultPropsCreator2.default)(polylineControlledPropTypes);

var polylineUpdaters = {
  draggable: function draggable(_draggable, component) {
    component.getPolyline().setDraggable(_draggable);
  },
  editable: function editable(_editable, component) {
    component.getPolyline().setEditable(_editable);
  },
  options: function options(_options, component) {
    component.getPolyline().setOptions(_options);
  },
  path: function path(_path, component) {
    component.getPolyline().setPath(_path);
  },
  visible: function visible(_visible, component) {
    component.getPolyline().setVisible(_visible);
  }
};

var _eventHandlerCreator = (0, _eventHandlerCreator3.default)(_PolylineEventList2.default),
    eventPropTypes = _eventHandlerCreator.eventPropTypes,
    registerEvents = _eventHandlerCreator.registerEvents;

var polylineEventPropTypes = exports.polylineEventPropTypes = eventPropTypes;

var PolylineCreator = function (_Component) {
  (0, _inherits3.default)(PolylineCreator, _Component);

  function PolylineCreator() {
    (0, _classCallCheck3.default)(this, PolylineCreator);
    return (0, _possibleConstructorReturn3.default)(this, (PolylineCreator.__proto__ || (0, _getPrototypeOf2.default)(PolylineCreator)).apply(this, arguments));
  }

  (0, _createClass3.default)(PolylineCreator, [{
    key: "getPolyline",
    value: function getPolyline() {
      return this.props.polyline;
    }
  }, {
    key: "render",
    value: function render() {
      return _react2.default.createElement("noscript", null);
    }
  }], [{
    key: "_createPolyline",
    value: function _createPolyline(polylineProps) {
      var mapHolderRef = polylineProps.mapHolderRef;
      // https://developers.google.com/maps/documentation/javascript/3.exp/reference#Polyline

      var polyline = new google.maps.Polyline((0, _composeOptions2.default)(polylineProps, polylineControlledPropTypes));

      polyline.setMap(mapHolderRef.getMap());

      return polyline;
    }
  }]);
  return PolylineCreator;
}(_react.Component);

PolylineCreator.propTypes = {
  polyline: _react.PropTypes.object.isRequired
};
exports.default = (0, _componentLifecycleDecorator2.default)({
  registerEvents: registerEvents,
  instanceMethodName: "getPolyline",
  updaters: polylineUpdaters
})(PolylineCreator);


text:
def test_types(plan_runner):
    _disks = '''[{
    name = "data1"
    size = "10"
    source_type = "image"
    source = "image-1"
    options = null
  }, {
    name = "data2"
    size = "20"
    source_type = "snapshot"
    source = "snapshot-2"
    options = null
  }, {
    name = "data3"
    size = null
    source_type = "attach"
    source = "disk-3"
    options = null
  }]
  '''
    _, resources = plan_runner(attached_disks=_disks)
    assert len(resources) == 3
    disks = {
        r['values']['name']: r['values']
        for r in resources if r['type'] == 'google_compute_disk'
    }
    assert disks['test-data1']['size'] == 10
    assert disks['test-data2']['size'] == 20
    assert disks['test-data1']['image'] == 'image-1'
    assert disks['test-data1']['snapshot'] is None
    assert disks['test-data2']['snapshot'] == 'snapshot-2'
    assert disks['test-data2']['image'] is None
    instance = [
        r['values'] for r in resources
        if r['type'] == 'google_compute_instance'
    ][0]
    instance_disks = {
        d['source']: d['device_name']
        for d in instance['attached_disk']
    }
    assert instance_disks == {
        'test-data1': 'data1',
        'test-data2': 'data2',
        'disk-3': 'data3'
    }

def test_options(plan_runner):
    _disks = '''[{
    name = "data1"
    size = "10"
    source_type = "image"
    source = "image-1"
    options = {
      mode = null, replica_zone = null, type = "pd-standard"
    }
  }, {
    name = "data2"
    size = "20"
    source_type = null
    source = null
    options = {
      mode = null, replica_zone = "europe-west1-c", type = "pd-ssd"
    }
  }]
  '''
    _, resources = plan_runner(attached_disks=_disks)
    assert len(resources) == 3
    disks_z = [
        r['values'] for r in resources if r['type'] == 'google_compute_disk'
    ]
    disks_r = [
        r['values'] for r in resources
        if r['type'] == 'google_compute_region_disk'
    ]
    assert len(disks_z) == len(disks_r) == 1
    instance = [
        r['values'] for r in resources
        if r['type'] == 'google_compute_instance'
    ][0]
    instance_disks = [d['device_name'] for d in instance['attached_disk']]
    assert instance_disks == ['data1', 'data2']

def test_template(plan_runner):
    _disks = '''[{
    name = "data1"
    size = "10"
    source_type = "image"
    source = "image-1"
    options = {
      mode = null, replica_zone = null, type = "pd-standard"
    }
  }, {
    name = "data2"
    size = "20"
    source_type = null
    source = null
    options = {
      mode = null, replica_zone = "europe-west1-c", type = "pd-ssd"
    }
  }]
  '''
    _, resources = plan_runner(attached_disks=_disks, create_template="true")
    assert len(resources) == 1
    template = [
        r['values'] for r in resources
        if r['type'] == 'google_compute_instance_template'
    ][0]
    assert len(template['disk']) == 3

def test_auto_delete(plan_runner):
    _disks = '''[{
    name = "data1"
    size = "10"
    options = {
      auto_delete = true, mode = "READ_WRITE"
    }
  }, {
    name = "data2"
    size = "20"
    options = {
      auto_delete = false, mode = "READ_WRITE"
    },
  }, {
    name = "data3"
    size = "20"
    options = {
      mode = "READ_ONLY"
    }
  }]
  '''
    _, resources = plan_runner(attached_disks=_disks, create_template="true")
    assert len(resources) == 1
    template = [
        r['values'] for r in resources
        if r['type'] == 'google_compute_instance_template'
    ][0]
    additional_disks = [
        d for d in template['disk'] if 'boot' not in d or d['boot'] != True
    ]
    assert len(additional_disks) == 3
    disk_data1 = [d for d in additional_disks if d['disk_name'] == 'data1']
    disk_data2 = [d for d in additional_disks if d['disk_name'] == 'data2']
    disk_data3 = [d for d in additional_disks if d['disk_name'] == 'data3']
    assert len(disk_data1) == 1 and disk_data1[0]['auto_delete'] == True
    assert len(disk_data2) == 1 and disk_data2[0]['auto_delete'] == False
    assert len(disk_data3) == 1 and disk_data3[0]['auto_delete'] == False


text:
@interface MockWebServerManager() {
    NSInteger	activeThread;
    NSCondition	*waitForThread;
    BOOL        isListening;
    BOOL        isStopped;
    int         listenfd;
    int         listeningPort;
}

- (void)startServer:(int)port;
- (void)stopServer;
- (void)startLocalServerManager;
- (void)exitConnThread:(id)thread;

- (void)setDispatch:(DispatchMap*)dispatch;

@end

@implementation MockWebServerManager

@synthesize dispatchMap;

- (id)init
{
	if ((self = [super init])) {
		waitForThread = [[NSCondition alloc] init];
		activeThread = 0;
        isListening = false;
//        self.requestHeaders = [[NSMutableDictionary alloc] init];
	}

	return self;
}

- (void)startServer:(int)port
{
    self->listeningPort = port;
    [self start];

    [waitForThread lock];
    while (isListening == false && isStopped == NO) {
        TRACE("%s, waiting for listening thread.\n", __func__);
        [waitForThread wait];
    }
    [waitForThread unlock];
    TRACE("%s, exit wait.", __func__);
}

- (void)startLocalServerManager
{
	int connfd=-1;
	struct sockaddr_in cliaddr, servaddr;
	unsigned int clilen = 0;
	int optval = 1;
	int onoff = 0;
	BOOL get_new_socket = NO;

	//TRACE("%s, ttl: %d\n", __func__, ttl);

    self->listenfd = -1;
    self->isStopped = NO;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(self->listeningPort);
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
    if (bind(listenfd, (const struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        NSLog(@"%s: bind error=%s", __func__, strerror(errno));

        isStopped = YES;
        return;
    }

    if (listen(listenfd, LISTENQ) < 0) {
        NSLog(@"%s: listen error=%s", __func__, strerror(errno));

        isStopped = YES;

        return;
    }

    [waitForThread lock];
    isListening = true;
    [waitForThread broadcast];
    [waitForThread unlock];

    do {
        @try {

            TRACE("~~~~ before accept ~~~~~~\n");
            if ((connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen)) < 0) {
                if (errno == EINTR)
                    continue;
                else {
                    NSLog(@"%s, accept error: %s", __func__, strerror(errno));
                    get_new_socket = YES;
                    continue;
                }
            }

            TRACE("MockServerManager, accepting connection: %d from listening %d\n", connfd, listenfd);
            //setsockopt(connfd, SOL_SOCKET, SO_LINGER, &l_onoff, sizeof(l_onoff));
            if (setsockopt(connfd, IPPROTO_TCP, TCP_NODELAY, &onoff, sizeof(onoff)) < 0) {
                NSLog(@"%s, failed to set nodelay. %s", __func__, strerror(errno));
            }

            MockServer *server = [[MockServer alloc] initWithManager:self connFD:connfd];
            TRACE("Starting thread: %p\n", server);
            [server start];

            if (++activeThread >= MAX_LOCAL_SERVER_THREAD) {
                [waitForThread lock];
                TRACE("%s, waiting for available thread.\n", __func__);
                [waitForThread wait];
                [waitForThread unlock];
                TRACE("%s, thread is available.\n", __func__);
            }

        } @catch (NSException *exception) {
            NSLog(@"%s: main: %@: %@", __func__, [exception name], [exception reason]);
        }
    } while (get_new_socket == NO && self->isStopped == NO);

    if (self->isStopped == YES) {
        TRACE("Listening thread exiting.\n");
        return;
    }
    shutdown(listenfd, SHUT_RDWR);
    close(listenfd);
    NSLog(@"Close %d socket.\n", listenfd);
    get_new_socket = NO;

}

- (void)stopServer
{
    shutdown(self->listenfd, SHUT_RDWR);
    close(self->listenfd);
    self->dispatchMap = nil;

    TRACE("%s=%d", __func__, self->listenfd);
}

- (void)exitConnThread:(id)thread
{
    --activeThread;
	[waitForThread signal];
    TRACE("%s, id: %p, n=%d\n", __func__, thread, activeThread);
}

- (void)main
{
	[self startLocalServerManager];

}

- (void)setDispatch:(DispatchMap*)dispatch
{
    self->dispatchMap = dispatch;
}

@end

@interface MockWebServer()

@property(nonatomic, retain)    MockWebServerManager    *mockServerManager;
@end

@implementation MockWebServer
@synthesize mockServerManager;

- (id)init
{
    if ((self = [super init])) {
        self.mockServerManager = [[MockWebServerManager alloc] init];
    }

    return self;
}

- (void)start:(int)port
{
    [self.mockServerManager startServer:port];
}

- (void)stop
{
    [self.mockServerManager stopServer];
}

- (void)setDispatch:(DispatchMap *)dispatch
{
    [self.mockServerManager setDispatch:dispatch];
}

@end


text:
import devTools from "remote-redux-devtools"

export default () => devTools({
  port: 7001
})


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

using Foundation;
using UIKit;

using Glympse;
using Glympse.EnRoute;
using Glympse.EnRoute.iOS;

namespace EnRouteDemo.iOS
{
    [Register ("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public const bool IS_ENROUTE_MODE = true;

        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init ();

            if (IS_ENROUTE_MODE)
            {
                GEnRouteFactory enRouteFactory = new EnRouteFactory();
                LoadApplication(new App(enRouteFactory));

                // Register for a Push notification token
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                                       UIUserNotificationType.Alert | UIUserNotificationType.Badge |
                                       UIUserNotificationType.Sound,
                                       new NSSet());

                    UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
                    UIApplication.SharedApplication.RegisterForRemoteNotifications();
                }
                else
                {
                    UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert |
                    UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
                    UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
                }
            }
            else
            {
                GGlympseFactory glympseFactory = new GlympseFactory();
                LoadApplication(new App(glympseFactory));
            }

            return base.FinishedLaunching (app, options);
        }

        public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
        {
            // Get current device token
            byte[] bytes = deviceToken.ToArray<byte>();
            string[] hexArray = bytes.Select(b => b.ToString("x2")).ToArray();
            var DeviceToken = string.Join(string.Empty, hexArray);

            Debug.WriteLine(DeviceToken);

            // Get previous device token
            var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

            // Has the token changed?
            if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
            {
                Debug.WriteLine("Sharing device token with EnRoute platform");
                if (IS_ENROUTE_MODE)
                {
                    EnRouteManagerWrapper.Instance.Manager.registerDeviceToken("apple_background", DeviceToken);
                }
            }

            // Save new device token
            NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");
        }

        public override void FailedToRegisterForRemoteNotifications (UIApplication application , NSError error)
        {
            Debug.WriteLine("FailedToRegisterForRemoteNotifications()");
        }

        public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
        {
            Debug.WriteLine("ReceivedRemoteNotification:" + userInfo.Description);
            if (IS_ENROUTE_MODE)
            {
                EnRouteManagerWrapper.Instance.Manager.handleRemoteNotification(userInfo.Description);
            }
        }

        public override void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo,
            Action<UIBackgroundFetchResult> completionHandler)
        {
            Debug.WriteLine("DidReceiveRemoteNotification:" + userInfo.Description);
            if (IS_ENROUTE_MODE)
            {
                EnRouteManagerWrapper.Instance.Manager.handleRemoteNotification(userInfo.Description);
            }
            completionHandler(UIBackgroundFetchResult.NewData);
        }
    }
}