text:
<?php
namespace Chalcedonyt\RedisTagger;

use Log;
use Redis;

class TaggerProxy {
    /**
     * The Redis key generated from the arguments
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @return String The key
     */
    public static function getKey( $class, $key_args )
    {
        $instance = TaggerFactory::create( $class, $key_args );
        return $instance -> getKey();
    }

    /**
     * Given a Tagger with the class $class, search for the value of the tag named $tag_name (without {}) if available.
     * E.g. given a KeyValueTagger with the tags ['somelabel','{campaign_id}'] and the generated key somelabel:123
     * calling valueOfTagInKey('myclass', 'campaign_id') would return 123.
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @param mixed $value the value to set
     * @return mixed $value the value of Redis::set
     */
    public static function valueOfTagInKey( $class, $key, $tag_name){
        $key_tags = explode( Tagger::DELIMITER, $key);
        $instance = TaggerFactory::create($class);
        $class_tags = $instance -> getPlainTags();

        if( in_array($tag_name, $class_tags)){
            $index = array_search($tag_name, $class_tags);
            return $key_tags[$index];
        }
        return false;
    }

    /**
     * Wrapper for Redis::set Sets a value into the cache
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @param mixed $value the value to set
     * @return mixed $value the value of Redis::set
     */
    public static function set($class, $key_args, $value){
        $key = static::getKey( $class, $key_args );
        Log::info('Storing into '.$key, ['value' => $value]);
        return Redis::set($key, $value);
    }

    /**
     * Wrapper for Redis::get Gets a value from the cache
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @return mixed The result of Redis::get
     */
    public function get($class, $key_args){
        $key = static::getKey( $class, $key_args );
        return Redis::get($key);
    }

    /**
     * Wrapper for Redis::keys
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @return Array the matched keys
     */
    public static function keys($class, $key_args)
    {
        $search_string = static::getSearchKey($class, $key_args);
        return Redis::keys( $search_string );
    }

    /**
     * Returns a key with wildcards where applicable
     * @param String $class the class name of the tagger, relative to KeyValueFactory::BASE_PATH
     * @param Array $key_args The keys to be replaced into the tagger.
     * @return String the derived key
     */
    public static function getSearchKey($class, $key_args )
    {
        $instance = TaggerFactory::create( $class, $key_args );
        return $instance -> getKeysForSearch();
    }

}
?>


text:
interface EXIFStatic {
    getData(url: string, callback: any): any;
    getTag(img: any, tag: any): any;
    getAllTags(img: any): any;
    pretty(img: any): string;
    readFromBinaryFile(file: any): any;
}

declare var EXIF : EXIFStatic;
export = EXIF;

redpajama_set_name: RedPajamaGithub


text:
This repo provides all necessary drivers and descriptions for tams' full ur5 setup in the lab including a matching moveit configuration.

---

## Usage with the hardware

To bring up the whole arm configuration with all drivers, the corner urdf, moveit and the camera:

```
roslaunch tams_ur5_setup_bringup tams_ur5_setup_floor_camera.launch
```

This launch file is included in the tams_ur5_setup.launch. You can set the `use_kinect` argument to `true` to bringup the kinect drivers, to `false` to bringup the mechmind camera.

You can also use this launch file to directly bring up the arm without a camera:
```
roslaunch tams_ur5_setup_bringup tams_ur5_setup_ur_robot_driver.launch
```

---

## Usage with moveit demo mode

To start the setup without hardware, use the moveit demo mode:

```
roslaunch tams_ur5_setup_moveit_config demo.launch
```

This will bring up the same setup as `tams_ur5_setup.launch` and `rviz` but replaces the hardware drivers by moveits fake execution interfaces.

You can start this with a gui for the joint states of the ur5 and the gripper:

```
roslaunch tams_ur5_setup_moveit_config demo.launch use_gui:=true
```


text:
module.exports = class Test {
    constructor () {

    }

    start(options) {
        this.callbackTimeout = options.callbackTimeout;
    };

    exchangeFunction (object, callback) {
        return callback(null, object);
    };

    methodOk(object, callback) {
        callback(null, object);
    };

    methodError(callback) {
        callback(new Error('Some problem'));
    };

    methodInjectHappn1($happn, object, callback) {
        callback(null, {meshName: $happn.info.mesh.name});
    };

    methodInjectHappn2(object, $happn, callback) {
        callback(null, {meshName: $happn.info.mesh.name});
    };

    methodInjectOrigin($origin, object, $happn, callback) {
        object.meshName = $happn.info.mesh.name;
        object.originUser = $origin.username;
        callback(null, object);
    };

    methodInjectHappnLast(object, $origin, callback, $happn) {
        object.meshName = $happn.info.mesh.name;
        object.originUser = $origin.username;
        callback(null, object);
    };

    synchronousMethod($origin, object, $happn) {
        console.log(arguments);
    };

    promiseMethod(param1, param2) {
        return new Promise(resolve => {
            setTimeout(() => {resolve([param1, param2])}, 50);
        });
    }

    async asyncMethod($happn, $origin, param1, param2) {
        if (typeof param2 === 'function') throw new Error('bad parameter passed in');
        return await this.promiseMethod(param1, param2);
    }

    methodOther(object, callback, $happn) {
        return callback(null, { object });
    };

    methodError(object, callback, $happn) {
        callback(new Error('test'));
    };
}


text:
using System;

namespace Rhino.ServiceBus.Internal
{
    internal interface ITransaction
    {
        int Commit(int fRetaining, int grfTC, int grfRM);
        int Abort(int pboidReason, int fRetaining, int fAsync);
        int GetTransactionInfo(IntPtr pinfo);
    }
}


text:
"use strict";
exports.TUTORIALS_FIND = 'TUTORIALS_FIND';
exports.TUTORIALS_UPDATE = 'TUTORIALS_UPDATE';
exports.TUTORIAL_UPDATE = 'TUTORIAL_UPDATE';
exports.TUTORIAL_VERSION = 'TUTORIAL_VERSION';
//# sourceMappingURL=types.js.map


text:
package com.google.javascript.jscomp.newtypes;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Represents the type-parameter names of a generic function.
 * If the function uses TTL, this class also knows about the TTL AST of each type parameter.
 * We do not use this class for generic nominal types, because they do not use TTL.
 */
public final class TypeParameters implements Serializable {
  /**
   * If a type parameter is a TTL parameter, we map it to its TTL AST. Otherwise, to an empty node.
   */
  private final ImmutableMap<String, Node> typeParams;
  static final TypeParameters EMPTY = new TypeParameters(ImmutableMap.<String, Node>of());

  private TypeParameters(Map<String, Node> typeParams) {
    this.typeParams = ImmutableMap.copyOf(typeParams);
  }

  static TypeParameters make(List<String> ordinaryTypeParams) {
    return make(ordinaryTypeParams, ImmutableMap.<String, Node>of());
  }

  static TypeParameters make(List<String> ordinaryTypeParams, Map<String, Node> ttlParams) {
    ImmutableMap.Builder<String, Node> builder = ImmutableMap.builder();
    for (String typeParam : ordinaryTypeParams) {
      builder.put(typeParam, IR.empty());
    }
    builder.putAll(ttlParams);
    return new TypeParameters(builder.build());
  }

  List<String> asList() {
    return this.typeParams.keySet().asList();
  }

  /**
   * Returns a non-null list of type variables, by filtering out the TTL variables
   * from this.typeParams.
   */
  List<String> getOrdinaryTypeParams() {
    boolean foundTtlVariable = false;
    for (Map.Entry<String, Node> entry : this.typeParams.entrySet()) {
      if (!entry.getValue().isEmpty()) {
        foundTtlVariable = true;
        break;
      }
    }
    if (foundTtlVariable) {
      ImmutableList.Builder<String> builder = ImmutableList.builder();
      for (Map.Entry<String, Node> entry : this.typeParams.entrySet()) {
        if (entry.getValue().isEmpty()) {
          builder.add(entry.getKey());
        }
      }
      return builder.build();
    }
    return this.typeParams.keySet().asList();
  }

  /**
   * Returns a non-null map from TTL variables to their ASTs, by filtering out the non-TTL
   * variables from this.typeParams.
   */
  public Map<String, Node> getTypeTransformations() {
    boolean foundOrdinaryTypeVariable = false;
    for (Map.Entry<String, Node> entry : this.typeParams.entrySet()) {
      if (entry.getValue().isEmpty()) {
        foundOrdinaryTypeVariable = true;
        break;
      }
    }
    if (foundOrdinaryTypeVariable) {
      ImmutableMap.Builder<String, Node> builder = ImmutableMap.builder();
      for (Map.Entry<String, Node> entry : this.typeParams.entrySet()) {
        if (!entry.getValue().isEmpty()) {
          builder.put(entry);
        }
      }
      return builder.build();
    }
    return this.typeParams;
  }

  boolean isEmpty() {
    return this.typeParams.isEmpty();
  }

  boolean contains(String typeParam) {
    return this.typeParams.containsKey(typeParam);
  }

  @Override
  public boolean equals(Object o) {
    TypeParameters other = (TypeParameters) o;
    return this.typeParams.equals(other.typeParams);
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(this.typeParams);
  }
}


text:
@interface vBulletinCommonConfig : NSObject <BBSBaseConfigDelegate, vBulletinConfigDelegate>

@property(nonatomic) NSURL *forumURL;
@end


text:
require 'renegade/prepare_commit_msg'
require 'stringio'

describe Renegade::PrepareCommitMsg do
  subject { Renegade::PrepareCommitMsg }

  before do
    $stdout = StringIO.new
  end

  after(:all) do
    $stdout = STDOUT
  end

  def fail_all_msg
    'Includes a valid BugId, Story or Epic number'.error + "\n" +
      'Commit message length'.error + "\n" +
      'Only ASCII characters'.error + "\n"
  end

  def success_msg
    'Includes a valid BugId, Story or Epic number'.success + "\n" +
      'Commit message length'.success + "\n" +
      'Only ASCII characters'.success + "\n"
  end

  def fail_length_msg
    'Includes a valid BugId, Story or Epic number'.success + "\n" +
      'Commit message length'.error + "\n" +
      'Only ASCII characters'.success + "\n"
  end

  def fail_non_ascii_msg
    'Includes a valid BugId, Story or Epic number'.success + "\n" +
      'Commit message length'.success + "\n" +
      'Only ASCII characters'.error + "\n"
  end

  it 'should do nothing if not a message' do
    subject.new(['./test/fixtures/commit_messages/just_right.txt',
                 'something else']).run
    $stdout.string.must_equal('')
  end

  it 'should be too long' do
    subject.new(['./test/fixtures/commit_messages/too_long.txt',
                 'message']).run

    $stdout.string.must_equal("\n"\
      "\e[35mRunning prepare-commit-msg hooks…\e[0m\n" +
      fail_length_msg + "\n"\
      "Errors:\n"\
      '- Commit messages should be between 7 and 50 characters.' + "\n\n")
  end

  it 'should be too short' do
    subject.new(['./test/fixtures/commit_messages/too_short.txt',
                 'message']).run

    $stdout.string.must_equal("\n"\
      "\e[35mRunning prepare-commit-msg hooks…\e[0m\n" +
      fail_length_msg + "\n"\
      "Errors:\n"\
      '- Commit messages should be between 7 and 50 characters.' + "\n\n")
  end

  it 'should have non-ascii' do
    subject.new(['./test/fixtures/commit_messages/has_non_ascii.txt',
                 'message']).run

    $stdout.string.must_equal("\n"\
      "\e[35mRunning prepare-commit-msg hooks…\e[0m\n" +
      fail_non_ascii_msg + "\n"\
      "Errors:\n"\
      '- Commit messages may not contain non-ASCII characters' + "\n\n")
  end

  it 'should fail everything' do
    subject.new(['./test/fixtures/commit_messages/fail_everything.txt',
                 'message']).run

    $stdout.string.must_equal("\n"\
      "\e[35mRunning prepare-commit-msg hooks…\e[0m\n" +
      fail_all_msg + "\n"\
      "Errors:\n"\
      "- Commit messages should be between 7 and 50 characters.\n"\
      "- You must include a valid BugId, Story or Epic number.\n"\
      "  Examples:\n"\
      "  - BugId: 12345 | Helpful comment describing bug fix\n"\
      "  - Story: B-12345 | Helpful comment describing story\n"\
      "  - Epic: E-12345 | Epic comment\n"\
      '- Commit messages may not contain non-ASCII characters' + "\n\n")
  end

  it 'should be just right' do
    subject.new(['./test/fixtures/commit_messages/just_right.txt',
                 'message']).run

    $stdout.string.must_equal("\n"\
      "\e[35mRunning prepare-commit-msg hooks…\e[0m\n" +
      success_msg)
  end
