text:
import logging
from os.path import expanduser, isfile

import subprocess32

LOG = logging.getLogger("simdeplower")

class OvfHelper(object):

    def __init__(self, ovftool_path=None):
        """
        Constructor

        :param ovftool_path:
        :return:
        """
        if ovftool_path is None:

            LOG.info("No ovftool_path set. Attempting to locate ovftool on file system.")
            # try the location of the tool on osx
            if isfile(expanduser("/Applications/VMware OVF Tool/ovftool")):
                ovftool_path = expanduser("/Applications/VMware OVF Tool/ovftool")
            elif isfile(expanduser("/Applications/VMware Fusion.app/Contents/Library/VMware OVF Tool/ovftool")):
                ovftool_path = expanduser("/Applications/VMware Fusion.app/Contents/Library/VMware OVF Tool/ovftool")
            else:
                raise ValueError("ovftool_path required to continue.")
            # default fusion here for osx
            # even though this is a valid path for linux or any other unix
            # its doubtful someone would do such a horrible thing..
            LOG.info("Using {0}".format(ovftool_path))
        elif not isfile(expanduser(ovftool_path)):
            raise ValueError("ovftool not found at specified location.")

        self.ovftool_path = ovftool_path

    def extract_ovf_to_file_system(self, source=None, dest=None, name=None):
        """
        Extract an OVA to a given destination, and return full path to vmx

        vmx_path = extract_ovf_to_file_system("/tmp/myvcsa.ova", "/home/me/vms/")

        :param source:
        :param dest:
        :return:
        """
        if source is None or dest is None:
            raise ValueError("Missing source or dest argument")
        source = expanduser(source)
        if not isfile(source):
            raise ValueError("Invalid source location supplied. File not found.")
        dest = expanduser(dest)
        output = subprocess32.check_output(
            [
                self.ovftool_path,
                "--name={0}".format(name),
                source,
                dest
            ],
            universal_newlines=True
        )
        output = output.split("\n")
        # pattern to look for to match from above output
        mat = "Writing VMX file"
        output = (s for s in output if mat in s)
        val = next(output)
        output = val.split(":")[-1]
        LOG.debug(output)
        del val
        return output.strip()


text:
import React, { useState, useRef, ForwardedRef, MouseEvent, useCallback } from "react"
import { useCombobox, useMultipleSelection } from "downshift"
import { MdExpandMore, MdClose } from "react-icons/md"

import { chakra, omitThemingProps, SystemStyleObject, ThemingProps, useMultiStyleConfig } from "~/system"
import { __DEV__ } from "~/utils"
import { InputCore, InputError } from "~/components/Input"
import { Label } from "~/components/Input"
import { useFormControl, UseFormControlProps } from "~/form-control"
import { Icon } from "~/icon"
import { usePopper, UsePopperProps } from "~/popper"
import { mergeRefs } from "~/react-utils"
import { Dropdown } from "./Dropdown"
import { Tags } from "./Tags"

export type MultiselectProps<T, K extends keyof T = keyof T> = ThemingProps<"Multiselect"> &
  Omit<UseFormControlProps<HTMLInputElement>, "isInvalid" | "isReadOnly"> & {
    placeholder?: string
    options: T[]
    value: T[K][]
    label?: string
    error?: string
    onChange: (value: T[K][]) => void
    getOptionLabel?: (option: T | null) => string
    valueKey?: K
    noOptionsPlaceholder?: string
    placement?: UsePopperProps["placement"]
  }

const itemToString = <T extends { label?: string; id?: string }>(item: T | null) => item?.label ?? ""

export const Multiselect = React.forwardRef(
  <T extends { label?: string; id?: string }>(props: MultiselectProps<T>, ref: ForwardedRef<any>) => {
    const {
      value = [],
      options: items,
      onChange,
      label,
      error,
      valueKey = "id",
      placement = "bottom-start",
      getOptionLabel = itemToString,
      noOptionsPlaceholder,
      disabled,
      ...rest
    } = omitThemingProps(props)

    const styles = useMultiStyleConfig("Multiselect", props)
    const ownProps = useFormControl<HTMLInputElement>({ ...rest, disabled })
    const [inputItems, setInputItems] = useState(items)

    const selectedItems = items.filter((item) => value.includes(item[valueKey]))
    const { getSelectedItemProps, addSelectedItem, removeSelectedItem, reset, getDropdownProps } = useMultipleSelection(
      {
        onSelectedItemsChange: ({ selectedItems }) => {
          if (selectedItems) {
            onChange?.(selectedItems.map((item) => (item as any)[valueKey]))
          }
        },
        selectedItems,
        stateReducer: (_, actionAndChanges) => {
          const { type, changes } = actionAndChanges
          switch (type) {
            case useMultipleSelection.stateChangeTypes.FunctionRemoveSelectedItem:
              return {
                ...changes,
                activeIndex: undefined,
              }
            default:
              return changes
          }
        },
      },
    )

    const {
      isOpen,
      getLabelProps,
      getMenuProps,
      getInputProps,
      getComboboxProps,
      highlightedIndex,
      getItemProps,
      openMenu,
    } = useCombobox({
      selectedItem: null,
      items: inputItems,
      onInputValueChange: ({ inputValue }) => {
        const filteredItems = items.filter((item) =>
          getOptionLabel(item)
            .toLowerCase()
            .startsWith(inputValue?.toLowerCase() || ""),
        )

        setInputItems(filteredItems)
      },
      stateReducer: (state, actionAndChanges) => {
        const { changes, type } = actionAndChanges
        switch (type) {
          case useCombobox.stateChangeTypes.InputBlur:
            return {
              ...changes,
              highlightedIndex: state.highlightedIndex,
              inputValue: "",
            }
          case useCombobox.stateChangeTypes.InputKeyDownEnter:
          case useCombobox.stateChangeTypes.ItemClick:
            return {
              ...changes,
              highlightedIndex: state.highlightedIndex,
              isOpen: true,
              inputValue: "",
            }
          case useCombobox.stateChangeTypes.FunctionOpenMenu:
            return {
              ...changes,
              isOpen: !ownProps.disabled,
            }
          default:
            return changes
        }
      },
      onStateChange: ({ type, selectedItem }) => {
        switch (type) {
          case useCombobox.stateChangeTypes.InputKeyDownEnter:
          case useCombobox.stateChangeTypes.ItemClick:
            if (selectedItem) {
              if (value?.includes(selectedItem[valueKey])) {
                removeSelectedItem(selectedItem)
              } else {
                addSelectedItem(selectedItem)
              }
            }
            break
          default:
            break
        }
      },
    })

    const { ref: comboboxPropsRef, ...comboboxProps } = getComboboxProps()
    const { ref: downshiftInputRef, ...inputProps } = getInputProps(
      getDropdownProps({
        onClick: isOpen ? () => {} : openMenu,
      }),
    )
    const { popperRef, referenceRef } = usePopper({
      placement,
      matchWidth: true,
    })
    const inputFocusRef = useRef<HTMLInputElement>(null)
    const inputWrapperRef = mergeRefs(comboboxPropsRef, referenceRef)
    const inputRef = mergeRefs(downshiftInputRef, inputFocusRef)

    const focusInput = useCallback(() => inputFocusRef.current?.focus(), [inputFocusRef])
    const handleMouseDown = useCallback((e: MouseEvent) => e.preventDefault(), [])
    const handleInputWrapperClick = useCallback(() => {
      if (ownProps.disabled) {
        return
      }
      focusInput()
      if (!isOpen) {
        openMenu()
      }
    }, [isOpen, openMenu, focusInput, ownProps.disabled])
    const handleTagClose = useCallback(
      (e: MouseEvent, item: T) => {
        e.stopPropagation()
        removeSelectedItem(item)
      },
      [items, removeSelectedItem],
    )
    const handleClearMultiselect = useCallback(
      (e: MouseEvent) => {
        e.stopPropagation()
        if (ownProps.disabled) {
          return
        }
        reset()
        focusInput()
      },
      [reset, focusInput, ownProps.disabled],
    )

    const rootStyles: SystemStyleObject = {
      width: "100%",
      height: "fit-content",
      position: "relative",
    }

    return (
      <chakra.div __css={rootStyles}>
        <Label text={label || ""} isRequired={ownProps.required} {...getLabelProps()} />
        <chakra.div
          __css={styles.field}
          {...comboboxProps}
          ref={inputWrapperRef}
          aria-invalid={!!error}
          onClick={handleInputWrapperClick}
          disabled={ownProps.disabled}
        >
          <Tags
            items={selectedItems}
            getSelectedItemProps={getSelectedItemProps}
            getOptionLabel={getOptionLabel}
            isDisabled={ownProps.disabled}
            onMouseDown={handleMouseDown}
            onTagClose={handleTagClose}
          />
          <InputCore {...ownProps} variant="unstyled" __css={styles.input} {...inputProps} ref={inputRef} />
          <chakra.div __css={styles.iconBox}>
            <Icon
              as={MdClose}
              __css={styles.clearIcon}
              onMouseDown={handleMouseDown}
              onClick={handleClearMultiselect}
              isDisabled={ownProps.disabled}
              title="Clear"
            />
            <Icon as={MdExpandMore} __css={styles.selectIcon} isDisabled={ownProps.disabled} title="Expand" />
          </chakra.div>
        </chakra.div>
        <InputError error={error} />
        <Dropdown
          items={inputItems}
          isOpen={isOpen}
          highlightedIndex={highlightedIndex}
          getOptionLabel={getOptionLabel}
          onMouseDown={handleMouseDown}
          getMenuProps={getMenuProps}
          valueKey={valueKey}
          popperRef={popperRef}
          getItemProps={getItemProps}
          noOptionsPlaceholder={noOptionsPlaceholder}
          value={value}
        />
      </chakra.div>
    )
  },
)

if (__DEV__) {
  Multiselect.displayName = "Multiselect"
}

redpajama_set_name: RedPajamaGithub


text:
package com.randal.aviana.database;

import android.content.Context;

import java.util.List;

public class SQLiteUtils {
    public static KeyValueTable
    createOrOpenKeyValueTable(Context context, String dbName, String tableName) {
        return new KeyValueTable(context, dbName, tableName);
    }

    public static TextTable
    createOrOpenTextTable(Context context, String dbName, String tableName,
                    String[] columnTitles,
                    List<String[]> columnValues) {
        return new TextTable(context, dbName, tableName,
                columnTitles, columnValues);
    }
}


text:
This repo contains a boilerplate Angular2 project used by ArchitectNow to kickstart specific client projects.  This code is also used in various presentations and demonstrations.

# Prerequisites
- [Node](https://nodejs.org/en/download/current/) (version >= 6)

# How to Install
```bash
# Note: If on windows, open command line as administrator
# Clone this repo
git clone --depth=1 https://github.com/ArchitectNow/ArchitectNow.Boilerplate.Angular2
# Navigate to the frontend folder contaning the `package.json`
cd ArchitectNow.Boilerplate.Angular2/src/ArchitectNow.Boilerplate.Angular2
# install webpack and other frontend tools via npm
npm install
npm start

# if npm start fails, rebuild the project and try again
npm rebuild
npm start
```

# How to Rename Project (windows only)
1. Navigate to scripts folder
2. Run PrepareProject.bat
3. Enter the desired namespace
4. Delete the scripts folder

# TODO:
 - add bash option for renaming project


text:
package org.sourcepit.common.manifest.osgi.impl;

import java.util.Collection;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.util.EDataTypeUniqueEList;
import org.sourcepit.common.manifest.osgi.BundleManifestPackage;
import org.sourcepit.common.manifest.osgi.ClassPathEntry;

/**
 *
 * An implementation of the model object 'Class Path Entry'.
 *
 *

 * The following features are implemented:
 *

 *
{@link org.sourcepit.common.manifest.osgi.impl.ClassPathEntryImpl#getPaths Paths}

 *

 *

 *
 * @generated
 */
public class ClassPathEntryImpl extends ParameterizedImpl implements ClassPathEntry {
   /**
    * The cached value of the '{@link #getPaths() Paths}' attribute list.
    *
    *
    *
    * @see #getPaths()
    * @generated
    * @ordered
    */
   protected EList<String> paths;

   /**
    *
    *
    *
    * @generated
    */
   protected ClassPathEntryImpl() {
      super();
   }

   /**
    *
    *
    *
    * @generated
    */
   @Override
   protected EClass eStaticClass() {
      return BundleManifestPackage.Literals.CLASS_PATH_ENTRY;
   }

   /**
    *
    *
    *
    * @generated
    */
   public EList<String> getPaths() {
      if (paths == null) {
         paths = new EDataTypeUniqueEList<String>(String.class, this, BundleManifestPackage.CLASS_PATH_ENTRY__PATHS);
      }
      return paths;
   }

   /**
    *
    *
    *
    * @generated
    */
   @Override
   public Object eGet(int featureID, boolean resolve, boolean coreType) {
      switch (featureID) {
         case BundleManifestPackage.CLASS_PATH_ENTRY__PATHS :
            return getPaths();
      }
      return super.eGet(featureID, resolve, coreType);
   }

   /**
    *
    *
    *
    * @generated
    */
   @SuppressWarnings("unchecked")
   @Override
   public void eSet(int featureID, Object newValue) {
      switch (featureID) {
         case BundleManifestPackage.CLASS_PATH_ENTRY__PATHS :
            getPaths().clear();
            getPaths().addAll((Collection<? extends String>) newValue);
            return;
      }
      super.eSet(featureID, newValue);
   }

   /**
    *
    *
    *
    * @generated
    */
   @Override
   public void eUnset(int featureID) {
      switch (featureID) {
         case BundleManifestPackage.CLASS_PATH_ENTRY__PATHS :
            getPaths().clear();
            return;
      }
      super.eUnset(featureID);
   }

   /**
    *
    *
    *
    * @generated
    */
   @Override
   public boolean eIsSet(int featureID) {
      switch (featureID) {
         case BundleManifestPackage.CLASS_PATH_ENTRY__PATHS :
            return paths != null && !paths.isEmpty();
      }
      return super.eIsSet(featureID);
   }

   /**
    *
    *
    *
    * @generated
    */
   @Override
   public String toString() {
      if (eIsProxy())
         return super.toString();

      StringBuffer result = new StringBuffer(super.toString());
      result.append(" (paths: ");
      result.append(paths);
      result.append(')');
      return result.toString();
   }

} // ClassPathEntryImpl


text:
+---------------------------+
| layout: page              |
+---------------------------+
| title: User (llvm.core)   |
+---------------------------+

``User``-s are values that refer to other values. The values so refered
can be retrived by the properties of ``User``. This is the reverse of
the ``Value.uses``. Together these can be used to traverse the use-def
chains of the SSA.

--------------

llvm.core.User # {#user}
========================

Base Class
----------

-  `llvm.core.Value <llvm.core.Value.html>`_

Properties
----------

``operands``
~~~~~~~~~~~~

[read-only]

The list of operands (values, of type
`llvm.core.Value <llvm.core.Value.html>`_) that this value refers to.

``operand_count``
~~~~~~~~~~~~~~~~~

[read-only]

The number of operands that this value referes to. Same as
``len(uses.operands)`` but faster if you just want the count.


text:
namespace blink {

void NGLineBoxFragmentBuilder::Reset() {
  children_.Shrink(0);
  child_break_tokens_.Shrink(0);
  last_inline_break_token_ = nullptr;
  oof_positioned_candidates_.Shrink(0);
  unpositioned_list_marker_ = NGUnpositionedListMarker();

  annotation_overflow_ = LayoutUnit();
  bfc_block_offset_.reset();
  line_box_bfc_block_offset_.reset();
  is_pushed_by_floats_ = false;
  subtree_modified_margin_strut_ = false;

  size_.inline_size = LayoutUnit();
  metrics_ = FontHeight::Empty();
  line_box_type_ = NGPhysicalLineBoxFragment::kNormalLineBox;

  has_floating_descendants_for_paint_ = false;
  has_descendant_that_depends_on_percentage_block_size_ = false;
  has_block_fragmentation_ = false;
}

void NGLineBoxFragmentBuilder::SetIsEmptyLineBox() {
  line_box_type_ = NGPhysicalLineBoxFragment::kEmptyLineBox;
}

void NGLineBoxFragmentBuilder::PropagateChildrenData(
    NGLogicalLineItems& children) {
  for (unsigned index = 0; index < children.size(); ++index) {
    auto& child = children[index];
    if (child.layout_result) {
      // An accumulated relative offset is applied to an OOF once it reaches its
      // inline container. Subtract out the relative offset to avoid adding it
      // twice.
      PropagateChildData(
          child.layout_result->PhysicalFragment(),
          child.Offset() -
              ComputeRelativeOffsetForInline(ConstraintSpace(),
                                             child.PhysicalFragment()->Style()),
          ComputeRelativeOffsetForOOFInInline(
              ConstraintSpace(), child.PhysicalFragment()->Style()));

      // Skip over any children, the information should have already been
      // propagated into this layout result.
      if (child.children_count)
        index += child.children_count - 1;

      continue;
    }
    if (child.out_of_flow_positioned_box) {
      AddOutOfFlowInlineChildCandidate(
          NGBlockNode(To<LayoutBox>(child.out_of_flow_positioned_box.Get())),
          child.Offset(), child.container_direction);
      child.out_of_flow_positioned_box = nullptr;
    }
  }

  DCHECK(oof_positioned_descendants_.IsEmpty());
  MoveOutOfFlowDescendantCandidatesToDescendants();
}

const NGLayoutResult* NGLineBoxFragmentBuilder::ToLineBoxFragment() {
  writing_direction_.SetWritingMode(ToLineWritingMode(GetWritingMode()));

  const NGPhysicalLineBoxFragment* fragment =
      NGPhysicalLineBoxFragment::Create(this);

  return MakeGarbageCollected<NGLayoutResult>(
      NGLayoutResult::NGLineBoxFragmentBuilderPassKey(), std::move(fragment),
      this);
}

}  // namespace blink


text:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfLastAction xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Kooboo.CMS.Search.Models">
	<LastAction>
		<FolderName>Article</FolderName>
		<ContentSummary>Lorem ipsum dolor sit amet</ContentSummary>
		<Action>Update</Action>
		<UtcActionDate>2013-08-22T06:39:46.1466756Z</UtcActionDate>
	</LastAction>
	<LastAction>
		<FolderName>Article</FolderName>
		<ContentSummary>Lorem ipsum dolor sit amet</ContentSummary>
		<Action>Update</Action>
		<UtcActionDate>2013-08-14T03:32:36.786789Z</UtcActionDate>
	</LastAction>
	<LastAction>
		<FolderName>Article</FolderName>
		<ContentSummary>Lorem ipsum dolor sit amet</ContentSummary>
		<Action>Update</Action>
		<UtcActionDate>2013-08-14T03:31:12.8801538Z</UtcActionDate>
	</LastAction>
	<LastAction>
		<FolderName>Article</FolderName>
		<ContentSummary>Lorem ipsum dolor sit amet</ContentSummary>
		<Action>Update</Action>
		<UtcActionDate>2013-08-13T10:05:39.1354009Z</UtcActionDate>
	</LastAction>
	<LastAction>
		<FolderName>Article</FolderName>
		<ContentSummary>Lorem ipsum dolor sit amet 4</ContentSummary>
		<Action>Update</Action>
		<UtcActionDate>2013-01-31T03:20:15.3253781Z</UtcActionDate>
	</LastAction>
</ArrayOfLastAction>


text:
/*
 *	Variables and functions used by the code in sleep.c
 */

#include <asm/trampoline.h>

extern char wakeup_code_start, wakeup_code_end;

extern unsigned long saved_video_mode;
extern long saved_magic;

extern int wakeup_pmode_return;
extern char swsusp_pg_dir[PAGE_SIZE];

extern unsigned long acpi_copy_wakeup_routine(unsigned long);
extern void wakeup_long64(void);


text:
package org.axonframework.commandhandling.distributed;

import org.axonframework.commandhandling.CommandMessage;
import org.axonframework.commandhandling.GenericCommandMessage;
import org.axonframework.commandhandling.annotation.TargetAggregateIdentifier;
import org.junit.*;

import static org.junit.Assert.*;

/**
 * @author Allard Buijze
 */
public class AnnotationRoutingStrategyTest {

    private AnnotationRoutingStrategy testSubject;

    @Before
    public void setUp() throws Exception {
        this.testSubject = new AnnotationRoutingStrategy();
    }

    @Test
    public void testGetRoutingKey() throws Exception {
        String actual = testSubject.getRoutingKey(new GenericCommandMessage<Object>(new StubCommand("SomeIdentifier")));
        assertEquals("SomeIdentifier", actual);
    }

    @Test(expected = CommandDispatchException.class)
    public void testGetRoutingKey_NullKey() throws Exception {
        assertNull(testSubject.getRoutingKey(new GenericCommandMessage<Object>(new StubCommand(null))));
    }

    @Test(expected = CommandDispatchException.class)
    public void testGetRoutingKey_NoKey() throws Exception {
        assertNull(testSubject.getRoutingKey(new GenericCommandMessage<Object>("Just a String")));
    }

    @Test
    public void testGetRoutingKey_NullValueWithStaticPolicy() throws Exception {
        testSubject = new AnnotationRoutingStrategy(UnresolvedRoutingKeyPolicy.STATIC_KEY);
        CommandMessage<Object> command = new GenericCommandMessage<Object>(new Object());
        // two calls should provide the same result
        assertEquals(testSubject.getRoutingKey(command), testSubject.getRoutingKey(command));
    }

    @Test
    public void testGetRoutingKey_NullValueWithRandomPolicy() throws Exception {
        testSubject = new AnnotationRoutingStrategy(UnresolvedRoutingKeyPolicy.RANDOM_KEY);
        CommandMessage<Object> command = new GenericCommandMessage<Object>(new Object());
        // two calls should provide the same result
        assertFalse(testSubject.getRoutingKey(command).equals(testSubject.getRoutingKey(command)));
    }

    public static class StubCommand {

        @TargetAggregateIdentifier
        private String identifier;

        public StubCommand(String identifier) {
            this.identifier = identifier;
        }

        public String getIdentifier() {
            return identifier;
        }
    }
}


text:
const Mysql = require('mysql');
const Promise = require('promise');
const Helper = require('../utils/helper');

const config = require('../../../../config');

let instance = null;

class DataBaseConnector {
    constructor() {
        if (!instance) {
            instance = this;
        }

        return instance;
    }

    setup() {
        if (this.connection) {
            this.connection.end();
        }

        this.connection = Mysql.createConnection({
            host     : 'localhost',
            user     : 'root',
            password : 'root',
            database : config.DATABASE_NAME
        });

        return new Promise((resolve, reject) => {
            this.connection.connect(err => {
                if (err) {
                    reject(err);
                    return;
                }

                resolve();
            });
            console.log('Database Connection OK!');
        });
    }

    insert(table, data) {
        let columnsString = '(';
        let valuesString = '(';

        for (let key in data) {
            if (data.hasOwnProperty(key)) {
                columnsString += '`' + key + '`, ';
                valuesString += '\'' + data[key] + '\', ';
            }
        }

        columnsString = columnsString.replace(/,\s*$/, "").trim();
        valuesString = valuesString.replace(/,\s*$/, "").trim();

        columnsString += ')';
        valuesString += ')';

        return this._query('INSERT INTO `' + table + '` ' + columnsString + ' VALUES ' + valuesString + ';');
    }

    update(table, data, conditions) {
        let valuesString = '';
        let conditionsString;

        for (let key in data) {
            if (data.hasOwnProperty(key)) {
                valuesString += key + '=\'' + data[key] + '\', ';
            }
        }

        valuesString = valuesString.replace(/,\s*$/, "");
        conditionsString = this._getConditionsString(conditions);

        return this._query('UPDATE ' + table + ' SET ' + valuesString + ' WHERE ' + conditionsString + ';');
    }

    find(table, columns, conditions) {
        let columnArray = Helper.makeArray(columns);
        let conditionsString;

        conditionsString = this._getConditionsString(conditions);

        return this._query('SELECT ' + columnArray.join(', ') + ' FROM `' + table + '` WHERE ' + conditionsString + ';');
    }

    remove(table, conditions) {
        var conditionsString;

        conditionsString = this._getConditionsString(conditions);

        return this._query('DELETE FROM ' + table + ' WHERE ' + conditionsString + ';');
    }

    _getConditionsString(conditions) {
        let conditionsString = '';
        let conditionIndex = 0;
        let conditionsLogic = conditions._matchAll ? 'AND' : 'OR';

        delete conditions._matchAll;

        for (let condition in conditions) {
            if (conditions.hasOwnProperty(condition)) {
                if (conditionIndex > 0) {
                    conditionsString += ' ' + conditionsLogic + ' ';
                }
                conditionIndex += 1;
                conditionsString += condition;

                if (conditions[condition].toString().indexOf('*') > -1) {
                    conditions[condition].replace(/\*/gi, '%');
                    conditionsString += ' LIKE \'' + conditions[condition] + '\'';
                } else {
                    conditionsString += '=\'' + conditions[condition] + '\'';
                }
            }
        }

        return conditionsString;
    }

    _query(queryString) {
        return new Promise((resolve, reject) => {
            this.connection.query(queryString, (error, rows, fields) => {
                if (error) {
                    reject();
                    throw new Error(error);
                }

                resolve(rows, fields);
            });
        });
    }
}

module.exports = new DataBaseConnector();


text:
@interface NSString (Base64Addition)
+(NSString *)stringFromBase64String:(NSString *)base64String;
+(NSString *)stringFromBase64UrlEncodedString:(NSString *)base64UrlEncodedString;
-(NSString *)base64String;
-(NSString *)base64UrlEncodedString;
@end

@interface NSData (Base64Addition)
+(NSData *)dataWithBase64String:(NSString *)base64String;
+(NSData *)dataWithBase64UrlEncodedString:(NSString *)base64UrlEncodedString;
-(NSString *)base64String;
-(NSString *)base64UrlEncodedString;
@end

@interface MF_Base64Codec : NSObject
+(NSData *)dataFromBase64String:(NSString *)base64String;
+(NSString *)base64StringFromData:(NSData *)data;
+(NSString *)base64UrlEncodedStringFromBase64String:(NSString *)base64String;
+(NSString *)base64StringFromBase64UrlEncodedString:(NSString *)base64UrlEncodedString;
@end


text:
/// <reference path="../_references.ts"/>

module powerbi.visuals {
    export interface ComboChartDataViewObjects extends DataViewObjects {
        general: ComboChartDataViewObject;
    }

    export interface ComboChartDataViewObject extends DataViewObject {
        visualType1: string;
        visualType2: string;
    }

    /**
     * This module only supplies the capabilities for comboCharts.
     * Implementation is in cartesianChart and the various ICartesianVisual implementations.
     */
    export module ComboChart {
        export const capabilities = comboChartCapabilities;

        export function customizeQuery(options: CustomizeQueryOptions): void {
            // If there is a dynamic series but no values on the column data view mapping, remove the dynamic series
            let columnMapping = !_.isEmpty(options.dataViewMappings) && options.dataViewMappings[0];
            if (columnMapping) {
                let columnValuesMapping: data.CompiledDataViewGroupedRoleMapping = columnMapping.categorical && <data.CompiledDataViewGroupedRoleMapping>columnMapping.categorical.values;
                let seriesSelect = columnValuesMapping.group && !_.isEmpty(columnValuesMapping.group.select) && <data.CompiledDataViewRoleForMapping>columnValuesMapping.group.select[0];
                if (_.isEmpty(seriesSelect.for.in.items))
                    columnValuesMapping.group.by.items = undefined;
            }
        }

        export function isComboChart(chartType: CartesianChartType): boolean {
            return chartType === CartesianChartType.ComboChart
                || chartType === CartesianChartType.LineClusteredColumnCombo
                || chartType === CartesianChartType.LineStackedColumnCombo
                || chartType === CartesianChartType.DataDotClusteredColumnCombo
                || chartType === CartesianChartType.DataDotStackedColumnCombo;
        }
    }
}


text:
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Thinktecture.Relay.Server.Security
{
	[TestClass]
	public class PasswordComplexityValidatorTests
	{
		[TestMethod]
		public void ValidatePassword_validates_a_good_password()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("username", "12345678aA!", out var errorMessage);

			result.Should().BeTrue();
			errorMessage.Should().BeNull();
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_username_and_password_match()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("username", "username", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Username and password must not be the same.");
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_password_is_too_short()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("UserName", "1234567", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Password needs to be at least 8 characters long.");
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_password_misses_lowercase_chars()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("UserName", "1AAAAAAA!", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Password must contain at least one lower case character.");
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_password_misses_uppercase_chars()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("UserName", "1aaaaaaa!", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Password must contain at least one upper case character.");
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_password_misses_numerical_chars()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("UserName", "aaaaAAAA!", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Password must contain at least one number.");
		}

		[TestMethod]
		public void ValidatePassword_gives_error_when_password_misses_special_chars()
		{
			var sut = new PasswordComplexityValidator();

			var result = sut.ValidatePassword("UserName", "aaaaAAAA1", out var errorMessage);

			result.Should().BeFalse();
			errorMessage.Should().Contain("Password must contain at least one special character.");
		}
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import subprocess
import sys

import pytest

# test for _argcomplete but not specific for any application

def equal_with_bash(prefix, ffc, fc, out=None):
    res = ffc(prefix)
    res_bash = set(fc(prefix))
    retval = set(res) == res_bash
    if out:
        out.write("equal_with_bash({}) {} {}\n".format(prefix, retval, res))
        if not retval:
            out.write(" python - bash: %s\n" % (set(res) - res_bash))
            out.write(" bash - python: %s\n" % (res_bash - set(res)))
    return retval

# copied from argcomplete.completers as import from there
# also pulls in argcomplete.__init__ which opens filedescriptor 9
# this gives an IOError at the end of testrun

def _wrapcall(*args, **kargs):
    try:
        if sys.version_info > (2, 7):
            return subprocess.check_output(*args, **kargs).decode().splitlines()
        if "stdout" in kargs:
            raise ValueError("stdout argument not allowed, it will be overridden.")
        process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kargs)
        output, unused_err = process.communicate()
        retcode = process.poll()
        if retcode:
            cmd = kargs.get("args")
            if cmd is None:
                cmd = args[0]
            raise subprocess.CalledProcessError(retcode, cmd)
        return output.decode().splitlines()
    except subprocess.CalledProcessError:
        return []

class FilesCompleter(object):
    "File completer class, optionally takes a list of allowed extensions"

    def __init__(self, allowednames=(), directories=True):
        # Fix if someone passes in a string instead of a list
        if type(allowednames) is str:
            allowednames = [allowednames]

        self.allowednames = [x.lstrip("*").lstrip(".") for x in allowednames]
        self.directories = directories

    def __call__(self, prefix, **kwargs):
        completion = []
        if self.allowednames:
            if self.directories:
                files = _wrapcall(
                    ["bash", "-c", "compgen -A directory -- '{p}'".format(p=prefix)]
                )
                completion += [f + "/" for f in files]
            for x in self.allowednames:
                completion += _wrapcall(
                    [
                        "bash",
                        "-c",
                        "compgen -A file -X '!*.{0}' -- '{p}'".format(x, p=prefix),
                    ]
                )
        else:
            completion += _wrapcall(
                ["bash", "-c", "compgen -A file -- '{p}'".format(p=prefix)]
            )

            anticomp = _wrapcall(
                ["bash", "-c", "compgen -A directory -- '{p}'".format(p=prefix)]
            )

            completion = list(set(completion) - set(anticomp))

            if self.directories:
                completion += [f + "/" for f in anticomp]
        return completion

class TestArgComplete(object):
    @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
    def test_compare_with_compgen(self, tmpdir):
        from _pytest._argcomplete import FastFilesCompleter

        ffc = FastFilesCompleter()
        fc = FilesCompleter()

        with tmpdir.as_cwd():
            assert equal_with_bash("", ffc, fc, out=sys.stdout)

            tmpdir.ensure("data")

            for x in ["d", "data", "doesnotexist", ""]:
                assert equal_with_bash(x, ffc, fc, out=sys.stdout)

    @pytest.mark.skipif("sys.platform in ('win32', 'darwin')")
    def test_remove_dir_prefix(self):
        """this is not compatible with compgen but it is with bash itself:
        ls /usr/<TAB>
        """
        from _pytest._argcomplete import FastFilesCompleter

        ffc = FastFilesCompleter()
        fc = FilesCompleter()
        for x in "/usr/".split():
            assert not equal_with_bash(x, ffc, fc, out=sys.stdout)


text:
$LOAD_PATH.unshift File.expand_path("#{File.dirname(__FILE__)}/../lib/")
require 'messagebird'

# ACCESS_KEY = ''
# VERIFY_ID  = ''
# TOKEN      = ''

unless defined?(ACCESS_KEY)
  puts 'You need to set an ACCESS_KEY constant in this file'
  exit 1
end

unless defined?(VERIFY_ID)
  puts 'You need to set an VERIFY_ID constant in this file'
  exit 1
end

unless defined?(TOKEN)
  puts 'You need to set an TOKEN constant in this file'
  exit 1
end

begin
  # Create a MessageBird client with the specified ACCESS_KEY.
  client = MessageBird::Client.new(ACCESS_KEY)

  # Verify an OTP message with a token
  otp = client.verify_token(VERIFY_ID, TOKEN)

  # Print the object information.
  puts
  puts 'The following information was returned as an OTP object:'
  puts
  puts "  id                  : #{otp.id}"
  puts "  href                : #{otp.href}"
  puts "  recipient           : #{otp.recipient}"
  puts "  reference           : #{otp.reference}"
  puts "  messages            : #{otp.messages}"
  puts "  status              : #{otp.status}"
  puts "  createdDatetime     : #{otp.created_datetime}"
  puts "  validUntilDatetime  : #{otp.valid_until_datetime}"
  puts
rescue MessageBird::ErrorException => e
  puts
  puts 'An error occured while requesting an OTP object:'
  puts

  e.errors.each do |error|
    puts "  code        : #{error.code}"
    puts "  description : #{error.description}"
    puts "  parameter   : #{error.parameter}"
    puts
  end
end


text:
import * as snakeCaseKeys from 'snakecase-keys';
import { classToPlain } from 'class-transformer';

export abstract class InstaSticker {
  public width: number;
  public height: number;
  public rotation: number = 0.0;
  public x: number = 0.0;
  public y: number = 0.0;
  public z: number = 0;

  public isSticker: boolean = true;

  public abstract get id(): string;

  public abstract get key(): string;

  /**
   * Only used to set the media id when attaching media
   */
  public get additionalConfigureProperties(): any {
    return null;
  }

  public center(): this {
    this.x = 0.5;
    this.y = 0.5;
    return this;
  }

  public rotateDeg(deg: number): this {
    this.rotation = deg % 360.0;
    return this;
  }

  public scale(factor: number): this {
    this.width *= factor;
    this.height *= factor;
    return this;
  }

  public moveForward(layers: number = 1): this {
    this.z += layers;
    return this;
  }

  public moveBackwards(layers: number = 1): this {
    return this.moveForward(-layers);
  }

  public right(): this {
    this.x = 1.0 - this.width / 2;
    return this;
  }

  public left(): this {
    this.x = this.width / 2;
    return this;
  }

  public top(): this {
    this.y = this.height / 2;
    return this;
  }

  public bottom(): this {
    this.y = 1.0 - this.height / 2;
    return this;
  }

  public toJSON() {
    // @ts-ignore
    return snakeCaseKeys(classToPlain(this), { deep: true });
  }
}


text:
This release makes an important change to File DataObject permissions in order to close a vulnerability in
file modification privileges.

By default the minimum necessary permission required by any user to modify files has been changed
to CMS_ACCESS_AssetAdmin. If you need unauthenticated users, or users with other rights, to edit certain
files, then you will need to customise this.

E.g.

	:::php
	<?php
	class FileSecurityExtension extends DataExtension {
		public function canEdit($member) {
			return Permission::checkMember($member, 'MyCustomPermission');
		}
	}

An example use case is when you want to use UploadField on the frontend, where files could be uploaded
by non-admin users, and your above logic will need to ensure that those users can edit their own files
after they have uploaded it.

## Security

This release includes an important security fix.

 * 2015-01-12 [c49f164](https://github.com/silverstripe/silverstripe-framework/commit/c49f164) Fix file and uploadfield permissions [SS-2014-018](http://www.silverstripe.org/software/download/security-releases/ss-2014-018-open-file-permissions).

### Features and Enhancements

 * 2014-11-21 [31b5a9d](https://github.com/silverstripe/sapphire/commit/31b5a9d) Allow CMS re-authentication to be completely disabled if necessary (Damian Mooyman)
 * 2014-12-10 [fba6880](https://github.com/silverstripe/sapphire/commit/fba6880) Additional extension points for Tiny MCE editing, for when images are regenerated and manipulating the HTML prior to a save (Gordon Anderson)
 * 2014-11-13 [d7eb275](https://github.com/silverstripe/sapphire/commit/d7eb275) Make the record count in GridFieldFooter optional (Jeremy Shipman)

### Bugfixes

 * 2015-01-08 [a02adf6](https://github.com/silverstripe/sapphire/commit/a02adf6) Uneccessary class replacement (Michael Strong)
 * 2014-12-18 [5637431](https://github.com/silverstripe/sapphire/commit/5637431) The method 'name' does not exist on 'Form' (Elvinas L)
 * 2014-12-15 [6582162](https://github.com/silverstripe/sapphire/commit/6582162) How to folder on forms (Cam Findlay)
 * 2014-12-11 [b5c361a](https://github.com/silverstripe/sapphire/commit/b5c361a) GD - check file exists before getimagesize (Will Morgan)
 * 2014-12-09 [6bdd30c](https://github.com/silverstripe/sapphire/commit/6bdd30c) Fix gridfield storing duplicate data in session (Damian Mooyman)
 * 2014-12-09 [3ac705f](https://github.com/silverstripe/sapphire/commit/3ac705f) Feedback to name the fields section to "field types" to make it clearer what the section is about. (Cam Findlay)
 * 2014-12-09 [e9fd03b](https://github.com/silverstripe/sapphire/commit/e9fd03b) use GFMD code blocks to fix code formatting consistency. (Cam Findlay)
 * 2014-11-25 [01989aa](https://github.com/silverstripe/sapphire/commit/01989aa) Manifest flushing (Jonathon Menz)
 * 2014-11-24 [7384d01](https://github.com/silverstripe/sapphire/commit/7384d01) DataDifferencer was trying to compare fields, even if the fields didn't exist causing an error. (micmania1)
 * 2014-11-18 [2bdfd65](https://github.com/silverstripe/sapphire/commit/2bdfd65) Security::findAnAdministrator doesn't always find an admin (Damian Mooyman)
 * 2014-11-10 [85b4ba1](https://github.com/silverstripe/sapphire/commit/85b4ba1) DataObject::db() doesn't respect overloaded db types (fixes #3620) (Loz Calver)
 * 2014-10-03 [9d888d5](https://github.com/silverstripe/silverstripe-cms/commit/9d888d5) Fixed SearchForm not calling getTemplate() in forTemplate() (Stephen McMahon)
 * 2014-09-02 [1f4f5e6](https://github.com/silverstripe/sapphire/commit/1f4f5e6) Fix versioned Versioned is not writing Version to _version tables for subclasses of Version dataobjects which have their own DB fields - Fix disjoint of ID / RecordID (which should be the same) - Fix calculation of new record version - Fix use of empty vs !isset to check for existing version (Damian Mooyman)

## Changelog

 * [framework](https://github.com/silverstripe/silverstripe-framework/releases/tag/3.1.9)
 * [cms](https://github.com/silverstripe/silverstripe-cms/releases/tag/3.1.9)
 * [installer](https://github.com/silverstripe/silverstripe-installer/releases/tag/3.1.9)


text:
/*

Detect single-character XOR

One of the 60-character strings in this file has been encrypted by single-character XOR.

Find it.

(Your code from #3 should help.)

*/

namespace Crypto.Tests.Set1
{
    using System;
    using NUnit.Framework;
    using Utility;

    [TestFixture]
    public class Challenge4
    {
        [SetUp]
        public void Setup()
        {
            _data = IO.LoadTestFileLines("data/cryptoData_4.txt");

            Console.WriteLine(_data);
        }

        private string[] _data;

        [Test]
        public void ShouldFindBestSolutionInSampleSet()
        {
            var result = Solver.FindBestEnglishMessage(_data);

            Assert.AreEqual("5", result.Key, "Found: " + result);
            Assert.AreEqual("Now that the party is jumping", result.Message.Trim());
        }

        [Test]
        public void ShouldLoadFile()
        {
            Assert.AreEqual(327, _data.Length);
        }
    }
}


text:
class CreateMascotNames < ActiveRecord::Migration
  def change
    create_table :mascot_names do |t|
      t.references :mascot, index: true
      t.string :lang
      t.string :region
      t.string :script
      t.string :name
    end
  end
end


text:
@protocol DesignSpecDelegate <NSObject>
- (void)onRedraw;
@end

@interface DesignSpec : NSObject
@property (nonatomic) id <DesignSpecDelegate> delegate;
@property (nonatomic) UIView *hostView;

//DRAW
- (void)draw:(CGContextRef)context;

//BASELINE
- (DesignSpec *)setBaselineGridColor:(UIColor *)color;
- (DesignSpec *)setBaselineGridCellSize:(float)cellSize;
- (BOOL)isBaselineVisible;
- (DesignSpec *)setBaselineGridVisible:(BOOL)visible;

//KEYLINE
- (BOOL)areKeylinesVisible;
- (DesignSpec *)setKeylineVisible:(BOOL)visible;
- (DesignSpec *)setKeylineColor:(UIColor *)color;
- (DesignSpec *)addKeyline:(float)position From:(From)from;

//SPACING
- (BOOL)areSpacingsVisible;
- (DesignSpec *)setSpacingVisible:(BOOL)visible;
- (DesignSpec *)setSpacingColor:(UIColor *)color;
- (DesignSpec *)addSpacing:(float)offset Size:(float)size From:(From)from;

//JSON
- (void)loadSpecFromFileName:(NSString *)name;
@end


text:
external help file: Rubrik-help.xml
Module Name: Rubrik
online version: https://rubrik.gitbook.io/rubrik-sdk-for-powershell/command-documentation/reference/remove-rubrikuser
schema: 2.0.0
---

# Remove-RubrikUser

## SYNOPSIS
Removes a Rubrik user

## SYNTAX

```
Remove-RubrikUser [-Id] <String> [[-Server] <String>] [[-api] <String>] [-WhatIf] [-Confirm]
 [<CommonParameters>]
```

## DESCRIPTION
The Remove-RubrikUser cmdlet is used to remove a user from the Rubrik cluster.

## EXAMPLES

### EXAMPLE 1
```
Remove-RubrikUser -id "11111111-2222-3333-4444-555555555555"
```

This will remove the user matching id "11111111-2222-3333-4444-555555555555".

### EXAMPLE 2
```
Get-RubrikUser -Username 'john.doe' | Remove-RubrikUser
```

This will remove the user with the matching username of john.doe

## PARAMETERS

### -Id
ID of user to remove.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Server
Rubrik server IP or FQDN

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: $global:RubrikConnection.server
Accept pipeline input: False
Accept wildcard characters: False
```

### -api
API version

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: 3
Default value: $global:RubrikConnection.api
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

## NOTES
Written by Mike Preston for community usage
Twitter: @mwpreston
GitHub: mwpreston

## RELATED LINKS

[https://rubrik.gitbook.io/rubrik-sdk-for-powershell/command-documentation/reference/remove-rubrikuser](https://rubrik.gitbook.io/rubrik-sdk-for-powershell/command-documentation/reference/remove-rubrikuser)


text:
redis-monitor
---------

base RedisLive,monitor multiple redis-server in product enviroment:
* 1. monitor multiple redis-instance in one page
* 2. monitor memory,comand per sec,HitRate,keyspace, master-slave change,expire
* 3. sms alert when crash , master-slave stats changed

### install
    in src/script/redis-monitor.sh add redis-monitor as a startup service for redhat
    python redis_live.py #start web with port 8888
    python redis_monitor.py # start info collector
    #start daemon
    python redis_live_daemon.py
    python redis_monitor_daemon.py

### overview
![Redis Live](https://raw.github.com/LittlePeng/redis-monitor/master/design/redis-live.png)
![Redis Live](https://raw.github.com/LittlePeng/redis-monitor/master/design/overview.png)


text:
package com.google.javascript.rhino.jstype;

import static com.google.javascript.rhino.jstype.TernaryValue.UNKNOWN;

import com.google.javascript.rhino.ErrorReporter;

import java.util.Set;

/**
 * The {@code Unknown} type.
 *
 *
 */
public class UnknownType extends ObjectType {
  private static final long serialVersionUID = 1L;

  // See the explanation of checked unknown types in JSTypeNative.
  private final boolean isChecked;

  UnknownType(JSTypeRegistry registry, boolean isChecked) {
    super(registry);
    this.isChecked = isChecked;
  }

  @Override
  public boolean isUnknownType() {
    return true;
  }

  @Override
  public boolean isCheckedUnknownType() {
    return isChecked;
  }

  @Override
  public boolean canAssignTo(JSType that) {
    return true;
  }

  @Override
  public boolean canBeCalled() {
    return true;
  }

  @Override
  public boolean matchesNumberContext() {
    return true;
  }

  @Override
  public boolean matchesObjectContext() {
    return true;
  }

  @Override
  public boolean matchesStringContext() {
    return true;
  }

  @Override
  public TernaryValue testForEquality(JSType that) {
    return UNKNOWN;
  }

  @Override
  public boolean isNullable() {
    return true;
  }

  @Override
  public boolean isSubtype(JSType that) {
    return true;
  }

  @Override
  public JSType getLeastSupertype(JSType that) {
    return this;
  }

  @Override
  public JSType getGreatestSubtype(JSType that) {
    return this;
  }

  @Override
  public <T> T visit(Visitor<T> visitor) {
    return visitor.caseUnknownType();
  }

  @Override
  public String toString() {
    return getReferenceName();
  }

  @Override
  boolean defineProperty(String propertyName, JSType type,
      boolean inferred, boolean inExterns) {
    // nothing to define
    return true;
  }

  @Override
  public ObjectType getImplicitPrototype() {
    return null;
  }

  @Override
  public int getPropertiesCount() {
    return Integer.MAX_VALUE;
  }

  @Override
  void collectPropertyNames(Set<String> props) {
  }

  @Override
  public JSType getPropertyType(String propertyName) {
    return this;
  }

  @Override
  public boolean hasProperty(String propertyName) {
    return true;
  }

  @Override
  public FunctionType getConstructor() {
    return null;
  }

  @Override
  public String getReferenceName() {
    return isChecked ? "??" : "?";
  }

  @Override
  public boolean isPropertyTypeDeclared(String propertyName) {
    return false;
  }

  @Override
  public boolean isPropertyTypeInferred(String propertyName) {
    return false;
  }

  @Override
  public BooleanLiteralSet getPossibleToBooleanOutcomes() {
    return BooleanLiteralSet.BOTH;
  }

  @Override
  JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) {
    return this;
  }
}


text: require 'gemtest'


text:
/*
 *	Implements generic behavior of a font.
 *
 *	Most likely used exclusively for subclassing, for Type 0, Type 1 etc.
 *
 *	Ideally, the subclasses are hidden from the user, who interacts with them through this facade class.
 *
 */
#import <Foundation/Foundation.h>
#import "FontDescriptor.h"
#import "CMap.h"

extern const char *kFontDescriptorKey;
extern const char *kTypeKey;

typedef enum {
	UnknownEncoding = 0,
	StandardEncoding, // Defined in Type1 font programs
	MacRomanEncoding,
	WinAnsiEncoding,
	PDFDocEncoding,
	MacExpertEncoding,

} CharacterEncoding;

static inline NSStringEncoding nativeEncoding(CharacterEncoding encoding)
{
	switch (encoding) {
		case MacRomanEncoding :
			return NSMacOSRomanStringEncoding;
		case WinAnsiEncoding :
			return NSWindowsCP1252StringEncoding;
		default:
			return NSUTF8StringEncoding;
	}
}

static inline BOOL knownEncoding(CharacterEncoding encoding)
{
	return encoding > 0;
}

@interface Font : NSObject {
	CMap *toUnicode;
	NSMutableDictionary *widths;
    FontDescriptor *fontDescriptor;
	NSDictionary *ligatures;
	NSRange widthsRange;
	NSString *baseFont;
	CharacterEncoding encoding;
}

/* Factory method returns a Font object given a PDF font dictionary */
+ (Font *)fontWithDictionary:(CGPDFDictionaryRef)dictionary;

/* Initialize with a font dictionary */
- (id)initWithFontDictionary:(CGPDFDictionaryRef)dict;

/* Populate the widths array given font dictionary */
- (void)setWidthsWithFontDictionary:(CGPDFDictionaryRef)dict;

/* Construct a font descriptor given font dictionary */
- (void)setFontDescriptorWithFontDictionary:(CGPDFDictionaryRef)dict;

/* Given a PDF string, returns a Unicode string */
- (NSString *)stringWithPDFString:(CGPDFStringRef)pdfString;

/* Given a PDF string, returns a CID string */
- (NSString *)cidWithPDFString:(CGPDFStringRef)pdfString;

- (NSString *)unicodeWithPDFString:(CGPDFStringRef)pdfString;

/* Returns the width of a charachter (optionally scaled to some font size) */
- (CGFloat)widthOfCharacter:(unichar)characher withFontSize:(CGFloat)fontSize;

/* Import a ToUnicode CMap from a font dictionary */
- (void)setToUnicodeWithFontDictionary:(CGPDFDictionaryRef)dict;

/* Return an equivalent string, replacing ligatures with individual characters */
- (NSString *)stringByExpandingLigatures:(NSString *)string;

@property (nonatomic, retain) CMap *toUnicode;
@property (nonatomic, retain) NSMutableDictionary *widths;
@property (nonatomic, retain) FontDescriptor *fontDescriptor;
@property (nonatomic, readonly) CGFloat minY;
@property (nonatomic, readonly) CGFloat maxY;
@property (nonatomic, readonly) NSDictionary *ligatures;
@property (nonatomic, readonly) CGFloat widthOfSpace;
@property (nonatomic, readonly) NSRange widthsRange;
@property (nonatomic, assign) CharacterEncoding encoding;
@property (nonatomic, readonly) NSArray *descendantFonts;

/*!
 @property baseFont
 */
@property (nonatomic, retain) NSString *baseFont;

/*!
 * The actual name of the base font, sans tag.
 @property baseFontName
 */
@property (nonatomic, readonly) NSString *baseFontName;
@end


text:
Check if a character is alphanumerical (`[a-zA-Z0-9]`).

## Installation

[npm][]:

```bash
npm install is-alphanumerical
```

## Usage

```javascript
var alphanumerical = require('is-alphanumerical');

alphanumerical('a'); //=> true
alphanumerical('Z'); //=> true
alphanumerical('0'); //=> true
alphanumerical(' '); //=> false
alphanumerical('💩'); //=> false
```

## API

### `alphanumerical(character)`

Check whether the given character code (`number`), or the character
code at the first position (`string`), is alphanumerical.

## Related

*   [`is-alphabetical`](https://github.com/wooorm/is-alphabetical)
*   [`is-decimal`](https://github.com/wooorm/is-decimal)
*   [`is-hexadecimal`](https://github.com/wooorm/is-hexadecimal)
*   [`is-whitespace-character`](https://github.com/wooorm/is-whitespace-character)
*   [`is-word-character`](https://github.com/wooorm/is-word-character)

## License

[MIT][license] © [Titus Wormer][author]

<!-- Definitions -->

[travis-badge]: https://img.shields.io/travis/wooorm/is-alphanumerical.svg

[travis]: https://travis-ci.org/wooorm/is-alphanumerical

[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/is-alphanumerical.svg

[codecov]: https://codecov.io/github/wooorm/is-alphanumerical

[npm]: https://docs.npmjs.com/cli/install

[license]: LICENSE

[author]: http://wooorm.com


text:
  # create a new container (hash)
  # for each item in list, creates a name with associated default value (set default quantity to 1)
  # print the list to the console
# output:
# new list (hash)

def create_list(list)
	list_array = list.split(' ')
	new_list = {}
	for item in list_array
		new_list[item] = 1
	end

	return new_list
end

original_list = "carrots apples cereal pizza"
final_list = create_list(original_list)
puts final_list

# Method to add an item to a list
# input:
# 1. item name and optional quantity
# 2. the list
# steps:
# IF item doesn't exist
# create a name with associated optional quantity (if defined) ELSE default quantity (1)
# ELSE
# add to existing quantity
# output:
# new list

def add_item (item, qty, final_list)
  final_list[item] = (final_list.has_key?(item)) ? final_list[item] + qty : qty
end

# Method to remove an item from the list
# input:
# 1. item name
# 2. the list
# steps:
# purge the item/quantity pair from the container
# output:
# new list

def delete_item(item, final_list)
  final_list.delete(item)
end

# Method to update the quantity of an item
# input:
# 1. the item
# 2. new-quantity
# 3. the list
# steps:
# IF EXISTS
#   Set the quantity to new-quantity
# ELSE NOT EXISTS
#   error message "Doesn't exist"
# output:
# new list

def update_item(item, qty, final_list)
  if final_list.has_key?(item)
  	final_list[item] = qty
  else
  	puts "Doesn't exist"
  end
end

# Method to print a list and make it look pretty
# input:
# 1. the list
# steps:
# FOR EACH item, print name and quantity
# output:
# prints item name and quantity

def print_list(final_list)
	final_list.each { |item, qty|
		puts "#{item}: #{qty}"
	}
end

print_list(final_list)

# * What did you learn about pseudocode from working on this challenge?

# I learned that it's quite beneficial to quickly code since the pseudo code helps you gather the logic.

# * What are the tradeoffs of using Arrays and Hashes for this challenge?

# Using an array, one would need to maintain two, one for the list of items and one for the number of items.
# In addition, you would have to ensure that you kept the two arrays in sync positionally. For example,
# if deleting apple from the list array index 3, you have to also delete the element in the "counter" array
# at position 3. If you mess this up, then your entire data is worthless.

# A hash lends itself to easily maintain it's associated count for each item since key and values are paired
# nicely for hashes, and the item-name is the key and the item-count is the value.

# * What does a method return?

# A method can return either nil or any object.

# * What kind of things can you pass into methods as arguments?

# You can pass Strings, numbers, basically any object or objects or even nothing at all.

# * How can you pass information between methods?

# You pass information between methods using arguments.

# * What concepts were solidified in this challenge, and what concepts are still confusing?

# How to access a value in a hash was solidified. I was originally trying to do my_hash{key}
# and learned one uses square brackets, not curly, when accessing. The one thing still confusing
# is knowing when to use the appropriate iterator from the MANY available, and things like
# each vs map.


text:
package de.tu_berlin.impro3.flink.spatio_temporal_dynamics.io

import java.io.IOException

import org.apache.flink.api.common.io.OutputFormat
import org.apache.flink.configuration.Configuration
import org.apache.hadoop.hbase._
import org.apache.hadoop.hbase.client._
import org.apache.hadoop.hbase.util.Bytes

class HashTagsOutputFormat[T] extends OutputFormat[T] {

  @transient protected var conn: Connection = _
  @transient protected var table: Table = _

  override def configure(parameters: Configuration): Unit = try {
    val conf = HBaseConfiguration.create()
    conf.set("hbase.rootdir", parameters.getString("hbase", "hdfs://localhost:8020/hbase"))
    conn = ConnectionFactory.createConnection(conf)
    table = conn.getTable(TableName.valueOf("Hashtags"))
  } catch { case ex: Exception =>
    println("Error instantiating a new Hashtags HTable instance", ex)
  }

  override def close(): Unit = {
    if (table != null) table.close()
    table = null
    if (conn != null) conn.close()
    conn = null
  }

  // Write to Hash-tags HBase table.
  override def writeRecord(record: T): Unit = record match {
    case (deg: String, (occ: Int, (zone: String, focus: Double), entropy: Double, spread: Double, (_, _))) =>
      val put = new Put(Bytes.toBytes(deg))
      put.addColumn(Bytes.toBytes("metrics"), Bytes.toBytes("occurrences"), Bytes.toBytes(occ))
      put.addColumn(Bytes.toBytes("metrics"), Bytes.toBytes("focus-zone"), Bytes.toBytes(zone))
      put.addColumn(Bytes.toBytes("metrics"), Bytes.toBytes("focus"), Bytes.toBytes(focus))
      put.addColumn(Bytes.toBytes("metrics"), Bytes.toBytes("entropy"), Bytes.toBytes(entropy))
      put.addColumn(Bytes.toBytes("metrics"), Bytes.toBytes("spread"), Bytes.toBytes(spread))
      table.put(put)

    case (deg: String, (day: Long, (occ: Int, (zone: String, focus: Double), entropy: Double, spread: Double))) =>
      val put = new Put(Bytes.toBytes(deg))
      put.addColumn(Bytes.toBytes("temporal"), Bytes.toBytes(day + ":occurrences"), Bytes.toBytes(occ))
      put.addColumn(Bytes.toBytes("temporal"), Bytes.toBytes(day + ":focus-zone"), Bytes.toBytes(zone))
      put.addColumn(Bytes.toBytes("temporal"), Bytes.toBytes(day + ":focus"), Bytes.toBytes(focus))
      put.addColumn(Bytes.toBytes("temporal"), Bytes.toBytes(day + ":entropy"), Bytes.toBytes(entropy))
      put.addColumn(Bytes.toBytes("temporal"), Bytes.toBytes(day + ":spread"), Bytes.toBytes(spread))
      table.put(put)

    case _ => throw new IOException("Wrong output format!")
  }

  override def open(t: Int, t1: Int): Unit =
    if (table == null) throw new IOException("No HTable provided!")
}


text:
#nullable disable

namespace Amazon.CodeBuild;

public sealed class BuildArtifacts
{
    public string Location { get; init; }

    public string Md5Sum { get; init; }

    public string Sha256Sum { get; init; }
}


text:
package codec

import (
	"fmt"
	"github.com/davyxu/cellnet"
)

var registedCodecs []cellnet.Codec

// 注册编码器
func RegisterCodec(c cellnet.Codec) {

	if GetCodec(c.Name()) != nil {
		panic("duplicate codec: " + c.Name())
	}

	registedCodecs = append(registedCodecs, c)
}

// 获取编码器
func GetCodec(name string) cellnet.Codec {

	for _, c := range registedCodecs {
		if c.Name() == name {
			return c
		}
	}

	return nil
}

// cellnet自带的编码对应包
func getPackageByCodecName(name string) string {
	switch name {
	case "binary":
		return "github.com/davyxu/cellnet/codec/binary"
	case "gogopb":
		return "github.com/davyxu/cellnet/codec/gogopb"
	case "httpjson":
		return "github.com/davyxu/cellnet/codec/httpjson"
	case "json":
		return "github.com/davyxu/cellnet/codec/json"
	case "protoplus":
		return "github.com/davyxu/cellnet/codec/protoplus"
	default:
		return "package/to/your/codec"
	}
}

// 指定编码器不存在时,报错
func MustGetCodec(name string) cellnet.Codec {
	codec := GetCodec(name)

	if codec == nil {
		panic(fmt.Sprintf("codec not found '%s'\ntry to add code below:\nimport (\n  _ \"%s\"\n)\n\n",
			name,
			getPackageByCodecName(name)))
	}

	return codec
}


text:
package org.carewebframework.shell.property;

import java.lang.reflect.Method;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.fujion.common.MiscUtil;

/**
 * Holds information about a specific plug-in property.
 */
public class PropertyInfo {

    private String name;

    private String id;

    private String type = "text";

    private PropertyType propertyType;

    private String description;

    private String getter;

    private String setter;

    private boolean serializable = true;

    private boolean editable = true;

    private String dflt;

    private final Properties config = new Properties();

    public PropertyInfo() {
        super();
    }

    public String getName() {
        return name;
    }

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

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;

        if (!StringUtils.isEmpty(id)) {
            String s = firstUpper(id);
            getter = getter == null ? "get" + s : getter;
            setter = setter == null ? "set" + s : setter;
        }
    }

    public String getGetter() {
        return getter;
    }

    public void setGetter(String getter) {
        this.getter = getter;
    }

    public String getSetter() {
        return setter;
    }

    public void setSetter(String setter) {
        this.setter = setter;
    }

    public PropertyType getPropertyType() {
        if (propertyType == null) {
            propertyType = PropertyTypeRegistry.getInstance().get(getType());
        }

        return propertyType;
    }

    public String getType() {
        if (!"enum".equals(type)) {
            return type;
        }

        String className = getConfigValue("class");
        return "enum:" + (className != null ? "class:" + className : "bean:" + getConfigValue("bean"));
    }

    public void setType(String type) {
        this.type = type;
        propertyType = null;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Properties getConfig() {
        return config;
    }

    public void setConfig(String config) {
        setConfig(config == null ? null : config.split("\\|"));
    }

    public void setConfig(Properties config) {
        this.config.clear();
        this.config.putAll(config);
    }

    private void setConfig(String[] config) {
        this.config.clear();

        if (config != null) {
            for (String param : config) {
                String[] pcs = param.split("\\=", 2);

                if (pcs.length == 2) {
                    this.config.put(pcs[0], pcs[1]);
                }
            }
        }
    }

    /**
     * Convert first character of a string to upper case.
     *
     * @param value String to convert
     * @return Converted string
     */
    private String firstUpper(String value) {
        return value == null ? null : value.substring(0, 1).toUpperCase() + value.substring(1);
    }

    /**
     * Returns the property value for a specified object instance.
     *
     * @param instance The object instance.
     * @return The object's property value.
     */
    public Object getPropertyValue(Object instance) {
        return getPropertyValue(instance, false);
    }

    /**
     * Returns the property value for a specified object instance.
     *
     * @param instance The object instance.
     * @param forceDirect If true, a forces a direct read on the instance even if it implements
     *            IPropertyAccessor
     * @return The object's property value.
     */
    public Object getPropertyValue(Object instance, boolean forceDirect) {
        try {
            if (instance == null) {
                return dflt == null || !isSerializable() ? null : getPropertyType().getSerializer().deserialize(dflt);
            }

            if (!forceDirect && instance instanceof IPropertyAccessor) {
                return ((IPropertyAccessor) instance).getPropertyValue(this);
            }

            Method method = PropertyUtil.findGetter(getter, instance, null);
            return method == null ? null : method.invoke(instance);
        } catch (Exception e) {
            throw MiscUtil.toUnchecked(e);
        }
    }

    /**
     * Sets the property value for a specified object instance.
     *
     * @param instance The object instance.
     * @param value The value to assign.
     */
    public void setPropertyValue(Object instance, Object value) {
        setPropertyValue(instance, value, false);
    }

    /**
     * Sets the property value for a specified object instance.
     *
     * @param instance The object instance.
     * @param value The value to assign.
     * @param forceDirect If true, a forces a direct write to the instance even if it implements
     *            IPropertyAccessor
     */
    public void setPropertyValue(Object instance, Object value, boolean forceDirect) {
        try {
            if (!forceDirect && instance instanceof IPropertyAccessor) {
                ((IPropertyAccessor) instance).setPropertyValue(this, value);
                return;
            }

            Method method = null;

            try {
                method = PropertyUtil.findSetter(setter, instance, value == null ? null : value.getClass());
            } catch (Exception e) {
                if (value != null) {
                    PropertySerializer<?> serializer = getPropertyType().getSerializer();
                    value = value instanceof String ? serializer.deserialize((String) value) : serializer.serialize(value);
                    method = PropertyUtil.findSetter(setter, instance, value.getClass());
                } else {
                    throw e;
                }
            }

            if (method != null) {
                method.invoke(instance, value);
            }
        } catch (Exception e) {
            throw MiscUtil.toUnchecked(e);
        }
    }

    /**
     * Returns whether the property is serializable.
     *
     * @return True if the property is serializable.
     */
    public boolean isSerializable() {
        return serializable && getPropertyType().getSerializer() != null;
    }

    /**
     * Sets whether the object is serializable. Properties marked as not serializable will be
     * ignored during the serialization/deserialization process.
     *
     * @param serializable True if the property is serializable.
     */
    public void setSerializable(boolean serializable) {
        this.serializable = serializable;
    }

    /**
     * Returns whether the property's value is editable.
     *
     * @return True if the property is editable.
     */
    public boolean isEditable() {
        return editable;
    }

    /**
     * Sets whether the object is editable. Properties marked as not editable will be not be
     * presented by the property editor.
     *
     * @param editable True if the property is editable.
     */
    public void setEditable(boolean editable) {
        this.editable = editable;
    }

    /**
     * This is a convenience method for returning a named configuration value.
     *
     * @param key The configuration value's key.
     * @return Configuration value or null if not found.
     */
    public String getConfigValue(String key) {
        return config.getProperty(key);
    }

    /**
     * This is a convenience method for returning a named configuration value that is expected to be
     * an integer.
     *
     * @param key The configuration value's key.
     * @param dflt Default value.
     * @return Configuration value as an integer or default value if not found or not a valid
     *         integer.
     */
    public Integer getConfigValueInt(String key, Integer dflt) {
        try {
            return Integer.parseInt(getConfigValue(key));
        } catch (Exception e) {
            return dflt;
        }
    }

    /**
     * This is a convenience method for returning a named configuration value that is expected to be
     * a double floating point number.
     *
     * @param key The configuration value's key.
     * @param dflt Default value.
     * @return Configuration value as a double or default value if not found or not a valid double.
     */
    public Double getConfigValueDouble(String key, Double dflt) {
        try {
            return Double.parseDouble(getConfigValue(key));
        } catch (Exception e) {
            return dflt;
        }
    }

    /**
     * This is a convenience method for returning a named configuration value that is expected to be
     * a Boolean value.
     *
     * @param key The configuration value's key.
     * @param dflt Default value.
     * @return Configuration value as a Boolean or default value if not found or not a valid
     *         Boolean.
     */
    public Boolean getConfigValueBoolean(String key, Boolean dflt) {
        try {
            String value = getConfigValue(key);
            return value == null ? dflt : Boolean.parseBoolean(value);
        } catch (Exception e) {
            return dflt;
        }
    }

    /**
     * This is a convenience method for returning a named configuration value that is expected to be
     * a list of array elements delimited by commas.
     *
     * @param key The configuration value's key.
     * @return The array of values.
     */
    public String[] getConfigValueArray(String key) {
        return StringUtils.split(getConfigValue(key), ",");
    }

    /**
     * This is a convenience method for returning a named configuration value that is expected to be
     * a list of array elements.
     *
     * @param key The configuration value's key.
     * @param delimiter The delimiter separating array elements.
     * @return The array of values.
     */
    public String[] getConfigValueArray(String key, String delimiter) {
        return StringUtils.split(getConfigValue(key), delimiter);
    }

    /**
     * Returns the default value for this property.
     *
     * @return The default value.
     */
    public String getDefault() {
        return dflt;
    }

    /**
     * Sets the default value for this property.
     *
     * @param dflt The default value.
     */
    public void setDefault(String dflt) {
        this.dflt = dflt;
    }

}


text:
// Copyright (C) 2014 Space Monkey, Inc.
//
// 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.

// +build cgo

/*
Package openssl is a light wrapper around OpenSSL for Go.

It strives to provide a near-drop-in replacement for the Go standard library
tls package, while allowing for:

Performance

OpenSSL is battle-tested and optimized C. While Go's built-in library shows
great promise, it is still young and in some places, inefficient. This simple
OpenSSL wrapper can often do at least 2x with the same cipher and protocol.

On my lappytop, I get the following benchmarking speeds:
  BenchmarkSHA1Large_openssl      1000  2611282 ns/op  401.56 MB/s
  BenchmarkSHA1Large_stdlib        500  3963983 ns/op  264.53 MB/s
  BenchmarkSHA1Small_openssl   1000000     3476 ns/op    0.29 MB/s
  BenchmarkSHA1Small_stdlib    5000000      550 ns/op    1.82 MB/s
  BenchmarkSHA256Large_openssl     200  8085314 ns/op  129.69 MB/s
  BenchmarkSHA256Large_stdlib      100 18948189 ns/op   55.34 MB/s
  BenchmarkSHA256Small_openssl 1000000     4262 ns/op    0.23 MB/s
  BenchmarkSHA256Small_stdlib  1000000     1444 ns/op    0.69 MB/s
  BenchmarkOpenSSLThroughput    100000    21634 ns/op   47.33 MB/s
  BenchmarkStdlibThroughput      50000    58974 ns/op   17.36 MB/s

Interoperability

Many systems support OpenSSL with a variety of plugins and modules for things,
such as hardware acceleration in embedded devices.

Greater flexibility and configuration

OpenSSL allows for far greater configuration of corner cases and backwards
compatibility (such as support of SSLv2). You shouldn't be using SSLv2 if you
can help but, but sometimes you can't help it.

Security

Yeah yeah, Heartbleed. But according to the author of the standard library's
TLS implementation, Go's TLS library is vulnerable to timing attacks. And
whether or not OpenSSL received the appropriate amount of scrutiny
pre-Heartbleed, it sure is receiving it now.

Usage

Starting an HTTP server that uses OpenSSL is very easy. It's as simple as:
  log.Fatal(openssl.ListenAndServeTLS(
        ":8443", "my_server.crt", "my_server.key", myHandler))

Getting a net.Listener that uses OpenSSL is also easy:
  ctx, err := openssl.NewCtxFromFiles("my_server.crt", "my_server.key")
  if err != nil {
          log.Fatal(err)
  }
  l, err := openssl.Listen("tcp", ":7777", ctx)

Making a client connection is straightforward too:
  ctx, err := NewCtx()
  if err != nil {
          log.Fatal(err)
  }
  err = ctx.LoadVerifyLocations("/etc/ssl/certs/ca-certificates.crt", "")
  if err != nil {
          log.Fatal(err)
  }
  conn, err := openssl.Dial("tcp", "localhost:7777", ctx, 0)

Help wanted: To get this library to work with net/http's client, we
had to fork net/http. It would be nice if an alternate http client library
supported the generality needed to use OpenSSL instead of crypto/tls.
*/
package openssl

/*
#include <openssl/ssl.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/engine.h>

extern int Goopenssl_init_locks();
extern void Goopenssl_thread_locking_callback(int, int, const char*, int);

static int Goopenssl_init_threadsafety() {
	// Set up OPENSSL thread safety callbacks.  We only set the locking
	// callback because the default id callback implementation is good
	// enough for us.
	int rc = Goopenssl_init_locks();
	if (rc == 0) {
		CRYPTO_set_locking_callback(Goopenssl_thread_locking_callback);
	}
	return rc;
}

static void OpenSSL_add_all_algorithms_not_a_macro() {
	OpenSSL_add_all_algorithms();
}

*/
import "C"

import (
	"errors"
	"fmt"
	"strings"
	"sync"
)

var (
	sslMutexes []sync.Mutex
)

func init() {
	C.OPENSSL_config(nil)
	C.ENGINE_load_builtin_engines()
	C.SSL_load_error_strings()
	C.SSL_library_init()
	C.OpenSSL_add_all_algorithms_not_a_macro()
	rc := C.Goopenssl_init_threadsafety()
	if rc != 0 {
		panic(fmt.Errorf("Goopenssl_init_locks failed with %d", rc))
	}
}

// errorFromErrorQueue needs to run in the same OS thread as the operation
// that caused the possible error
func errorFromErrorQueue() error {
	var errs []string
	for {
		err := C.ERR_get_error()
		if err == 0 {
			break
		}
		errs = append(errs, fmt.Sprintf("%s:%s:%s",
			C.GoString(C.ERR_lib_error_string(err)),
			C.GoString(C.ERR_func_error_string(err)),
			C.GoString(C.ERR_reason_error_string(err))))
	}
	return errors.New(fmt.Sprintf("SSL errors: %s", strings.Join(errs, "\n")))
}


text:
package com.github.lothar.security.acl.grant.domain;

public class NoAclObject {
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="ChangesViewManager" flattened_view="true" show_ignored="false" />
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
  <component name="RunManager" selected="Python.opsmanager">
    <configuration default="true" type="PythonConfigurationType" factoryName="Python">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="opsmanager" />
      <EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
      <option name="SCRIPT_NAME" value="" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <configuration default="false" name="opsmanager" type="PythonConfigurationType" factoryName="Python" singleton="true">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="opsmanager" />
      <EXTENSION ID="PythonCoverageRunConfigurationExtension" enabled="false" sample_coverage="true" runner="coverage.py" />
      <option name="SCRIPT_NAME" value="$PROJECT_DIR$/app/__init__.py" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="Python.opsmanager" />
    </list>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <created>1461216650566</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1461216650566</updated>
    </task>
    <servers />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
</project>


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="">
    <title>MEERKAT</title>

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

    <link href="css/stylish-portfolio.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link rel="stylesheet" href="css/creative.css" type="text/css">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                        <canvas id="myCanvas" width="480" height="400" style="margin-top:15%;">

                        </canvas>

                            <input id="sendFL" class="btn btn-success" type=button value="Start" style="font-weight:bold;">


text:
/* ###
 * IP: GHIDRA
 *
 * 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 ghidra.framework.main.projectdata.actions;

import java.awt.event.MouseEvent;

import docking.ActionContext;
import docking.DialogComponentProvider;
import ghidra.app.util.GenericHelpTopics;
import ghidra.framework.main.AppInfo;
import ghidra.framework.main.datatree.CheckoutsPanel;
import ghidra.framework.model.*;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.remote.User;
import ghidra.framework.store.ItemCheckoutStatus;
import ghidra.util.HelpLocation;

/**
 * Dialog for viewing all the current checkouts for a single domain file.
 */
public class CheckoutsDialog extends DialogComponentProvider implements ProjectListener {

	private CheckoutsPanel panel;

	public CheckoutsDialog(PluginTool tool, User user, DomainFile domainFile,
			ItemCheckoutStatus[] checkouts) {

		super("View Checkouts for " + domainFile.getName(), false);
		setHelpLocation(new HelpLocation(GenericHelpTopics.REPOSITORY, "View_Check_Outs"));
		panel = new CheckoutsPanel(rootPanel, tool, user, domainFile, checkouts);
		addWorkPanel(panel);
		addDismissButton();
		AppInfo.getFrontEndTool().addProjectListener(this);

		createActions();
	}

	@Override
	protected void dismissCallback() {
		AppInfo.getFrontEndTool().removeProjectListener(this);
		close();
		panel.dispose();
	}

	@Override
	public void projectClosed(Project project) {
		dismissCallback();
	}

	@Override
	public void projectOpened(Project project) {
		// don't care
	}

	private void createActions() {
		panel.createActions(this);
	}

	@Override
	public ActionContext getActionContext(MouseEvent event) {

		int[] selectedRows = panel.getSelectedRows();
		return new CheckoutsActionContext(selectedRows);
	}
}