end


text:
from django.conf.urls.defaults import patterns
from mint.django_rest.rbuilder.inventory.views.v1 import views as inventoryviews
from mint.django_rest import urls

URL = urls.URLRegistry.URL

urlpatterns = patterns('',

    # Discoverability
    URL(r'/?$',
        inventoryviews.InventoryService(),
        name='Inventory'),

    # Log
    URL(r'/log/?$',
        inventoryviews.InventoryLogService(),
        name='Log'),

    # System States
    URL(r'/system_states/?$',
        inventoryviews.InventorySystemStatesService(),
        name='SystemStates'),
    URL(r'/system_states/(?P<system_state_id>\d+)/?$',
        inventoryviews.InventorySystemStateService(),
        name='SystemState'),

    # Zones
    URL(r'/zones/?$',
        inventoryviews.InventoryZonesService(),
        name='Zones'),
    URL(r'/zones/(?P<zone_id>\d+)/?$',
        inventoryviews.InventoryZoneService(),
        name='Zone'),

    # Management Nodes
    URL(r'/management_nodes/?$',
        inventoryviews.InventoryManagementNodesService(),
        name='ManagementNodes',
        model='inventory.ManagementNodes'),
    URL(r'/management_nodes/(?P<management_node_id>\d+)/?$',
        inventoryviews.InventoryManagementNodeService(),
        name='ManagementNode',
        model='inventory.ManagementNode'),
    URL(r'/zones/(?P<zone_id>\d+)/management_nodes/?$',
        inventoryviews.InventoryZoneManagementNodesService(),
        name='ZoneManagementNodes',
        model='inventory.ZoneManagementNodes'),
    URL(r'/zones/(?P<zone_id>\d+)/management_nodes/(?P<management_node_id>\d+)/?$',
        inventoryviews.InventoryZoneManagementNodeService(),
        name='ZoneManagementNode',
        model='inventory.ZoneManagementNode'),

    # System types
    URL(r'/system_types/?$',
        inventoryviews.InventorySystemTypesService(),
        name='SystemTypes',
        model='inventory.SystemTypes'),
    URL(r'/system_types/(?P<system_type_id>\d+)/?$',
        inventoryviews.InventorySystemTypeService(),
        name='SystemType',
        model='inventory.SystemType'),
    URL(r'/system_types/(?P<system_type_id>\d+)/systems/?$',
        inventoryviews.InventorySystemTypeSystemsService(),
        name='SystemTypeSystems',
        model='inventory.Systems'),

    # Networks
    URL(r'/networks/?$',
        inventoryviews.InventoryNetworksService(),
        name='Networks',
        model='inventory.Networks'),
    URL(r'/networks/(?P<network_id>\d+)/?$',
        inventoryviews.InventoryNetworkService(),
        name='Network',
        model='inventory.Network'),

    # Systems
    # RBL-8919 - accept double slashes to accommodate an rpath-tools bug
    URL(r'/systems/?$',
        inventoryviews.InventorySystemsService(),
        name='Systems',
        model='inventory.Systems'),
    URL(r'/inventory_systems/?$',
        inventoryviews.InventoryInventorySystemsService(),
        name='InventorySystems',
        model='inventory.Systems'),
    URL(r'/infrastructure_systems/?$',
        inventoryviews.InventoryInfrastructureSystemsService(),
        name='InfrastructureSystems',
        model='inventory.Systems'),
    URL(r'/systems/(?P<system_id>\d+)/?$',
        inventoryviews.InventorySystemsSystemService(),
        name='System',
        model='inventory.System'),
    URL(r'/systems/(?P<system_id>\d+)/system_log/?$',
        inventoryviews.InventorySystemsSystemLogService(),
        name='SystemLog',
        model='inventory.SystemLog'),
    URL(r'/systems/(?P<system_id>\d+)/jobs/?$',
        inventoryviews.InventorySystemJobsService(),
        name='SystemJobs',
        model='inventory.SystemJobs'),
    URL(r'/systems/(?P<system_id>\d+)/descriptors/(?P<descriptor_type>[_A-Za-z]+)/?$',
        inventoryviews.InventorySystemJobDescriptorService(),
        name='SystemJobDescriptors'),
    URL(r'/systems/(?P<system_id>\d+)/job_states/(?P<job_state_id>[a-zA-Z0-9]+)/jobs/?$',
        inventoryviews.InventorySystemJobStatesService(),
        name='SystemJobStateJobs',
        model='inventory.SystemJobs'),
    URL(r'/systems/(?P<system_id>\d+)/system_events/?$',
        inventoryviews.InventorySystemsSystemEventService(),
        name='SystemsSystemEvent',
        model='inventory.SystemEvents'),
    URL(r'/systems/(?P<system_id>\d+)/system_log/(?P<format>[a-zA-Z]+)/?$',
        inventoryviews.InventorySystemsSystemLogService(),
        name='SystemLogFormat',
        model='inventory.SystemLog'),

    # System Events
    URL(r'/system_events/?$',
        inventoryviews.InventorySystemEventsService(),
        name='SystemEvents',
        model='inventory.SystemEvents'),
    URL(r'/system_events/(?P<system_event_id>\d+)/?$',
        inventoryviews.InventorySystemEventService(),
        name='SystemEvent',
        model='inventory.SystemEvent'),

    # System Tags
    URL(r'/systems/(?P<system_id>\d+)/system_tags/?$',
        inventoryviews.InventorySystemTagsService(),
        name='SystemTags'),
    URL(r'/systems/(?P<system_id>\d+)/system_tags/(?P<system_tag_id>\d+)/?$',
        inventoryviews.InventorySystemTagService(),
        name='SystemTag'),

    # Event Types
    URL(r'/event_types/?$',
        inventoryviews.InventoryEventTypesService(),
        name='EventTypes',
        model='inventory.EventTypes'),
    URL(r'/event_types/(?P<event_type_id>\d+)/?$',
        inventoryviews.InventoryEventTypeService(),
        name='EventType',
        model='inventory.EventType'),

)


text:
.PHONY: setup build dist serve test benchmark clean

setup:
	npm install

build:
	pub build --mode=release

dist:
	dart2js --out=./dist/katex-dart.js --package-root=./packages --minify ./lib/katex.dart

serve:
	pub serve

test:
	grunt test

benchmark:
	pub serve benchmark

clean:
	rm -rf dist/*


text:
package org.apache.samza.container.host;

/**
 * An object that returns {@link SystemMemoryStatistics} for the {@link org.apache.samza.container.SamzaContainer}.
 */
public interface SystemStatisticsGetter {

  /**
   * Returns the {@link SystemMemoryStatistics} for the current Samza container process. A 'null' value is
   * returned if no statistics are available.
   *
   * @return {@link SystemMemoryStatistics} for the Samza container
   */
  SystemMemoryStatistics getSystemMemoryStatistics();

  /**
   * Returns the {@link ProcessCPUStatistics} for the current Samza container process(includes its child processes). A
   * 'null' value is returned if no statistics are available.
   *
   * @return {@link ProcessCPUStatistics} for the Samza container process
   */
  ProcessCPUStatistics getProcessCPUStatistics();
}


text:
FOUNDATION_EXPORT double M3U8VersionNumber;

//! Project version string for M3U8.
FOUNDATION_EXPORT const unsigned char M3U8VersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <M3U8/PublicHeader.h>


text:
#if !defined(__COREFOUNDATION_CFMESSAGEPORT__)
#define __COREFOUNDATION_CFMESSAGEPORT__ 1

#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFRunLoop.h>
#include <CoreFoundation/CFData.h>
#include <dispatch/dispatch.h>

CF_IMPLICIT_BRIDGING_ENABLED
CF_EXTERN_C_BEGIN

typedef struct CF_BRIDGED_MUTABLE_TYPE(NSMessagePort) __CFMessagePort * CFMessagePortRef;

CF_ENUM(SInt32) {
    kCFMessagePortSuccess = 0,
    kCFMessagePortSendTimeout = -1,
    kCFMessagePortReceiveTimeout = -2,
    kCFMessagePortIsInvalid = -3,
    kCFMessagePortTransportError = -4,
    kCFMessagePortBecameInvalidError = -5
};

typedef struct {
    CFIndex	version;
    void *	info;
    const void *(*retain)(const void *info);
    void	(*release)(const void *info);
    CFStringRef	(*copyDescription)(const void *info);
} CFMessagePortContext;

typedef CFDataRef (*CFMessagePortCallBack)(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info);
/* If callout wants to keep a hold of the data past the return of the callout, it must COPY the data. This includes the case where the data is given to some routine which _might_ keep a hold of it; System will release returned CFData. */
typedef void (*CFMessagePortInvalidationCallBack)(CFMessagePortRef ms, void *info);

CF_EXPORT CFTypeID	CFMessagePortGetTypeID(void);

CF_EXPORT CFMessagePortRef	CFMessagePortCreateLocal(CFAllocatorRef allocator, CFStringRef name, CFMessagePortCallBack callout, CFMessagePortContext *context, Boolean *shouldFreeInfo);
CF_EXPORT CFMessagePortRef	CFMessagePortCreateRemote(CFAllocatorRef allocator, CFStringRef name);

CF_EXPORT Boolean	CFMessagePortIsRemote(CFMessagePortRef ms);
CF_EXPORT CFStringRef	CFMessagePortGetName(CFMessagePortRef ms);
CF_EXPORT Boolean	CFMessagePortSetName(CFMessagePortRef ms, CFStringRef newName);
CF_EXPORT void		CFMessagePortGetContext(CFMessagePortRef ms, CFMessagePortContext *context);
CF_EXPORT void		CFMessagePortInvalidate(CFMessagePortRef ms);
CF_EXPORT Boolean	CFMessagePortIsValid(CFMessagePortRef ms);
CF_EXPORT CFMessagePortInvalidationCallBack CFMessagePortGetInvalidationCallBack(CFMessagePortRef ms);
CF_EXPORT void CFMessagePortSetInvalidationCallBack(CFMessagePortRef ms, CFMessagePortInvalidationCallBack callout);

/* NULL replyMode argument means no return value expected, dont wait for it */
CF_EXPORT SInt32	CFMessagePortSendRequest(CFMessagePortRef remote, SInt32 msgid, CFDataRef data, CFTimeInterval sendTimeout, CFTimeInterval rcvTimeout, CFStringRef replyMode, CFDataRef *returnData);

CF_EXPORT CFRunLoopSourceRef	CFMessagePortCreateRunLoopSource(CFAllocatorRef allocator, CFMessagePortRef local, CFIndex order);

CF_EXPORT void CFMessagePortSetDispatchQueue(CFMessagePortRef ms, dispatch_queue_t queue) API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));

CF_EXTERN_C_END
CF_IMPLICIT_BRIDGING_DISABLED

#endif /* ! __COREFOUNDATION_CFMESSAGEPORT__ */


text:
package org.apache.hadoop.hbase.regionserver.wal;

import org.apache.hadoop.fs.Path;

/**
 * Interface that defines all actions that can be listened to coming
 * from the HLog. The calls are done in sync with what happens over in the
 * HLog so make sure your implementation is fast.
 */
public interface LogActionsListener {

  /**
   * Notify the listener that a new file is available
   * @param newFile the path to the new hlog
   */
  public void logRolled(Path newFile);
}


text:
<?php

/**
 * @namespace
 */

namespace Solarium\QueryType\Select\RequestBuilder\Component;

use Solarium\QueryType\Select\Query\Component\Highlighting\Highlighting as HighlightingComponent;
use Solarium\QueryType\Select\Query\Component\Highlighting\Field as HighlightingField;
use Solarium\Core\Client\Request;

/**
 * Add select component Highlighting to the request
 */
class Highlighting implements ComponentRequestBuilderInterface
{

    /**
     * Add request settings for Highlighting
     *
     * @param  HighlightingComponent $component
     * @param  Request               $request
     * @return Request
     */
    public function buildComponent($component, $request)
    {
        // enable highlighting
        $request->addParam('hl', 'true');

        // set global highlighting params
        $request->addParam('hl.fl', implode(',', array_keys($component->getFields())));
        $request->addParam('hl.snippets', $component->getSnippets());
        $request->addParam('hl.fragsize', $component->getFragSize());
        $request->addParam('hl.mergeContiguous', $component->getMergeContiguous());
        $request->addParam('hl.requireFieldMatch', $component->getRequireFieldMatch());
        $request->addParam('hl.maxAnalyzedChars', $component->getMaxAnalyzedChars());
        $request->addParam('hl.alternateField', $component->getAlternateField());
        $request->addParam('hl.maxAlternateFieldLength', $component->getMaxAlternateFieldLength());
        $request->addParam('hl.formatter', $component->getFormatter());
        $request->addParam('hl.simple.pre', $component->getSimplePrefix());
        $request->addParam('hl.simple.post', $component->getSimplePostfix());
        $request->addParam('hl.tag.pre', $component->getTagPrefix());
        $request->addParam('hl.tag.post', $component->getTagPostfix());
        $request->addParam('hl.fragmenter', $component->getFragmenter());
        $request->addParam('hl.fragListBuilder', $component->getFragListBuilder());
        $request->addParam('hl.fragmentsBuilder', $component->getFragmentsBuilder());
        $request->addParam('hl.useFastVectorHighlighter', $component->getUseFastVectorHighlighter());
        $request->addParam('hl.usePhraseHighlighter', $component->getUsePhraseHighlighter());
        $request->addParam('hl.highlightMultiTerm', $component->getHighlightMultiTerm());
        $request->addParam('hl.regex.slop', $component->getRegexSlop());
        $request->addParam('hl.regex.pattern', $component->getRegexPattern());
        $request->addParam('hl.regex.maxAnalyzedChars', $component->getRegexMaxAnalyzedChars());
        $request->addParam('hl.q', $component->getQuery());
        $request->addParam('hl.phraseLimit', $component->getPhraseLimit());
        $request->addParam('hl.multiValuedSeparatorChar', $component->getMultiValuedSeparatorChar());
        $request->addParam('hl.bs.maxScan', $component->getBoundaryScannerMaxScan());
        $request->addParam('hl.bs.chars', $component->getBoundaryScannerChars());
        $request->addParam('hl.bs.type', $component->getBoundaryScannerType());
        $request->addParam('hl.bs.language', $component->getBoundaryScannerLanguage());
        $request->addParam('hl.bs.country', $component->getBoundaryScannerCountry());

        // set per-field highlighting params
        foreach ($component->getFields() as $field) {
            $this->addFieldParams($field, $request);
        }

        return $request;
    }

    /**
     * Add per-field override options to the request
     *
     * @param  HighlightingField $field
     * @param  Request           $request
     * @return void
     */
    protected function addFieldParams($field, $request)
    {
        $prefix = 'f.' . $field->getName() . '.hl.';
        $request->addParam($prefix . 'snippets', $field->getSnippets());
        $request->addParam($prefix . 'fragsize', $field->getFragSize());
        $request->addParam($prefix . 'mergeContiguous', $field->getMergeContiguous());
        $request->addParam($prefix . 'alternateField', $field->getAlternateField());
        $request->addParam($prefix . 'formatter', $field->getFormatter());
        $request->addParam($prefix . 'simple.pre', $field->getSimplePrefix());
        $request->addParam($prefix . 'simple.post', $field->getSimplePostfix());
        $request->addParam($prefix . 'fragmenter', $field->getFragmenter());
        $request->addParam($prefix . 'useFastVectorHighlighter', $field->getUseFastVectorHighlighter());
    }

}


text:
package germ.command;

/**
 * Svaka komand implementira ovaj intefrace i
 * njegove instance se čuvaju na undo-redo stacku.
 * Svaka komanda zna sebe da uradi u da se "un-uradi"
 */
public interface Command {
	void doCommand();
	void undoCommand();
}


text:
package com.twitter.app

import com.google.common.io.ByteStreams
import com.twitter.conversions.time._
import com.twitter.finagle.util.loadServiceDenied
import com.twitter.util.registry.{Entry, GlobalRegistry, SimpleRegistry}
import com.twitter.util.{Await, Future, FuturePool}
import java.io.{File, InputStream}
import java.net.URL
import java.util
import java.util.Random
import java.util.concurrent
import java.util.concurrent.{Callable, CountDownLatch, ExecutorService, Executors}
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import scala.collection.mutable

// These traits correspond to files in:
// util-app/src/test/resources/META-INF/services

trait LoadServiceRandomInterface
class LoadServiceRandomInterfaceImpl extends LoadServiceRandomInterface
class LoadServiceRandomInterfaceIgnored extends LoadServiceRandomInterface

trait LoadServiceMaybeInterface
class LoadServiceFailingClass extends LoadServiceMaybeInterface {
  throw new RuntimeException("Cannot instanciate this!")
}
class LoadServiceGoodClass extends LoadServiceMaybeInterface

trait LoadServiceMultipleImpls
class LoadServiceMultipleImpls1 extends LoadServiceMultipleImpls
class LoadServiceMultipleImpls2 extends LoadServiceMultipleImpls
class LoadServiceMultipleImpls3 extends LoadServiceMultipleImpls

private object LoadServiceTest {
  val insideLoadSvcLatch: CountDownLatch = new CountDownLatch(1)
  val deadlockLatch: CountDownLatch = new CountDownLatch(1)
}

private object UsesLoadService {
  LoadServiceTest.deadlockLatch.countDown()
  val lsd: Seq[LoadServiceRandomInterface] =
    LoadService[LoadServiceRandomInterface]()
}

trait LoadServiceDeadlock
class LoadServiceDeadlockImpl extends LoadServiceDeadlock {
  LoadServiceTest.insideLoadSvcLatch.countDown()
  LoadServiceTest.deadlockLatch.await()
  val lsd: Seq[LoadServiceRandomInterface] =
    UsesLoadService.lsd
}

@RunWith(classOf[JUnitRunner])
class LoadServiceTest extends FunSuite with MockitoSugar {

  test("LoadService should apply[T] and return a set of instances of T") {
    assert(LoadService[LoadServiceRandomInterface]().nonEmpty)
  }

  test("LoadService should apply[T] and generate the right registry entries") {
    val simple = new SimpleRegistry
    GlobalRegistry.withRegistry(simple) {
      assert(LoadService[LoadServiceRandomInterface]().nonEmpty)
      assert(GlobalRegistry.get.toSet == Set(
        Entry(Seq("loadservice", "com.twitter.app.LoadServiceRandomInterface"), "com.twitter.app.LoadServiceRandomInterfaceImpl")
      ))
    }
  }

  test("LoadService should only load 1 instance of T, even when there's multiple occurence of T") {
    val randomIfaces = LoadService[LoadServiceRandomInterface]()
    assert(randomIfaces.size == 1)
  }

  test("LoadService should recover when seeing an initialization exception") {
    val randomIfaces = LoadService[LoadServiceMaybeInterface]()
    assert(randomIfaces.size == 1)
  }

  test("LoadService should only register successfully initialized classes") {
    val simple = new SimpleRegistry
    GlobalRegistry.withRegistry(simple) {
      LoadService[LoadServiceMaybeInterface]()
      assert(GlobalRegistry.get.toSet == Set(
        Entry(Seq("loadservice", "com.twitter.app.LoadServiceMaybeInterface"), "com.twitter.app.LoadServiceGoodClass")
      ))
    }
  }

  test("LoadService shouldn't fail on un-readable dir") {
    val loader = mock[ClassLoader]
    val buf = mutable.Buffer.empty[ClassPath.LoadServiceInfo]
    val rand = new Random()

    val f = File.createTempFile("tmp", "__utilapp_loadservice" + rand.nextInt(10000))
    f.delete
    if (f.mkdir()) {
      f.setReadable(false)

      new LoadServiceClassPath().browseUri(f.toURI, loader, buf)
      assert(buf.isEmpty)
      f.delete()
    }
  }

  test("LoadService shouldn't fail on un-readable sub-dir") {
    val loader = mock[ClassLoader]
    val buf = mutable.Buffer.empty[ClassPath.LoadServiceInfo]
    val rand = new Random()

    val f = File.createTempFile("tmp", "__utilapp_loadservice" + rand.nextInt(10000))
    f.delete
    if (f.mkdir()) {
      val subDir = new File(f.getAbsolutePath, "subdir")
      subDir.mkdir()
      assert(subDir.exists())
      subDir.setReadable(false)

      new LoadServiceClassPath().browseUri(f.toURI, loader, buf)
      assert(buf.isEmpty)

      subDir.delete()
      f.delete()
    }
  }

  test("LoadService should find services on non URLClassloader") {
    // Note: this test should find the service definitions in HIDDEN-INF/services
    val loader = new MetaInfCodedClassloader(getClass.getClassLoader)
    // Run LoadService in a different thread from the custom classloader
    val clazz: Class[_] = loader.loadClass("com.twitter.app.LoadServiceCallable")
    val executor: ExecutorService = Executors.newSingleThreadExecutor()
    val future: concurrent.Future[Seq[Any]] =
      executor.submit(clazz.newInstance().asInstanceOf[Callable[Seq[Any]]])

    // Get the result
    val impls: Seq[Any] = future.get()
    assert(impls.exists(_.getClass.getName.endsWith("LoadServiceRandomInterfaceIgnored")),
      "Non-URLClassloader found announcer was not discovered"
    )
    executor.shutdown()
  }

  test("LoadService shouldn't fail on self-referencing jar") {
    import java.io._
    import java.util.jar._
    import Attributes.Name._
    val jarFile = File.createTempFile("test", ".jar")
    try {
      val manifest = new Manifest
      val attributes = manifest.getMainAttributes
      attributes.put(MANIFEST_VERSION, "1.0")
      attributes.put(CLASS_PATH, jarFile.getName)
      val jos = new JarOutputStream(new FileOutputStream(jarFile), manifest)
      jos.close()
      val loader = mock[ClassLoader]
      val buf = mutable.Buffer.empty[ClassPath.LoadServiceInfo]
      new LoadServiceClassPath().browseUri(jarFile.toURI, loader, buf)
    } finally {
      jarFile.delete
    }
  }

  test("LoadService shouldn't fail on circular referencing jar") {
    import java.io._
    import java.util.jar._
    import Attributes.Name._
    val jar1 = File.createTempFile("test", ".jar")
    val jar2 = File.createTempFile("test", ".jar")
    try {
      val manifest = new Manifest
      val attributes = manifest.getMainAttributes
      attributes.put(MANIFEST_VERSION, "1.0")
      attributes.put(CLASS_PATH, jar2.getName)
      new JarOutputStream(new FileOutputStream(jar1), manifest).close()
      attributes.put(CLASS_PATH, jar1.getName)
      new JarOutputStream(new FileOutputStream(jar2), manifest).close()
      val loader = mock[ClassLoader]
      val buf = mutable.Buffer.empty[ClassPath.LoadServiceInfo]
      new LoadServiceClassPath().browseUri(jar1.toURI, loader, buf)
    } finally {
      jar1.delete
      jar2.delete
    }
  }

  test("LoadService should respect Denied if provided") {
    val denied1and2 = Set(
      "com.twitter.app.LoadServiceMultipleImpls1",
      "com.twitter.app.LoadServiceMultipleImpls2"
    )
    loadServiceDenied.let(denied1and2) {
      val loaded = LoadService[LoadServiceMultipleImpls]()
      assert(1 == loaded.size)
      assert(classOf[LoadServiceMultipleImpls3] == loaded.head.getClass)
    }
  }

  test("does not deadlock") {
    val f0: Future[Seq[LoadServiceDeadlock]] = FuturePool.unboundedPool {
      // this will be inside of `LoadService.apply` where it
      // will run the `LoadServiceDeadlockImpl` constructor body
      LoadService[LoadServiceDeadlock]()
    }

    // after this latch is tripped, we know the other thread is inside of `LoadService.apply`
    LoadServiceTest.insideLoadSvcLatch.await()

    // now we want to be inside of `UsesLoadService` and try to run `LoadService.apply`
    // while the other thread is still in there.
    val lsds1 = UsesLoadService.lsd
    assert(lsds1.size == 1)

    val lsds0 = Await.result(f0, 5.seconds)
    assert(lsds0.size == 1)
    assert(lsds0.head.getClass == classOf[LoadServiceDeadlockImpl])
  }

}

class LoadServiceCallable extends Callable[Seq[Any]] {
  override def call(): Seq[Any] = LoadService[LoadServiceRandomInterface]()
}

class MetaInfCodedClassloader(parent: ClassLoader) extends ClassLoader(parent) {
  override def loadClass(name: String): Class[_] = {
    if (name.startsWith("com.twitter.app" )) {
      try {
        val path = name.replaceAll("\\.", "/") + ".class"
        val is: InputStream = getClass.getClassLoader.getResourceAsStream(path)
        val buf = ByteStreams.toByteArray(is)

        defineClass(name, buf, 0, buf.length)
      } catch {
        case e: Exception => throw new ClassNotFoundException("Couldn't load class " + name, e)
      }
    } else {
      parent.loadClass(name)
    }
  }

  override def getResources(p1: String): util.Enumeration[URL] = {
    // Totally contrived example classloader that stores "META-INF" as "HIDDEN-INF"
    // Not a good example of real-world issues, but it does the job at hiding the service definition from the
    // com.twitter.app.ClassPath code
    val resources: util.Enumeration[URL] = super.getResources(p1.replace("META-INF", "HIDDEN-INF"))
    if (resources == null) {
      super.getResources(p1)
    } else {
      resources
    }
  }
}


text:
package proj.me.bitframe.helper;

public enum ColorCombination {
        VIBRANT_TO_MUTED(0),
        MUTED_TO_VIBRANT(1);
        final int colorCombo;
        ColorCombination(int colorCombo){
            this.colorCombo = colorCombo;
        }
    }


text:
import copy

import mox
import paramiko
import novaclient

from heat.db import api as db_api
from heat.tests.v1_1 import fakes
from heat.common import template_format
from heat.common import exception
from heat.engine import parser
from heat.engine import resource
from heat.engine import scheduler
from heat.engine import environment
from heat.openstack.common import uuidutils
from heat.tests.common import HeatTestCase
from heat.tests import utils

from ..engine.plugins import rackspace_resource
from ..engine.plugins import cloud_server

wp_template = '''
{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "WordPress",
  "Parameters" : {
    "flavor" : {
      "Description" : "Rackspace Cloud Server flavor",
      "Type" : "String",
      "Default" : "2",
      "AllowedValues" : [ "2", "3", "4", "5", "6", "7", "8" ],
      "ConstraintDescription" : "must be a valid Rackspace Cloud Server flavor"
    },
  },
  "Resources" : {
    "WebServer": {
      "Type": "Rackspace::Cloud::Server",
      "Properties": {
        "image"      : "Fedora 17 (Beefy Miracle)",
        "flavor"         : "2",
        "user_data"       : "wordpress"
      }
    }
  }
}
'''

rsa_key = """-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDibWGom/83F2xYfVylBZhUbREiVlw42X7afUuHzNJuh/5EyhXQ
BmBHjVGL1mxZY4GoISrxIkW1jVmTXbm8FknIlS3jxEOC+xF3IkLBtmZEkFVLOUCv
Fpru1xThFS0L/pRttiTWLm+dsjboCV4qtg/+y30O0RJ5AAFgGkoVs8idrQIDAQAB
AoGAQU/7037r5yBCiGPgzVkHz5KGVrlCcMOL68ood0uFh4yCs6T3FcJBE2KYGxYG
uuIRDEZE9LlGElBrfi6S3MYxEbewITK9Li1cr8K0fJlIbg5PI1MxwiTXzG7i0f8Y
trtZjo/fs8XNSS4xlGWCUgtiNXvLS6wxyDGGbqeh1BmETgECQQDmoPJ3h5kuZguA
o7B+iTaKXqyWPf0ImsZ0UQYBgnEWTaZEh8W0015jP55mndALWA9pmhHJm+BC/Hfe
Kp6jtVyxAkEA+1YctDe62u5pXU/GK8UfDJwi4m1VxUfASrlxh+ALag9knwe6Dlev
EKKIe8R6HZs2zavaJs6dddxHRcIi8rXfvQJAW6octOVwPMDSUY69140x4E1Ay3ZX
29OojRKnEHKIABVcwGA2dGiOW2Qt0RtoVRnrBk32Q+twdy9hdSv7YZX0AQJAVDaj
QYNW2Zp+tWRQa0QORkRer+2gioyjEqaWMsfQK0ZjGaIWJk4c+37qKkZIAHmMYFeP
recW/XHEc8w7t4VXJQJAevSyciBfFcWMZTwlqq8wXNMCRLJt5CxvO4gSO+hPNrDe
gDZkz7KcZC7TkO0NYVRssA6/84mCqx6QHpKaYNG9kg==
-----END RSA PRIVATE KEY-----
"""

class RackspaceCloudServerTest(HeatTestCase):
    def setUp(self):
        super(RackspaceCloudServerTest, self).setUp()
        self.fc = fakes.FakeClient()
        utils.setup_dummy_db()
        # Test environment may not have pyrax client library installed and if
        # pyrax is not installed resource class would not be registered.
        # So register resource provider class explicitly for unit testing.
        resource._register_class("Rackspace::Cloud::Server",
                                 cloud_server.CloudServer)

        f2 = self.m.CreateMockAnything()
        f2.id = '2'
        f3 = self.m.CreateMockAnything()
        f3.id = '3'
        f4 = self.m.CreateMockAnything()
        f4.id = '4'
        f5 = self.m.CreateMockAnything()
        f5.id = '5'
        f6 = self.m.CreateMockAnything()
        f6.id = '6'
        f7 = self.m.CreateMockAnything()
        f7.id = '7'
        f8 = self.m.CreateMockAnything()
        f8.id = '8'
        self.flavors = [f2, f3, f4, f5, f6, f7, f8]

    def _setup_test_stack(self, stack_name):
        t = template_format.parse(wp_template)
        template = parser.Template(t)
        stack = parser.Stack(utils.dummy_context(), stack_name, template,
                             environment.Environment({'flavor': '2'}),
                             stack_id=uuidutils.generate_uuid())
        return (t, stack)

    def _mock_ssh_sftp(self):
        # SSH
        self.m.StubOutWithMock(paramiko, "SSHClient")
        self.m.StubOutWithMock(paramiko, "MissingHostKeyPolicy")
        ssh = self.m.CreateMockAnything()
        paramiko.SSHClient().AndReturn(ssh)
        paramiko.MissingHostKeyPolicy()
        ssh.set_missing_host_key_policy(None)
        ssh.connect(mox.IgnoreArg(),
                    key_filename=mox.IgnoreArg(),
                    username='root')
        stdin = self.m.CreateMockAnything()
        stdout = self.m.CreateMockAnything()
        stderr = self.m.CreateMockAnything()
        stdout.read().AndReturn("stdout")
        stderr.read().AndReturn("stderr")
        ssh.exec_command(mox.IgnoreArg()).AndReturn((stdin, stdout, stderr))

        # SFTP
        self.m.StubOutWithMock(paramiko, "Transport")
        transport = self.m.CreateMockAnything()
        paramiko.Transport((mox.IgnoreArg(), 22)).AndReturn(transport)
        transport.connect(hostkey=None, username="root", pkey=mox.IgnoreArg())
        sftp = self.m.CreateMockAnything()
        self.m.StubOutWithMock(paramiko, "SFTPClient")
        paramiko.SFTPClient.from_transport(transport).AndReturn(sftp)
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()
        sftp_file = self.m.CreateMockAnything()
        sftp.open(mox.IgnoreArg(), 'w').AndReturn(sftp_file)
        sftp_file.write(mox.IgnoreArg())
        sftp_file.close()

    def _setup_test_cs(self, return_server, name):
        stack_name = '%s_stack' % name
        (t, stack) = self._setup_test_stack(stack_name)

        cs_name = 'Fedora 17 (Beefy Miracle)'
        t['Resources']['WebServer']['Properties']['image'] = '1'
        t['Resources']['WebServer']['Properties']['flavor'] = '2'

        cs = cloud_server.CloudServer('%s_name' % name,
                                      t['Resources']['WebServer'], stack)
        cs._private_key = rsa_key
        cs.t = cs.stack.resolve_runtime_data(cs.t)

        flavor = t['Resources']['WebServer']['Properties']['flavor']

        self.m.StubOutWithMock(self.fc.servers, 'create')
        self.fc.servers.create(utils.PhysName(stack_name, cs.name),
                               "1", flavor,
                               files=mox.IgnoreArg()).AndReturn(return_server)
        return_server.adminPass = "foobar"

        self.m.StubOutWithMock(cloud_server.CloudServer, 'script')
        cloud_server.CloudServer.script = "foobar"

        self.m.StubOutWithMock(rackspace_resource.RackspaceResource, "nova")
        rackspace_resource.RackspaceResource.nova().MultipleTimes()\
                                                   .AndReturn(self.fc)

        self._mock_ssh_sftp()
        return cs

    def _create_test_cs(self, return_server, name):
        cs = self._setup_test_cs(return_server, name)

        self.m.ReplayAll()
        scheduler.TaskRunner(cs.create)()
        return cs

    def _update_test_cs(self, return_server, name):
        self._mock_ssh_sftp()
        self.m.StubOutWithMock(rackspace_resource.RackspaceResource, "nova")
        rackspace_resource.RackspaceResource.nova().MultipleTimes()\
                                                   .AndReturn(self.fc)

    def test_cs_create(self):
        return_server = self.fc.servers.list()[1]
        cs = self._create_test_cs(return_server, 'test_cs_create')
        # this makes sure the auto increment worked on cloud server creation
        self.assertTrue(cs.id > 0)

        expected_public = return_server.networks['public'][0]
        expected_private = return_server.networks['private'][0]
        self.assertEqual(cs.FnGetAtt('PublicIp'), expected_public)
        self.assertEqual(cs.FnGetAtt('PrivateIp'), expected_private)
        self.assertEqual(cs.FnGetAtt('PublicDnsName'), expected_public)
        self.assertEqual(cs.FnGetAtt('PrivateDnsName'), expected_public)

        self.m.VerifyAll()

    def test_cs_create_with_image_name(self):
        return_server = self.fc.servers.list()[1]
        cs = self._setup_test_cs(return_server, 'test_cs_create_image_id')

        self.m.ReplayAll()
        scheduler.TaskRunner(cs.create)()

        # this makes sure the auto increment worked on cloud server creation
        self.assertTrue(cs.id > 0)

        expected_public = return_server.networks['public'][0]
        expected_private = return_server.networks['private'][0]
        self.assertEqual(cs.FnGetAtt('PublicIp'), expected_public)
        self.assertEqual(cs.FnGetAtt('PrivateIp'), expected_private)
        self.assertEqual(cs.FnGetAtt('PublicDnsName'), expected_public)
        self.assertEqual(cs.FnGetAtt('PrivateDnsName'), expected_public)
        self.assertRaises(exception.InvalidTemplateAttribute,
                          cs.FnGetAtt, 'foo')
        self.m.VerifyAll()

    def test_cs_create_image_name_err(self):
        stack_name = 'test_cs_create_image_name_err_stack'
        (t, stack) = self._setup_test_stack(stack_name)

        # create a cloud server with non exist image name
        t['Resources']['WebServer']['Properties']['image'] = 'Slackware'

        # Mock flavors
        self.m.StubOutWithMock(cloud_server.CloudServer, "flavors")
        cloud_server.CloudServer.flavors.__contains__('2').AndReturn(True)
        cloud_server.CloudServer.script = None
        self.m.ReplayAll()

        cs = cloud_server.CloudServer('cs_create_image_err',
                                      t['Resources']['WebServer'], stack)

        self.assertEqual({'Error': "user_data/metadata are not supported with "
                          "Slackware."},
                         cs.validate())
        self.m.VerifyAll()

    def test_cs_create_image_name_okay(self):
        stack_name = 'test_cs_create_image_name_err_stack'
        (t, stack) = self._setup_test_stack(stack_name)

        # create a cloud server with non exist image name
        t['Resources']['WebServer']['Properties']['image'] = 'Slackware'
        t['Resources']['WebServer']['Properties']['user_data'] = ''

        # Mock flavors
        self.m.StubOutWithMock(cloud_server.CloudServer, "flavors")
        cloud_server.CloudServer.flavors.__contains__('2').AndReturn(True)
        cloud_server.CloudServer.script = None
        self.m.ReplayAll()

        cs = cloud_server.CloudServer('cs_create_image_err',
                                      t['Resources']['WebServer'], stack)

        self.assertEqual(None, cs.validate())
        self.m.VerifyAll()

    def test_cs_create_flavor_err(self):
        """validate() should throw an if the flavor is invalid."""
        stack_name = 'test_cs_create_flavor_err_stack'
        (t, stack) = self._setup_test_stack(stack_name)

        # create a cloud server with non exist image name
        t['Resources']['WebServer']['Properties']['flavor'] = '1'

        # Mock flavors
        self.m.StubOutWithMock(cloud_server.CloudServer, "flavors")
        flavors = ['2', '3', '4', '5', '6', '7', '8']
        cloud_server.CloudServer.flavors = flavors
        self.m.ReplayAll()

        cs = cloud_server.CloudServer('cs_create_flavor_err',
                                      t['Resources']['WebServer'], stack)

        self.assertEqual({'Error': "flavor not found."}, cs.validate())

        self.m.VerifyAll()

    def test_cs_create_delete(self):
        return_server = self.fc.servers.list()[1]
        cs = self._create_test_cs(return_server,
                                  'test_cs_create_delete')
        cs.resource_id = 1234

        # this makes sure the auto-increment worked on cloud server creation
        self.assertTrue(cs.id > 0)

        self.m.StubOutWithMock(self.fc.client, 'get_servers_1234')
        get = self.fc.client.get_servers_1234
        get().AndRaise(novaclient.exceptions.NotFound(404))
        mox.Replay(get)

        scheduler.TaskRunner(cs.delete)()
        self.assertTrue(cs.resource_id is None)
        self.assertEqual(cs.state, (cs.DELETE, cs.COMPLETE))
        self.m.VerifyAll()

    def test_cs_update_metadata(self):
        return_server = self.fc.servers.list()[1]
        cs = self._create_test_cs(return_server, 'test_cs_metadata_update')
        self.m.UnsetStubs()
        self._update_test_cs(return_server, 'test_cs_metadata_update')
        self.m.ReplayAll()
        update_template = copy.deepcopy(cs.t)
        update_template['Metadata'] = {'test': 123}
        scheduler.TaskRunner(cs.update, update_template)()
        self.assertEqual(cs.metadata, {'test': 123})

    def test_cs_update_replace(self):
        return_server = self.fc.servers.list()[1]
        cs = self._create_test_cs(return_server, 'test_cs_update')

        update_template = copy.deepcopy(cs.t)
        update_template['Notallowed'] = {'test': 123}
        updater = scheduler.TaskRunner(cs.update, update_template)
        self.assertRaises(resource.UpdateReplace, updater)

    def test_cs_update_properties(self):
        return_server = self.fc.servers.list()[1]
        cs = self._create_test_cs(return_server, 'test_cs_update')

        update_template = copy.deepcopy(cs.t)
        update_template['Properties']['user_data'] = 'mustreplace'
        updater = scheduler.TaskRunner(cs.update, update_template)
        self.assertRaises(resource.UpdateReplace, updater)

    def test_cs_status_build(self):
        return_server = self.fc.servers.list()[0]
        cs = self._setup_test_cs(return_server, 'test_cs_status_build')
        cs.resource_id = 1234

        # Bind fake get method which cs.check_create_complete will call
        def activate_status(server):
            server.status = 'ACTIVE'
        return_server.get = activate_status.__get__(return_server)
        self.m.ReplayAll()

        scheduler.TaskRunner(cs.create)()
        self.assertEqual(cs.state, (cs.CREATE, cs.COMPLETE))

    def test_cs_status_hard_reboot(self):
        self._test_cs_status_not_build_active('HARD_REBOOT')

    def test_cs_status_password(self):
        self._test_cs_status_not_build_active('PASSWORD')

    def test_cs_status_reboot(self):
        self._test_cs_status_not_build_active('REBOOT')

    def test_cs_status_rescue(self):
        self._test_cs_status_not_build_active('RESCUE')

    def test_cs_status_resize(self):
        self._test_cs_status_not_build_active('RESIZE')

    def test_cs_status_revert_resize(self):
        self._test_cs_status_not_build_active('REVERT_RESIZE')

    def test_cs_status_shutoff(self):
        self._test_cs_status_not_build_active('SHUTOFF')

    def test_cs_status_suspended(self):
        self._test_cs_status_not_build_active('SUSPENDED')

    def test_cs_status_verify_resize(self):
        self._test_cs_status_not_build_active('VERIFY_RESIZE')

    def _test_cs_status_not_build_active(self, uncommon_status):
        return_server = self.fc.servers.list()[0]
        cs = self._setup_test_cs(return_server, 'test_cs_status_build')
        cs.resource_id = 1234

        # Bind fake get method which cs.check_create_complete will call
        def activate_status(server):
            if hasattr(server, '_test_check_iterations'):
                server._test_check_iterations += 1
            else:
                server._test_check_iterations = 1
            if server._test_check_iterations == 1:
                server.status = uncommon_status
            if server._test_check_iterations > 2:
                server.status = 'ACTIVE'
        return_server.get = activate_status.__get__(return_server)
        self.m.ReplayAll()

        scheduler.TaskRunner(cs.create)()
        self.assertEqual(cs.state, (cs.CREATE, cs.COMPLETE))

        self.m.VerifyAll()

    def mock_get_ip(self, cs):
        self.m.UnsetStubs()
        self.m.StubOutWithMock(cloud_server.CloudServer, "server")
        cloud_server.CloudServer.server = cs
        self.m.ReplayAll()

    def test_cs_get_ip(self):
        stack_name = 'test_cs_get_ip_err'
        (t, stack) = self._setup_test_stack(stack_name)
        cs = cloud_server.CloudServer('cs_create_image_err',
                                      t['Resources']['WebServer'],
                                      stack)
        cs.addresses = {'public': [{'version': 4, 'addr': '4.5.6.7'},
                                   {'version': 6, 'addr': 'fake:ip::6'}],
                        'private': [{'version': 4, 'addr': '10.13.12.13'}]}
        self.mock_get_ip(cs)
        self.assertEqual(cs.public_ip, '4.5.6.7')
        self.mock_get_ip(cs)
        self.assertEqual(cs.private_ip, '10.13.12.13')

        cs.addresses = {'public': [],
                        'private': []}
        self.mock_get_ip(cs)
        self.assertRaises(exception.Error, cs._get_ip, 'public')

    def test_private_key(self):
        stack_name = 'test_private_key'
        (t, stack) = self._setup_test_stack(stack_name)
        cs = cloud_server.CloudServer('cs_private_key',
                                      t['Resources']['WebServer'],
                                      stack)

        # This gives the fake cloud server an id and created_time attribute
        cs._store_or_update(cs.CREATE, cs.IN_PROGRESS, 'test_store')

        cs.private_key = 'fake private key'
        rs = db_api.resource_get_by_name_and_stack(None,
                                                   'cs_private_key',
                                                   stack.id)
        encrypted_key = rs.data[0]['value']
        self.assertNotEqual(encrypted_key, "fake private key")
        decrypted_key = cs.private_key
        self.assertEqual(decrypted_key, "fake private key")


text:
package cluster

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/pkg/errors"
	"github.com/rancher/norman/httperror"
	"github.com/rancher/norman/types"
	"github.com/rancher/rancher/pkg/controllers/user/cis"
	v3 "github.com/rancher/types/apis/management.cattle.io/v3"
	"github.com/rancher/types/namespace"
	"github.com/sirupsen/logrus"
	kerrors "k8s.io/apimachinery/pkg/api/errors"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func (a ActionHandler) runCisScan(actionName string, action *types.Action, apiContext *types.APIContext) error {
	var err error

	canUpdateClusterFn := func(apiContext *types.APIContext) bool {
		cluster := map[string]interface{}{
			"id": apiContext.ID,
		}
		return apiContext.AccessControl.CanDo(v3.ClusterGroupVersionKind.Group, v3.ClusterResource.Name, "update", apiContext, cluster, apiContext.Schema) == nil
	}

	canUpdateCluster := canUpdateClusterFn(apiContext)
	logrus.Debugf("user: %v, canUpdateCluster: %v", apiContext.Request.Header.Get("Impersonate-User"), canUpdateCluster)
	if !canUpdateCluster {
		return httperror.NewAPIError(httperror.PermissionDenied, "can not run security scan")
	}

	data, err := ioutil.ReadAll(apiContext.Request.Body)
	if err != nil {
		return errors.Wrap(err, "reading request body error")
	}

	cisScanConfig := &v3.CisScanConfig{}
	if err = json.Unmarshal(data, cisScanConfig); err != nil {
		return errors.Wrap(err, "unmarshaling input error")
	}

	cluster, err := a.ClusterClient.Get(apiContext.ID, v1.GetOptions{})
	if err != nil {
		return httperror.WrapAPIError(err, httperror.NotFound,
			fmt.Sprintf("cluster with id %v doesn't exist", apiContext.ID))
	}

	if cluster.Spec.WindowsPreferedCluster {
		return httperror.WrapAPIError(err, httperror.InvalidAction,
			fmt.Sprintf("cannot run scan on a windows cluster"))
	}
	if cluster.DeletionTimestamp != nil {
		return httperror.NewAPIError(httperror.InvalidType,
			fmt.Sprintf("cluster with id %v is being deleted", apiContext.ID))
	}
	if !v3.ClusterConditionReady.IsTrue(cluster) {
		return httperror.WrapAPIError(err, httperror.ClusterUnavailable,
			fmt.Sprintf("cluster not ready"))
	}
	if cluster.Status.CurrentCisRunName != "" {
		return httperror.WrapAPIError(err, httperror.Conflict,
			fmt.Sprintf("CIS scan already running on cluster"))
	}

	if cisScanConfig.OverrideBenchmarkVersion != "" {
		_, err := a.CisBenchmarkVersionLister.Get(namespace.GlobalNamespace, cisScanConfig.OverrideBenchmarkVersion)
		if err != nil {
			if kerrors.IsNotFound(err) {
				return httperror.WrapAPIError(err, httperror.InvalidOption,
					fmt.Sprintf("invalid override benchmark version specified"))
			}
			logrus.Errorf("error fetching cis benchmark version %v: %v", cisScanConfig.OverrideBenchmarkVersion, err)
			return httperror.WrapAPIError(err, httperror.ServerError,
				fmt.Sprintf("error fetching cis benchmark version %v", cisScanConfig.OverrideBenchmarkVersion))
		}
	}
	_, _, err = cis.GetBenchmarkVersionToUse(cisScanConfig.OverrideBenchmarkVersion,
		cluster.Spec.RancherKubernetesEngineConfig.Version,
		a.CisConfigLister, a.CisConfigClient,
		a.CisBenchmarkVersionLister, a.CisBenchmarkVersionClient,
	)
	if err != nil {
		return httperror.NewAPIError(httperror.MethodNotAllowed, err.Error())
	}

	isManual := true
	cisScan, err := cis.LaunchScan(
		isManual,
		cisScanConfig,
		cluster,
		a.ClusterClient,
		a.ClusterScanClient,
	)
	if err != nil {
		return httperror.NewAPIError(httperror.ServerError, err.Error())
	}
	cisScanJSON, err := json.Marshal(cisScan)
	if err != nil {
		return httperror.WrapAPIError(err, httperror.ServerError,
			fmt.Sprintf("failed to marshal cis scan object"))
	}

	logrus.Infof("CIS scan requested for cluster: %v", cluster.Name)
	apiContext.Response.Header().Set("Content-Type", "application/json")
	http.ServeContent(apiContext.Response, apiContext.Request, "clusterScan", time.Now(), bytes.NewReader(cisScanJSON))
	return nil
}


text:
namespace IronJS.Tests.UnitTests.Sputnik.Conformance.NativeECMAScriptObjects.StringObjects.PropertiesOfTheStringPrototypeObject
{
    using System;
    using NUnit.Framework;

    [TestFixture]
    public class StringPrototypeCharAtTests : SputnikTestFixture
    {
        public StringPrototypeCharAtTests()
            : base(@"Conformance\15_Native_ECMA_Script_Objects\15.5_String_Objects\15.5.4_Properties_of_the_String_Prototype_Object\15.5.4.4_String.prototype.charAt")
        {
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 13.2")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A1.1.js", Description = "String.prototype.charAt() can accept many arguments")]
        public void StringPrototypeCharAtCanAcceptManyArguments(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A1_T1.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T10.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T2.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T3.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T4.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T5.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T6.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T7.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T8.js", Description = "String.prototype.charAt(pos)")]
        [TestCase("S15.5.4.4_A1_T9.js", Description = "String.prototype.charAt(pos)")]
        public void StringPrototypeCharAtPos(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A10.js", Description = "The String.prototype.charAt.length property has the attribute ReadOnly")]
        public void TheStringPrototypeCharAtLengthPropertyHasTheAttributeReadOnly(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A11.js", Description = "The length property of the charAt method is 1")]
        public void TheLengthPropertyOfTheCharAtMethodIs1(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A2.js", Description = "When String.prototype.charAt(pos) calls if ToInteger(pos) less than 0 the empty string returns")]
        public void WhenStringPrototypeCharAtPosCallsIfToIntegerPosLessThan0TheEmptyStringReturns(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A3.js", Description = "When String.prototype.charAt(pos) calls if ToInteger(pos) not less than ToString(this value) the empty string returns")]
        public void WhenStringPrototypeCharAtPosCallsIfToIntegerPosNotLessThanToStringThisValueTheEmptyStringReturns(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A4_T1.js", Description = "If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1)")]
        [TestCase("S15.5.4.4_A4_T2.js", Description = "If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1)")]
        [TestCase("S15.5.4.4_A4_T3.js", Description = "If pos is a value of Number type that is an integer, then the result of x.charAt(pos) is equal to the result of x.substring(pos, pos+1)")]
        public void IfPosIsAValueOfNumberTypeThatIsAnIntegerThenTheResultOfXCharAtPosIsEqualToTheResultOfXSubstringPosPos1(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A5.js", Description = "When String.prototype.charAt(pos) calls first calls ToString, giving it the this value as its argument")]
        public void WhenStringPrototypeCharAtPosCallsFirstCallsToStringGivingItTheThisValueAsItsArgument(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 13.2")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A6.js", Description = "String.prototype.charAt has not prototype property")]
        public void StringPrototypeCharAtHasNotPrototypeProperty(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 13.2")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A7.js", Description = "String.prototype.charAt can\'t be used as constructor")]
        public void StringPrototypeCharAtCanTBeUsedAsConstructor(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A8.js", Description = "The String.prototype.charAt.length property has the attribute DontEnum")]
        public void TheStringPrototypeCharAtLengthPropertyHasTheAttributeDontEnum(string file)
        {
            RunFile(file);
        }

        [Test]
        [Category("Sputnik Conformance")]
        [Category("ECMA 15.5.4.4")]
        [TestCase("S15.5.4.4_A9.js", Description = "The String.prototype.charAt.length property has the attribute DontDelete")]
        public void TheStringPrototypeCharAtLengthPropertyHasTheAttributeDontDelete(string file)
        {
            RunFile(file);
        }
    }
}


text:
require 'generator/exercise_case'

class SpaceAgeCase < Generator::ExerciseCase
  def workload
    [
      "age = SpaceAge.new(#{underscore(seconds)})\n",
      "assert_in_delta #{expected}, age.on_#{planet.downcase}, DELTA\n"
    ].join
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Arthopyrenia effugiens Müll. Arg.

### Remarks
null


text:
package com.intellij.ui;

import com.intellij.ide.BrowserUtil;
import com.intellij.ide.PrivacyPolicy;
import com.intellij.idea.Main;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ex.ApplicationEx;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.SwingHelper;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.awt.AWTAccessor;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.StyleSheet;
import java.awt.*;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Locale;

import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

/**
 * @author yole
 */
public class AppUIUtil {
  private static final String VENDOR_PREFIX = "jetbrains-";

  public static void updateWindowIcon(@NotNull Window window) {
    window.setIconImages(getAppIconImages());
  }

  @SuppressWarnings({"UnnecessaryFullyQualifiedName", "deprecation"})
  private static List<Image> getAppIconImages() {
    ApplicationInfoEx appInfo = ApplicationInfoImpl.getShadowInstance();
    List<Image> images = ContainerUtil.newArrayListWithCapacity(3);

    if (SystemInfo.isUnix) {//MacOS is Unix too
      String bigIconUrl = appInfo.getBigIconUrl();
      if (bigIconUrl != null) {
        images.add(com.intellij.util.ImageLoader.loadFromResource(bigIconUrl));
      }
    }

    images.add(com.intellij.util.ImageLoader.loadFromResource(appInfo.getIconUrl()));
    images.add(com.intellij.util.ImageLoader.loadFromResource(appInfo.getSmallIconUrl()));
    for (int i = 0; i < images.size(); i++) {
      Image image = images.get(i);
      if (image instanceof JBHiDPIScaledImage) {
        images.set(i, ((JBHiDPIScaledImage)image).getDelegate());
      }
    }
    return images;
  }

  public static void invokeLaterIfProjectAlive(@NotNull Project project, @NotNull Runnable runnable) {
    final Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
      runnable.run();
    }
    else {
      application.invokeLater(runnable, o -> !project.isOpen() || project.isDisposed());
    }
  }

  public static void invokeOnEdt(Runnable runnable) {
    invokeOnEdt(runnable, null);
  }

  public static void invokeOnEdt(Runnable runnable, @Nullable Condition expired) {
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread()) {
      //noinspection unchecked
      if (expired == null || !expired.value(null)) {
        runnable.run();
      }
    }
    else if (expired == null) {
      application.invokeLater(runnable);
    }
    else {
      application.invokeLater(runnable, expired);
    }
  }

  public static void updateFrameClass() {
    try {
      final Toolkit toolkit = Toolkit.getDefaultToolkit();
      final Class<? extends Toolkit> aClass = toolkit.getClass();
      if ("sun.awt.X11.XToolkit".equals(aClass.getName())) {
        ReflectionUtil.setField(aClass, toolkit, null, "awtAppClassName", getFrameClass());
      }
    }
    catch (Exception ignore) { }
  }

  public static String getFrameClass() {
    String name = ApplicationNamesInfo.getInstance().getProductName().toLowerCase(Locale.US);
    String wmClass = VENDOR_PREFIX + name.replace(' ', '-');
    if ("true".equals(System.getProperty("idea.debug.mode"))) {
      wmClass += "-debug";
    }
    return PlatformUtils.isCommunityEdition() ? wmClass + "-ce" : wmClass;
  }

  public static void registerBundledFonts() {
    if (SystemProperties.getBooleanProperty("ide.register.bundled.fonts", true)) {
      registerFont("/fonts/Inconsolata.ttf");
      registerFont("/fonts/SourceCodePro-Regular.ttf");
      registerFont("/fonts/SourceCodePro-Bold.ttf");
      registerFont("/fonts/SourceCodePro-It.ttf");
      registerFont("/fonts/SourceCodePro-BoldIt.ttf");
      registerFont("/fonts/FiraCode-Regular.ttf");
      registerFont("/fonts/FiraCode-Bold.ttf");
      registerFont("/fonts/FiraCode-Light.ttf");
      registerFont("/fonts/FiraCode-Medium.ttf");
      registerFont("/fonts/FiraCode-Retina.ttf");
    }
  }

  private static void registerFont(@NonNls String name) {
    URL url = AppUIUtil.class.getResource(name);
    if (url == null) {
      Logger.getInstance(AppUIUtil.class).warn("Resource missing: " + name);
      return;
    }

    try {
      InputStream is = url.openStream();
      try {
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(font);
      }
      finally {
        is.close();
      }
    }
    catch (Throwable t) {
      Logger.getInstance(AppUIUtil.class).warn("Cannot register font: " + url, t);
    }
  }

  public static void hideToolWindowBalloon(@NotNull String id, @NotNull Project project) {
    invokeLaterIfProjectAlive(project, () -> {
      Balloon balloon = ToolWindowManager.getInstance(project).getToolWindowBalloon(id);
      if (balloon != null) {
        balloon.hide();
      }
    });
  }

  private static final int MIN_ICON_SIZE = 32;

  @Nullable
  public static String findIcon(@NotNull String iconsPath) {
    String[] childFiles = ObjectUtils.notNull(new File(iconsPath).list(), ArrayUtil.EMPTY_STRING_ARRAY);

    // 1. look for .svg icon
    for (String child : childFiles) {
      if (child.endsWith(".svg")) {
        return iconsPath + '/' + child;
      }
    }

    // 2. look for .png icon of max size
    int best = MIN_ICON_SIZE - 1;
    String iconPath = null;
    for (String child : childFiles) {
      if (child.endsWith(".png")) {
        String path = iconsPath + '/' + child;
        Icon icon = new ImageIcon(path);
        int size = icon.getIconHeight();
        if (size > best && size == icon.getIconWidth()) {
          best = size;
          iconPath = path;
        }
      }
    }

    return iconPath;
  }

  public static void showPrivacyPolicy() {
    if (ApplicationInfoImpl.getShadowInstance().isVendorJetBrains()) {
      Pair<PrivacyPolicy.Version, String> policy = PrivacyPolicy.getContent();
      if (!PrivacyPolicy.isVersionAccepted(policy.getFirst())) {
        try {
          SwingUtilities.invokeAndWait(() -> showPrivacyPolicyAgreement(policy.getSecond()));
          PrivacyPolicy.setVersionAccepted(policy.getFirst());
        }
        catch (Exception e) {
          Logger.getInstance(AppUIUtil.class).warn(e);
        }
      }
    }
  }

  /**
   * @param htmlText Updated version of Privacy Policy text if any.
   *                 If it's {@code null}, the standard text from bundled resources would be used.
   */
  public static void showPrivacyPolicyAgreement(@NotNull String htmlText) {
    DialogWrapper dialog = new DialogWrapper(true) {
      @Nullable
      @Override
      protected JComponent createCenterPanel() {
        JPanel centerPanel = new JPanel(new BorderLayout(JBUI.scale(5), JBUI.scale(5)));
        JEditorPane viewer = SwingHelper.createHtmlViewer(true, null, JBColor.WHITE, JBColor.BLACK);
        viewer.setFocusable(true);
        viewer.addHyperlinkListener(new HyperlinkAdapter() {
          @Override
          protected void hyperlinkActivated(HyperlinkEvent e) {
            URL url = e.getURL();
            if (url != null) {
              BrowserUtil.browse(url);
            }
            else {
              SwingHelper.scrollToReference(viewer, e.getDescription());
            }
          }
        });
        viewer.setText(htmlText);
        StyleSheet styleSheet = ((HTMLDocument)viewer.getDocument()).getStyleSheet();
        styleSheet.addRule("body {font-family: \"Segoe UI\", Tahoma, sans-serif;}");
        styleSheet.addRule("body {margin-top:0;padding-top:0;}");
        styleSheet.addRule("body {font-size:" + JBUI.scaleFontSize(13) + "pt;}");
        styleSheet.addRule("h2, em {margin-top:" + JBUI.scaleFontSize(20) + "pt;}");
        styleSheet.addRule("h1, h2, h3, p, h4, em {margin-bottom:0;padding-bottom:0;}");
        styleSheet.addRule("p, h1 {margin-top:0;padding-top:"+JBUI.scaleFontSize(6)+"pt;}");
        styleSheet.addRule("li {margin-bottom:" + JBUI.scaleFontSize(6) + "pt;}");
        styleSheet.addRule("h2 {margin-top:0;padding-top:"+JBUI.scaleFontSize(13)+"pt;}");
        viewer.setCaretPosition(0);
        viewer.setBorder(JBUI.Borders.empty(0, 5, 5, 5));
        centerPanel.add(new JLabel("Please read and accept these terms and conditions:"), BorderLayout.NORTH);
        centerPanel.add(new JBScrollPane(viewer, VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER), BorderLayout.CENTER);
        return centerPanel;
      }

      @Override
      protected void createDefaultActions() {
        super.createDefaultActions();
        init();
        setOKButtonText("Accept");
        setCancelButtonText("Reject and Exit");
        setAutoAdjustable(false);
      }

      @Override
      public void doCancelAction() {
        super.doCancelAction();
        ApplicationEx application = ApplicationManagerEx.getApplicationEx();
        if (application == null) {
          System.exit(Main.PRIVACY_POLICY_REJECTION);
        }
        else {
          ((ApplicationImpl)application).exit(true, true, false);
        }
      }
    };
    dialog.setModal(true);
    dialog.setTitle(ApplicationNamesInfo.getInstance().getFullProductName() + " Privacy Policy Agreement");
    dialog.setSize(JBUI.scale(509), JBUI.scale(395));
    dialog.show();
  }

  /**
   * Targets the component to a (screen) device before showing.
   * In case the component is already a part of UI hierarchy (and is thus bound to a device)
   * the method does nothing.
   *

   * The prior targeting to a device is required when there's a need to calculate preferred
   * size of a compound component (such as JEditorPane, for instance) which is not yet added
   * to a hierarchy. The calculation in that case may involve device-dependent metrics
   * (such as font metrics) and thus should refer to a particular device in multi-monitor env.
   *

   * Note that if after calling this method the component is added to another hierarchy,
   * bound to a different device, AWT will throw IllegalArgumentException. To avoid that,
   * the device should be reset by calling {@code targetToDevice(comp, null)}.
   *
   * @param target the component representing the UI hierarchy and the target device
   * @param comp the component to target
   */
  public static void targetToDevice(@NotNull Component comp, @Nullable Component target) {
    if (comp.isShowing()) return;
    GraphicsConfiguration gc = target != null ? target.getGraphicsConfiguration() : null;
    AWTAccessor.getComponentAccessor().setGraphicsConfiguration(comp, gc);
  }
}


text:
package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import service.HouseService;
import service.HouseServiceImpl;
import util.PagenationSupport;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import entity.District;
import entity.House;
import entity.HouseType;
import entity.Street;
import entity.User;

public class HouseAction extends ActionSupport {
	HouseService houseService = new HouseServiceImpl();
	private PagenationSupport pagenaton;
	private int pagenow;
	private int id;
	private House house;
	private List<Street> streets;
	private List<HouseType> types;
	private List<District> districts;

	private File images;
	private String imagesContentType;
	private String imagesFileName;
	private String savePath="/images";

	public String upload() throws Exception {
		System.out.println("getImagesContentType()="+getImagesContentType());
		System.out.println("images.getName()=="+getImagesFileName());
		System.out.println("images!=null=="+images!=null);
		InputStream is=new FileInputStream(getImages());
		OutputStream os=new FileOutputStream(getSavePath()+"\\"+getImagesFileName());
		byte[] buffer = new byte[1024];
        while(is.read(buffer)>0){
        		os.write(buffer);
        }
		return "updloadSUCC";

	}

	// 分页显示所有房屋
	@SuppressWarnings("unchecked")
	public String getHousesByPage() {
		Map<String, Object> factor = houseService.getHouseFactor();
		streets = (List<Street>) factor.get("streets");
		types = (List<HouseType>) factor.get("housetypes");
		districts = (List<District>) factor.get("districts");
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put("streets", streets);
		session.put("types", types);
		session.put("districts", districts);
		pagenaton = houseService.getHousesByPage(pagenow, pagenaton.PageSize);
		return "houselist";
	}
	public static Logger log=Logger.getLogger(HouseAction.class);

	// 新增房屋
	public String addHouse()throws IOException {

		Map<String,Object> session=ActionContext.getContext().getSession();
			User u= (User)session.get("user");
			house.setUser(u);
			System.out.println("u.getName()==="+u.getName());
			System.out.println("house.getHousetype().getId()==="+house.getHousetype().getId());
			System.out.println("house.getStreet().getId()==="+house.getStreet().getId());
			System.out.println("images.getName()=="+imagesFileName);
			System.out.println("images!=null=="+images!=null);
		if(images!=null){
			InputStream is=new FileInputStream(images);
			//上传图片目录;设置图片名称:上传时间+用户名+image.getName().
			Date date=new Date(System.currentTimeMillis());
			String strDate=new SimpleDateFormat("yyyyMMddhhmmss").format(date);
			String fileName=strDate+u.getName()+imagesFileName;
			System.out.println("上传的图片:"+imagesFileName+"存储到:"+getSavePath()+fileName);
			log.info("上传的图片:"+images.getName()+"存储到:"+getSavePath()+fileName);
			//设置存储目标文件
			File toFile=new File(getSavePath(),fileName);
			OutputStream os=new FileOutputStream(toFile);
			 //设置缓存
	        byte[] buffer = new byte[1024];
	        while(is.read(buffer)>0){
	        	os.write(buffer);
	        }
	        is.close();
	        os.close();
	        house.setPic(fileName);
		}
			houseService.save(house);
		return "houseAddSuccess";
	}

	// 查询district下的所有street
	public String getStreetByDistrict() throws IOException {
		streets = houseService.getStreetByDistrictId(id);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/xml");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.print("<streets>");
		for (Street s : streets) {
			out.print("<street>" + "<streetid>" + s.getId() + "</streetid>"
					+ "<streetname>" + s.getStreet_name() + "</streetname>"
					+ "</street>");
		}
		out.println("</streets>");
		System.out.println(out);
		return null;
	}

	// 根据ID查询房屋明细
	public String getHouseDetail() {
		house = houseService.getHouseById(id);
		return "houseDetail";
	}

	public PagenationSupport getPagenaton() {
		return pagenaton;
	}

	public void setPagenaton(PagenationSupport pagenaton) {
		this.pagenaton = pagenaton;
	}

	public int getPagenow() {
		return pagenow;
	}

	public void setPagenow(int pagenow) {
		this.pagenow = pagenow;
	}

	public List<Street> getStreets() {
		return streets;
	}

	public void setStreets(List<Street> streets) {
		this.streets = streets;
	}

	public List<HouseType> getTypes() {
		return types;
	}

	public void setTypes(List<HouseType> types) {
		this.types = types;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public House getHouse() {
		return house;
	}

	public void setHouse(House house) {
		this.house = house;
	}

	public String getImagesContentType() {
		return imagesContentType;
	}

	public void setImagesContentType(String imagesContentType) {
		this.imagesContentType = imagesContentType;
	}

	public String getImagesFileName() {
		return imagesFileName;
	}

	public void setImagesFileName(String imagesFileName) {
		this.imagesFileName = imagesFileName;
	}
	//指定上传图片的保存位置
	@SuppressWarnings("deprecation")
	public String getSavePath() {
		return ServletActionContext.getRequest().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public File getImages() {
		return images;
	}

	public void setImages(File images) {
		this.images = images;
	}

}


text:
author: alex
comments: true
date: 2011-07-27 19:00:58+00:00
layout: post
redirect_from: /2011/07/se-podcast-13
hero: /images/category/podcasts.jpg
slug: se-podcast-13
title: 'SE Podcast #13 - Jin Yang'
wordpress_id: 9033
tags:
- company
- podcasts
---

Jeff & Joel are joined this week by [Jin Yang](http://www.twitter.com/jzy) - our resident web/graphic designer here at Stack (the distinction between the two becomes a discussion point).  Once we get the proper picture of [Jin](http://www.8164.org/) in the chatroom, he relates everything from his background in design to how he ended up at Stack Exchange and our philosophy behind design.

Full topics this week include:

  * Jin refers to himself as a "web designer" as opposed to a "graphic designer" because of the type of work he focuses on.

  * [Last week](http://blog.stackoverflow.com/2011/07/se-podcast-12), we discussed [this amazing answer](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) from [Eric Lippert](http://stackoverflow.com/users/88656/eric-lippert) and how it was a great answer in response to a poor question.  Looking over this led Joel to notice that some people will vote to close a question as duplicate because the answers are the same even though the questions are different.

  * In this case, there was already some questions on the topic but Eric decided to write the "canonical" answer that can be referenced from here out.  Joel will often do the same thing on some of the other Stack Exchange sites (like in [this OnStartups post](http://answers.onstartups.com/questions/6949/forming-a-new-software-startup-how-do-i-allocate-ownership-fairly/23326#23326))

  * Sometimes you do [have to have SOME duplication](http://blog.stackoverflow.com/2010/11/dr-strangedupe-or-how-i-learned-to-stop-worrying-and-love-duplication/) of questions to make sure that the different use-cases are covered, but you want to avoid there being 12 of the exact same question on every site.

  * When applying for Stack Exchange, Jin created a custom site targeted at Joel to show his abilities.

  * As Joel notes (and expands on) Jin went with the always smart tactic of spending a ton of time focusing on the one company he truly wanted to work for instead of very little time on 50 random companies.

  * Many people forget that truly great design is very hard, when you have to meld it with making sure the site stays useful and effective for the users.

  * Talking about continuous improvement: Jin notes an [episode of This American Life](http://www.thisamericanlife.org/radio-archives/episode/403/nummi) covering similar topics.

  * Joel likes Robin Williams' (no, not that Robin Williams) book on design since it has really good and basic lessons on it - [The Non-Designers Design Book](http://www.amazon.com/Non-Designers-Design-Book-Robin-Williams/dp/0321193857)

  * We use a special CSS structure that lets us have a master CSS file for the entire network and then smaller CSS files for each site that just contain the differences between the generic template and the special parts of each site.

  * We've also learned a number of design lessons: like that white on black designs just don't look very good and aren't usable.

  * There have been issues in the past with designers creating their designs on macs but those designs then looking funny on PCs because of differences in text rendering - fortunately, thanks to improvements on both ends, that happens less now.

  * While Jin is our in house designer and works on everything, we occasionally have help from some outside designers (such as for English and UX) who are members of the community.

  * Prompted by a question for the chatroom, Jin is really excited about getting to design [our RPG site](http://rpg.stackexchange.com/).

  * Anonymous feedback is now live!  That means non-logged in users and those with less than 15 rep can give feedback on how good questions/answers are.  We haven't figured out how we'll incorporate this data yet, but we're collecting it and will figure that out.

  * Make sure you get your tickets for [Stack Overflow DevDays](http://devdays.stackoverflow.com) (we just [announced the first round of speakers](http://blog.stackoverflow.com/2011/07/documenting-devdays-2011-2-%E2%80%93-speakers/) for all the cities!) and use discount code "podcast" to save $100!

We'll be back live next week with a bunch of brand new podcast gear  and our special guest: [Miguel De Icaza](http://stackoverflow.com/users/16929/miguel-de-icaza).  Join us for the [live stream](http://www.livestream.com/stackexchange) and in the [official show chatroom](http://chat.stackexchange.com/rooms/512)

[Stack Exchange Podcast - Episode #13 w/ Jin Yang](http://soundcloud.com/stack-exchange/stack-exchange-podcast-13) by [Stack Exchange](http://soundcloud.com/stack-exchange)

<object width="100%" height="81" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowscriptaccess" value="always" /><param name="src" value="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F19889804" /><embed width="100%" height="81" type="application/x-shockwave-flash" src="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F19889804" allowscriptaccess="always" /></object> Stack Exchange Podcast – Episode #13 w/ Jin Yang by Stack Exchange


text:
package com.darly.im.ui.chatting.model;

/**
 *
Title: ChatRowType.java

 *
Description:

 *
Copyright: Copyright (c) 2014

 *
Company: Beijing Speedtong Information Technology Co.,Ltd

 * @author Jorstin Chan
 * @date 2014-4-16
 * @version 1.0
 */
public enum ChattingRowType {

    /**
     * display a image of message received
     */
    IMAGE_ROW_RECEIVED("C200R" , Integer.valueOf(1)),

    /**
     * display a image of message transmitted
     */
    IMAGE_ROW_TRANSMIT("C200T" , Integer.valueOf(2)),

    /**
     * display a file of message received
     */
    FILE_ROW_RECEIVED("C1024R" , Integer.valueOf(3)),

    /**
     * display a file of message transmitted
     */
    FILE_ROW_TRANSMIT("C1024T" , Integer.valueOf(4)),

    /**
     * display a voice of message received
     */
    VOICE_ROW_RECEIVED("C60R" , Integer.valueOf(5)),

    /**
     *  display a voice of message transmitted
     */
    VOICE_ROW_TRANSMIT("C60T" , Integer.valueOf(6)),

    /**
     * Display text of message received
     */
    DESCRIPTION_ROW_RECEIVED("C2000R" , Integer.valueOf(7)),

    /**
     * Display text of message transmitted
     */
    DESCRIPTION_ROW_TRANSMIT("C2000T" , Integer.valueOf(8)),

    /**
     * chatting item for system .such as time
     */
    CHATTING_SYSTEM("C18600668603R" , Integer.valueOf(9)),

    LOCATION_ROW_RECEIVED("C2200R" , Integer.valueOf(10)),

    LOCATION_ROW_TRANSMIT("C2200T" , Integer.valueOf(11));

    private final Integer mId;
    private final Object mDefaultValue;

    /**
     * Constructor of ChattingRowType.
     *
     * @param id The unique identifier of the setting
     * @param defaultValue The default value of the setting
     */
    private ChattingRowType(Object defaultValue , Integer id) {
        this.mId = id;
        this.mDefaultValue = defaultValue;
    }

    /**
     * Method that returns the unique identifier of the setting.
     * @return the mId
     */
    public Integer getId() {
        return this.mId;
    }

    /**
     * Method that returns the default value of the setting.
     *
     * @return Object The default value of the setting
     */
    public Object getDefaultValue() {
        return this.mDefaultValue;
    }

    /**
     * Method that returns an instance of {@link com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings} from its.
     * unique identifier
     *
     * @param value The unique identifier
     * @return CCPPreferenceSettings The navigation sort mode
     */
    public static ChattingRowType fromValue(String value) {
        ChattingRowType[] values = values();
        int cc = values.length;
        for (int i = 0; i < cc; i++) {
            if (values[i].mDefaultValue.equals(value)) {
                return values[i];
            }
        }
        return null;
    }

}


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { OverridableComponent } from '@mui/types';
import composeClasses from '../composeClasses';
import appendOwnerState from '../utils/appendOwnerState';
import useBadge from './useBadge';
import { getBadgeUnstyledUtilityClass } from './badgeUnstyledClasses';
import {
  BadgeUnstyledProps,
  BadgeUnstyledOwnerState,
  BadgeUnstyledTypeMap,
  BadgeUnstyledRootSlotProps,
  BadgeUnstyledBadgeSlotProps,
} from './BadgeUnstyled.types';
import { WithOptionalOwnerState } from '../utils';

const useUtilityClasses = (ownerState: BadgeUnstyledOwnerState) => {
  const { invisible } = ownerState;

  const slots = {
    root: ['root'],
    badge: ['badge', invisible && 'invisible'],
  };

  return composeClasses(slots, getBadgeUnstyledUtilityClass, undefined);
};
/**
 *
 * Demos:
 *
 * - [Badge](https://mui.com/base/react-badge/)
 *
 * API:
 *
 * - [BadgeUnstyled API](https://mui.com/base/api/badge-unstyled/)
 */
const BadgeUnstyled = React.forwardRef(function BadgeUnstyled(
  props: BadgeUnstyledProps & { component?: React.ElementType },
  ref,
) {
  const {
    badgeContent: badgeContentProp,
    component,
    children,
    className,
    components = {},
    componentsProps = {},
    invisible: invisibleProp,
    max: maxProp = 99,
    showZero = false,
    ...other
  } = props;

  const { badgeContent, max, displayValue, invisible } = useBadge({
    ...props,
    max: maxProp,
  });

  const ownerState: BadgeUnstyledOwnerState = {
    ...props,
    badgeContent,
    invisible,
    max,
    showZero,
  };

  const classes = useUtilityClasses(ownerState);

  const Root = component || components.Root || 'span';
  const rootProps: WithOptionalOwnerState<BadgeUnstyledRootSlotProps> = appendOwnerState(
    Root,
    {
      ...other,
      ...componentsProps.root,
      ref,
      className: clsx(classes.root, componentsProps.root?.className, className),
    },
    ownerState,
  );

  const Badge = components.Badge || 'span';
  const badgeProps: WithOptionalOwnerState<BadgeUnstyledBadgeSlotProps> = appendOwnerState(
    Badge,
    { ...componentsProps.badge, className: clsx(classes.badge, componentsProps.badge?.className) },
    ownerState,
  );

  return (
    <Root {...rootProps}>
      {children}
      <Badge {...badgeProps}>{displayValue}</Badge>
    </Root>
  );
}) as OverridableComponent<BadgeUnstyledTypeMap>;

BadgeUnstyled.propTypes /* remove-proptypes */ = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit TypeScript types and run "yarn proptypes"  |
  // ----------------------------------------------------------------------
  /**
   * The content rendered within the badge.
   */
  badgeContent: PropTypes.node,
  /**
   * The badge will be added relative to this node.
   */
  children: PropTypes.node,
  /**
   * @ignore
   */
  className: PropTypes.string,
  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: PropTypes.elementType,
  /**
   * The components used for each slot inside the Badge.
   * Either a string to use a HTML element or a component.
   * @default {}
   */
  components: PropTypes.shape({
    Badge: PropTypes.elementType,
    Root: PropTypes.elementType,
  }),
  /**
   * The props used for each slot inside the Badge.
   * @default {}
   */
  componentsProps: PropTypes.shape({
    badge: PropTypes.object,
    root: PropTypes.object,
  }),
  /**
   * If `true`, the badge is invisible.
   * @default false
   */
  invisible: PropTypes.bool,
  /**
   * Max count to show.
   * @default 99
   */
  max: PropTypes.number,
  /**
   * Controls whether the badge is hidden when `badgeContent` is zero.
   * @default false
   */
  showZero: PropTypes.bool,
} as any;

export default BadgeUnstyled;


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"math/rand"
	"time"

	"sync"

	"github.com/nats-io/gnatsd/server"
	"github.com/nats-io/gnatsd/test"
	"github.com/nats-io/nats"
)

var csvOutput *bool
var doReconnect *bool
var useLocalServer bool

func runTest(url, user string, count int64) {
	var wg sync.WaitGroup
	var srv *server.Server

	if useLocalServer {
		srv, _ = test.RunServerWithConfig("./gnatsd.conf")
	}

	opts := nats.DefaultOptions
	opts.Timeout = time.Second * 600
	opts.Url = url
	opts.User = user
	opts.Password = "password"

	opts.ReconnectedCB = func(c *nats.Conn) {
		if *doReconnect {
			wg.Done()
		}
	}

	var connStartTime = time.Now()

	connList := make([]*nats.Conn, 0, count)
	wg.Add(int(count))

	// create connections simultaneously to make the test complete faster.
	for i := int64(0); i < count; i++ {
		go func() {
			// randomize connect times to prevent connection read errors
			time.Sleep(time.Millisecond * time.Duration(rand.Intn(2000)))
			nc, err := opts.Connect()
			if err != nil {
				log.Fatalf("Can't connect: %v\n", err)
			}
			connList = append(connList, nc)
			wg.Done()
		}()
	}
	defer func() {
		for _, nc := range connList {
			nc.Close()
		}
	}()

	// wait for all connections to connect
	wg.Wait()
	totalConnectTime := time.Now().Sub(connStartTime)

	var reconnectWaitTime time.Duration

	// Bounce the server
	if *doReconnect {
		wg.Add(int(count))

		srv.Shutdown()
		disconnectTime := time.Now()
		srv, _ = test.RunServerWithConfig("./gnatsd.conf")

		// wait for all connections to reconnect
		wg.Wait()
		reconnectWaitTime = time.Now().Sub(disconnectTime)
	}
	defer srv.Shutdown()

	if *csvOutput {
		log.Printf("%s,%f", user, totalConnectTime.Seconds())
	} else {
		if *doReconnect {
			log.Printf("user=%s, connect time=%v, reconnect time=%v",
				user, totalConnectTime, reconnectWaitTime)
		} else {
			log.Printf("user=%s, connect time=%v",
				user, totalConnectTime)
		}
	}
}

func main() {
	var url = flag.String("s", "", "The nats server URLs (separated by comma)")
	var count = flag.Int("c", 50, "# of connections")
	csvOutput = flag.Bool("csv", false, "csv output")
	doReconnect = flag.Bool("rc", false, "do reconnect")
	var user = flag.String("u", "", "user name, if not specified, run all")

	log.SetFlags(0)
	flag.Parse()

	fmt.Printf("Connections: %d\n", *count)

	if *user != "" {
		runTest(*url, *user, int64(*count))
		return
	}

	if *url == "" {
		*url = "nats://localhost:4222"
		useLocalServer = false
	}

	if !useLocalServer && *doReconnect {
		log.Fatalf("Reconnect testing is only supported with a local sever.")
	}

	runTest(*url, "cost_0", int64(*count))
	runTest(*url, "cost_4", int64(*count))
	runTest(*url, "cost_5", int64(*count))
	runTest(*url, "cost_6", int64(*count))
	runTest(*url, "cost_7", int64(*count))
	runTest(*url, "cost_8", int64(*count))
	runTest(*url, "cost_9", int64(*count))
	runTest(*url, "cost_10", int64(*count))
	runTest(*url, "cost_11", int64(*count))
	runTest(*url, "cost_12", int64(*count))
	runTest(*url, "cost_13", int64(*count))
	runTest(*url, "cost_14", int64(*count))
	runTest(*url, "cost_15", int64(*count))
	runTest(*url, "cost_16", int64(*count))
	runTest(*url, "cost_17", int64(*count))
	runTest(*url, "cost_18", int64(*count))
	runTest(*url, "cost_19", int64(*count))
	runTest(*url, "cost_20", int64(*count))

	log.Println("Done.")
}