text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- 摇一摇相关style -->
    <style name="scrshot_dlg_style" parent="@android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:backgroundDimEnabled">true</item>
        <item name="android:backgroundDimAmount">0.6</item>
    </style>

    <!--  -->
    <style name="lan_DialogWindowAnim" mce_bogus="1" parent="android:Animation">
        <item name="android:windowExitAnimation">@anim/shake_umeng_socialize_dlg_alpha</item>
    </style>

    <style name="snapshotDialogWindowAnim" mce_bogus="1" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/shake_umeng_socialize_scrshot_dlg</item>
        <item name="android:windowExitAnimation">@anim/shake_umeng_socialize_dlg_alpha</item>
    </style>

    <style name="notitleDialog">

        <!-- 边框 -->
        <item name="android:windowFrame">@null</item>
        <!-- 半透明 -->
        <item name="android:windowIsTranslucent">true</item>
        <!-- 无标题 -->
        <item name="android:windowNoTitle">true</item>
        <!-- 背景透明 -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <!-- 模糊 -->
        <item name="android:backgroundDimEnabled">false</item>
    </style>

    <style name="Dialog_Fullscreen">

        <!-- 边框 -->
        <item name="android:windowFrame">@null</item>
        <!-- 半透明 -->
        <item name="android:windowIsTranslucent">true</item>
        <!-- 背景透明 -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">true</item>
        <item name="android:backgroundDimAmount">0.6</item>
    </style>

    <style name="Notitle_Fullscreen">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>


text:
module Twitter
  module Config
    mattr_accessor(:read)

    if File.exists?( RAILS_ROOT + '/config/r2_tweet2.yml' )
      self.read = YAML::load_file( RAILS_ROOT + '/config/r2_tweet2.yml' )[RAILS_ENV]

    else
      self.read = YAML::load_file( File.expand_path(File.join(File.dirname(__FILE__), '/../r2_tweet2.yml' )) )[RAILS_ENV]
    end

    @@user_agent = self.read['user_agent']
    @@client_app = self.read['client_app']
    @@client_url = self.read['client_url']
    @@user = self.read['user']
    @@password = self.read['password']
    @@proxy_host = self.read['proxy_host']
    @@proxy_port = self.read['proxy_port']
    @@proxy_pass = self.read['proxy_pass']
    @@proxy_user = self.read['proxy_user']

    mattr_reader(:user_agent,
                 :client_app, :client_url,
                 :user, :password, :proxy_host,
                 :proxy_port, :proxy_pass, :proxy_user)
  end
end

redpajama_set_name: RedPajamaGithub


text:
package operation

//go:generate operationgen insert.toml operation insert.go
//go:generate operationgen find.toml operation find.go
//go:generate operationgen list_collections.toml operation list_collections.go
//go:generate operationgen createIndexes.toml operation createIndexes.go
//go:generate operationgen drop_collection.toml operation drop_collection.go
//go:generate operationgen distinct.toml operation distinct.go
//go:generate operationgen delete.toml operation delete.go
//go:generate operationgen drop_indexes.toml operation drop_indexes.go
//go:generate operationgen drop_database.toml operation drop_database.go
//go:generate operationgen commit_transaction.toml operation commit_transaction.go
//go:generate operationgen abort_transaction.toml operation abort_transaction.go
//go:generate operationgen count.toml operation count.go
//go:generate operationgen end_sessions.toml operation end_sessions.go


text:
class Candidate < ActiveRecord::Base
  has_and_belongs_to_many :tweets
  validates_presence_of :firstName
  validates_presence_of :lastName
end


text:
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or at:
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =================================================================================================

package com.twitter.common.zookeeper;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Nullable;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.base.Throwables;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.MapDifference;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.google.gson.GsonBuilder;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;

import com.twitter.common.args.Arg;
import com.twitter.common.args.CmdLine;
import com.twitter.common.base.Command;
import com.twitter.common.base.Function;
import com.twitter.common.base.Supplier;
import com.twitter.common.io.Codec;
import com.twitter.common.io.CompatibilityCodec;
import com.twitter.common.io.JsonCodec;
import com.twitter.common.io.ThriftCodec;
import com.twitter.common.util.BackoffHelper;
import com.twitter.common.zookeeper.Group.GroupChangeListener;
import com.twitter.common.zookeeper.Group.JoinException;
import com.twitter.common.zookeeper.Group.Membership;
import com.twitter.common.zookeeper.Group.WatchException;
import com.twitter.common.zookeeper.ZooKeeperClient.ZooKeeperConnectionException;
import com.twitter.thrift.Endpoint;
import com.twitter.thrift.ServiceInstance;
import com.twitter.thrift.Status;

/**
 * Implementation of {@link ServerSet}.
 *
 * @author John Sirois
 */
public class ServerSetImpl implements ServerSet {
  private static final Logger LOG = Logger.getLogger(ServerSetImpl.class.getName());

  @CmdLine(name = "serverset_encode_json",
           help = "If true, use JSON for encoding server set information. Defaults to false (use Thrift).")
  private static final Arg<Boolean> ENCODE_JSON = Arg.create(false);

  private final ZooKeeperClient zkClient;
  private final Group group;
  private final Codec<ServiceInstance> codec;
  private final BackoffHelper backoffHelper;

  /**
   * Creates a new ServerSet using open ZooKeeper node ACLs.
   *
   * @param zkClient the client to use for interactions with ZooKeeper
   * @param path the name-service path of the service to connect to
   */
  public ServerSetImpl(ZooKeeperClient zkClient, String path) {
    this(zkClient, ZooDefs.Ids.OPEN_ACL_UNSAFE, path);
  }

  /**
   * Creates a new ServerSet for the given service {@code path}.
   *
   * @param zkClient the client to use for interactions with ZooKeeper
   * @param acl the ACL to use for creating the persistent group path if it does not already exist
   * @param path the name-service path of the service to connect to
   */
  public ServerSetImpl(ZooKeeperClient zkClient, Iterable<ACL> acl, String path) {
    this(zkClient, new Group(zkClient, acl, path), createDefaultCodec());
  }

  /**
   * Creates a new ServerSet using the given service {@code group}.
   *
   * @param zkClient the client to use for interactions with ZooKeeper
   * @param group the server group
   */
  public ServerSetImpl(ZooKeeperClient zkClient, Group group) {
    this(zkClient, group, createDefaultCodec());
  }

  /**
   * Creates a new ServerSet using the given service {@code group} and a custom {@code codec}.
   *
   * @param zkClient the client to use for interactions with ZooKeeper
   * @param group the server group
   * @param codec a codec to use for serializing and de-serializing the ServiceInstance data to and
   *     from a byte array
   */
  public ServerSetImpl(ZooKeeperClient zkClient, Group group, Codec<ServiceInstance> codec) {
    this.zkClient = Preconditions.checkNotNull(zkClient);
    this.group = Preconditions.checkNotNull(group);
    this.codec = Preconditions.checkNotNull(codec);

    // TODO(John Sirois): Inject the helper so that backoff strategy can be configurable.
    backoffHelper = new BackoffHelper();
  }

  @VisibleForTesting
  ZooKeeperClient getZkClient() {
    return zkClient;
  }

  @Override
  public EndpointStatus join(InetSocketAddress endpoint,
      Map<String, InetSocketAddress> additionalEndpoints, Status status)
      throws JoinException, InterruptedException {
    Preconditions.checkNotNull(endpoint);
    Preconditions.checkNotNull(additionalEndpoints);
    Preconditions.checkNotNull(status);

    final MemberStatus memberStatus = new MemberStatus(endpoint, additionalEndpoints, status);
    Supplier<byte[]> serviceInstanceSupplier = new Supplier<byte[]>() {
      @Override public byte[] get() {
        return memberStatus.serializeServiceInstance();
      }
    };
    final Membership membership = group.join(serviceInstanceSupplier);

    return new EndpointStatus() {
      @Override public void update(Status status) throws UpdateException {
        Preconditions.checkNotNull(status);
        memberStatus.updateStatus(membership, status);
      }
    };
  }

  @Override
  public void monitor(final HostChangeMonitor<ServiceInstance> monitor) throws MonitorException {
    ServerSetWatcher serverSetWatcher = new ServerSetWatcher(zkClient, monitor);
    try {
      serverSetWatcher.watch();
    } catch (WatchException e) {
      throw new MonitorException("ZooKeeper watch failed.", e);
    } catch (InterruptedException e) {
      throw new MonitorException("Interrupted while watching ZooKeeper.", e);
    }
  }

  private class MemberStatus {
    private final InetSocketAddress endpoint;
    private final Map<String, InetSocketAddress> additionalEndpoints;
    private volatile Status status;

    private MemberStatus(InetSocketAddress endpoint,
        Map<String, InetSocketAddress> additionalEndpoints, Status status) {

      this.endpoint = endpoint;
      this.additionalEndpoints = additionalEndpoints;
      this.status = status;
    }

    synchronized void updateStatus(Membership membership, Status status) throws UpdateException {
      if (this.status != status) {
        this.status = status;
        if (Status.DEAD == status) {
          try {
            membership.cancel();
          } catch (JoinException e) {
            throw new UpdateException(
                "Failed to auto-cancel group membership on transition to DEAD status", e);
          }
        } else {
          try {
            membership.updateMemberData();
          } catch (Group.UpdateException e) {
            throw new UpdateException(
                "Failed to update service data for: " + membership.getMemberPath(), e);
          }
        }
      }
    }

    byte[] serializeServiceInstance() {
      ServiceInstance serviceInstance =
          new ServiceInstance(toEndpoint(endpoint),
              Maps.transformValues(additionalEndpoints, TO_ENDPOINT), status);
      LOG.info("updating endpoint data to:\n\t" + serviceInstance);
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      try {
        codec.serialize(serviceInstance, output);
      } catch (IOException e) {
        throw new IllegalStateException("Unexpected problem serializing thrift struct: " +
                                        serviceInstance + " to a byte[]", e);
      }
      return output.toByteArray();
    }
  }

  private static final Function<InetSocketAddress, Endpoint> TO_ENDPOINT =
      new Function<InetSocketAddress, Endpoint>() {
        @Override public Endpoint apply(InetSocketAddress address) {
          return toEndpoint(address);
        }
      };

  private static Endpoint toEndpoint(InetSocketAddress address) {
    return new Endpoint(address.getHostName(), address.getPort());
  }

  private static class ServiceInstanceFetchException extends RuntimeException {
    ServiceInstanceFetchException(String message, Throwable cause) {
      super(message, cause);
    }
  }

  private static class ServiceInstanceDeletedException extends RuntimeException {
    ServiceInstanceDeletedException(String path) {
      super(path);
    }
  }

  private static final Function<ServiceInstance, Endpoint> GET_PRIMARY_ENDPOINT =
      new Function<ServiceInstance, Endpoint>() {
        @Override public Endpoint apply(ServiceInstance serviceInstance) {
          return serviceInstance.getServiceEndpoint();
        }
      };

  private class ServerSetWatcher {
    private final ZooKeeperClient zkClient;
    private final HostChangeMonitor<ServiceInstance> monitor;
    @Nullable private ImmutableSet<ServiceInstance> serverSet;

    ServerSetWatcher(ZooKeeperClient zkClient, HostChangeMonitor<ServiceInstance> monitor) {
      this.zkClient = zkClient;
      this.monitor = monitor;
    }

    public void watch() throws WatchException, InterruptedException {
      zkClient.registerExpirationHandler(new Command() {
        @Override public void execute() {
          // Servers may have changed Status while we were disconnected from ZooKeeper, check and
          // re-register our node watches.
          rebuildServerSet();
        }
      });

      group.watch(new GroupChangeListener() {
        @Override public void onGroupChange(Iterable<String> memberIds) {
          notifyGroupChange(memberIds);
        }
      });
    }

    private Watcher serviceInstanceWatcher = new Watcher() {
      @Override public void process(WatchedEvent event) {
        if (event.getState() == KeeperState.SyncConnected) {
          switch (event.getType()) {
            case None:
              // Ignore re-connects that happen while we're watching
              break;
            case NodeDeleted:
              // Ignore deletes since these trigger a group change through the group node watch.
              break;
            case NodeDataChanged:
              notifyNodeChange(event.getPath());
              break;
            case NodeCreated:
              // This watcher is only applied to ephemeral sequential server set member nodes we
              // already know the path of (ie: the ephemeral sequential exists and we're told about
              // this by reading children).  Its not clear how we can get a NodeCreated event for a
              // node we already know about - but this appears to occur in the wild.  Firing a
              // change here is safe even if the event path does not represent a server set member.
              // The node de-serializer will throw ServiceInstanceFetchException in this case and
              // these exceptions are logged and filtered out of member sets.
              notifyNodeChange(event.getPath());

              // TODO(John Sirois): inject a Statsprovider and track these events in a stat
              LOG.warning("Unexpected NodeCreated event while watching service node: " +
                  event.getPath());

              break;
            default:
              LOG.severe("Unexpected event watching service node: " + event);
          }
        }
      }
    };

    private ServiceInstance getServiceInstance(final String nodePath) {
      try {
        return backoffHelper.doUntilResult(new Supplier<ServiceInstance>() {
          @Override public ServiceInstance get() {
            try {
              byte[] data = zkClient.get().getData(nodePath, serviceInstanceWatcher, null);
              return codec.deserialize(new ByteArrayInputStream(data));
            } catch (InterruptedException e) {
              Thread.currentThread().interrupt();
              throw new ServiceInstanceFetchException(
                  "Interrupted updating service data for: " + nodePath, e);
            } catch (ZooKeeperConnectionException e) {
              LOG.log(Level.WARNING,
                  "Temporary error trying to updating service data for: " + nodePath, e);
              return null;
            } catch (NoNodeException e) {
              invalidateNodePath(nodePath);
              throw new ServiceInstanceDeletedException(nodePath);
            } catch (KeeperException e) {
              if (zkClient.shouldRetry(e)) {
                LOG.log(Level.WARNING,
                    "Temporary error trying to update service data for: " + nodePath, e);
                return null;
              } else {
                throw new ServiceInstanceFetchException(
                    "Failed to update service data for: " + nodePath, e);
              }
            } catch (IOException e) {
              throw new ServiceInstanceFetchException(
                  "Failed to deserialize the ServiceInstance data for: " + nodePath, e);
            }
          }
        });
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new ServiceInstanceFetchException(
            "Interrupted trying to update service data for: " + nodePath, e);
      }
    }

    private final LoadingCache<String, ServiceInstance> servicesByMemberId =
        CacheBuilder.newBuilder().build(new CacheLoader<String, ServiceInstance>() {
          @Override public ServiceInstance load(String memberId) {
            return getServiceInstance(group.getMemberPath(memberId));
          }
        });

    private void rebuildServerSet() {
      Set<String> memberIds = ImmutableSet.copyOf(servicesByMemberId.asMap().keySet());
      servicesByMemberId.invalidateAll();
      notifyGroupChange(memberIds);
    }

    private void notifyNodeChange(String changedPath) {
      // Invalidate the associated ServiceInstance to trigger a fetch on group notify.
      String memberId = invalidateNodePath(changedPath);
      notifyGroupChange(
          Iterables.concat(servicesByMemberId.asMap().keySet(), ImmutableList.of(memberId)));
    }

    private String invalidateNodePath(String deletedPath) {
      String memberId = group.getMemberId(deletedPath);
      servicesByMemberId.invalidate(memberId);
      return memberId;
    }

    private final Function<String, ServiceInstance> MAYBE_FETCH_NODE =
        new Function<String, ServiceInstance>() {
          @Override public ServiceInstance apply(String memberId) {
            // This get will trigger a fetch
            try {
              return servicesByMemberId.getUnchecked(memberId);
            } catch (UncheckedExecutionException e) {
              Throwable cause = e.getCause();
              if (!(cause instanceof ServiceInstanceDeletedException)) {
                Throwables.propagateIfInstanceOf(cause, ServiceInstanceFetchException.class);
                throw new IllegalStateException(
                    "Unexpected error fetching member data for: " + memberId, e);
              }
              return null;
            }
          }
        };

    private synchronized void notifyGroupChange(Iterable<String> memberIds) {
      ImmutableSet<String> newMemberIds = ImmutableSortedSet.copyOf(memberIds);
      Set<String> existingMemberIds = servicesByMemberId.asMap().keySet();

      // Ignore no-op state changes except for the 1st when we've seen no group yet.
      if ((serverSet == null) || !newMemberIds.equals(existingMemberIds)) {
        SetView<String> deletedMemberIds = Sets.difference(existingMemberIds, newMemberIds);
        // Implicit removal from servicesByMemberId.
        existingMemberIds.removeAll(ImmutableSet.copyOf(deletedMemberIds));

        Iterable<ServiceInstance> serviceInstances = Iterables.filter(
            Iterables.transform(newMemberIds, MAYBE_FETCH_NODE), Predicates.notNull());

        notifyServerSetChange(ImmutableSet.copyOf(serviceInstances));
      }
    }

    private void notifyServerSetChange(ImmutableSet<ServiceInstance> currentServerSet) {
      // ZK nodes may have changed if there was a session expiry for a server in the server set, but
      // if the server's status has not changed, we can skip any onChange updates.
      if (!currentServerSet.equals(serverSet)) {
        if (currentServerSet.isEmpty()) {
          LOG.warning("server set empty!");
        } else {
          if (LOG.isLoggable(Level.INFO)) {
            if (serverSet == null) {
              LOG.info("received initial membership " + currentServerSet);
            } else {
              logChange(Level.INFO, currentServerSet);
            }
          }
        }
        serverSet = currentServerSet;
        monitor.onChange(serverSet);
      }
    }

    private void logChange(Level level, ImmutableSet<ServiceInstance> newServerSet) {
      StringBuilder message = new StringBuilder("server set change: ");
      if (serverSet.size() != newServerSet.size()) {
        message.append("from ").append(serverSet.size())
            .append(" members to ").append(newServerSet.size());
      }

      MapDifference<Endpoint, ServiceInstance> changes =
          Maps.difference(
              Maps.uniqueIndex(serverSet, GET_PRIMARY_ENDPOINT),
              Maps.uniqueIndex(newServerSet, GET_PRIMARY_ENDPOINT));
      Joiner joiner = Joiner.on("\n\t\t");
      Map<Endpoint, ServiceInstance> left = changes.entriesOnlyOnLeft();
      if (!left.isEmpty()) {
        message.append("\n\tleft:\n\t\t").append(joiner.join(left.values()));
      }
      Map<Endpoint, ServiceInstance> joined = changes.entriesOnlyOnRight();
      if (!joined.isEmpty()) {
        message.append("\n\tjoined:\n\t\t").append(joiner.join(joined.values()));
      }
      Map<Endpoint, ValueDifference<ServiceInstance>> differing = changes.entriesDiffering();
      if (!differing.isEmpty()) {
        message.append("\n\tstatus changed:\n\t\t").append(joiner.join(differing.values()));
      }
      LOG.log(level, message.toString());
    }
  }

  private static Codec<ServiceInstance> createCodec(final boolean useJsonEncoding) {
    final Codec<ServiceInstance> json = JsonCodec.create(ServiceInstance.class, new GsonBuilder()
        .setExclusionStrategies(JsonCodec.getThriftExclusionStrategy()).create());
    final Codec<ServiceInstance> thrift = ThriftCodec.create(ServiceInstance.class,
        ThriftCodec.BINARY_PROTOCOL);
    final Predicate<byte[]> recognizer = new Predicate<byte[]>() {
      public boolean apply(byte[] input) {
        return (input.length > 1 && input[0] == '{' && input[1] == '\"') == useJsonEncoding;
      }
    };

    if (useJsonEncoding) {
      return CompatibilityCodec.create(json, thrift, 2, recognizer);
    }
    return CompatibilityCodec.create(thrift, json, 2, recognizer);
  }

  /**
   * Creates a codec for {@link ServiceInstance} objects that uses Thrift binary encoding, and can
   * decode both Thrift and JSON encodings.
   *
   * @return a new codec instance.
   */
  public static Codec<ServiceInstance> createThriftCodec() {
    return createCodec(false);
  }

  /**
   * Creates a codec for {@link ServiceInstance} objects that uses JSON encoding, and can decode
   * both Thrift and JSON encodings.
   *
   * @return a new codec instance.
   */
  public static Codec<ServiceInstance> createJsonCodec() {
    return createCodec(true);
  }

  /**
   * Returns a codec for {@link ServiceInstance} objects that uses either the Thrift or the JSON
   * encoding, depending on whether the command line argument <tt>serverset_json_encofing</tt> is
   * set to <tt>true</tt>, and can decode both Thrift and JSON encodings.
   *
   * @return a new codec instance.
   */
  public static Codec<ServiceInstance> createDefaultCodec() {
    return createCodec(ENCODE_JSON.get());
  }
}


text:
var sourceType = [ ['camera'], ['album'], ['camera', 'album'] ]
var sizeType = [ ['compressed'], ['original'], ['compressed', 'original'] ]

Page({
  data: {
    sourceTypeIndex: 0,
    sourceType: ['拍照', '相册', '拍照或相册'],

    sizeTypeIndex: 0,
    sizeType: ['压缩', '原图', '压缩或原图'],

    countIndex: 0,
    count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  },
  sourceTypeChange: function (e) {
    this.setData({
      sourceTypeIndex: e.detail.value
    })
  },
  sizeTypeChange: function (e) {
    this.setData({
      sizeTypeIndex: e.detail.value
    })
  },
  countChange: function (e) {
    this.setData({
      countIndex: e.detail.value
    })
  },
  chooseImage: function () {
    var that = this
    wx.chooseImage({
      sourceType: sourceType[this.data.sourceTypeIndex],
      sizeType: sizeType[this.data.sizeTypeIndex],
      count: this.data.count[this.data.countIndex],
      success: function (res) {
        console.log(res)
        that.setData({
          imageList: res.tempFilePaths
        })
      }
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  }
})


text:
<?php

namespace HiveSDK\API\WorkUnit;

class Body{

    protected $data;

    public function set($path, $value){
        $parts = explode('/', $path);
        $this->data = $this->traverse($this->data, $parts, $value);
        return $this;
    }

    public function read(){
        $data = $this->data;
        $this->reset();
        return $data;
    }

    public function reset(){
        $this->reset = array();
        return $this;
    }

    public function hasChanges(){
        return !empty($this->data);
    }

    protected function traverse($cursor, $parts, $value){
        $part = array_shift($parts);

        if($part){
            $cursor[$part] = isset($cursor[$part])? $cursor[$part] : array();
            $cursor[$part] = $this->traverse($cursor[$part], $parts, $value);
            return $cursor;
        }else{
            return $value;
        }
    }

}


text:
#import "UILabel+TCCustomFont.h"

@implementation UILabel (TCCustomFont)

- (NSString *)fontName {
    return self.font.fontName;
}

- (void)setFontName:(NSString *)fontName {
    self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}

@end


text:
namespace mediapipe {

// static
absl::StatusOr<Executor*> ThreadPoolExecutor::Create(
    const MediaPipeOptions& extendable_options) {
  auto& options =
      extendable_options.GetExtension(ThreadPoolExecutorOptions::ext);
  if (!options.has_num_threads()) {
    return absl::InvalidArgumentError(
        "num_threads is not specified in ThreadPoolExecutorOptions.");
  }
  if (options.num_threads() <= 0) {
    return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
           << "The num_threads field in ThreadPoolExecutorOptions should be "
              "positive but is "
           << options.num_threads();
  }

  ThreadOptions thread_options;
  if (options.has_stack_size()) {
    // thread_options.set_stack_size() takes a size_t as input, so we must not
    // pass a negative value. 0 has a special meaning (the default thread
    // stack size for the system), so we also avoid that.
    if (options.stack_size() <= 0) {
      return mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC)
             << "The stack_size field in ThreadPoolExecutorOptions should be "
                "positive but is "
             << options.stack_size();
    }
    thread_options.set_stack_size(options.stack_size());
  }
  if (options.has_nice_priority_level()) {
    thread_options.set_nice_priority_level(options.nice_priority_level());
  }
  if (options.has_thread_name_prefix()) {
    thread_options.set_name_prefix(options.thread_name_prefix());
  }
#if defined(__linux__)
  switch (options.require_processor_performance()) {
    case ThreadPoolExecutorOptions::LOW:
      thread_options.set_cpu_set(InferLowerCoreIds());
      break;
    case ThreadPoolExecutorOptions::HIGH:
      thread_options.set_cpu_set(InferHigherCoreIds());
      break;
    default:
      break;
  }
#endif
  return new ThreadPoolExecutor(thread_options, options.num_threads());
}

ThreadPoolExecutor::ThreadPoolExecutor(int num_threads)
    : thread_pool_("mediapipe", num_threads) {
  Start();
}

ThreadPoolExecutor::ThreadPoolExecutor(const ThreadOptions& thread_options,
                                       int num_threads)
    : thread_pool_(thread_options,
                   thread_options.name_prefix().empty()
                       ? "mediapipe"
                       : thread_options.name_prefix(),
                   num_threads) {
  Start();
}

ThreadPoolExecutor::~ThreadPoolExecutor() {
  VLOG(2) << "Terminating thread pool.";
}

void ThreadPoolExecutor::Schedule(std::function<void()> task) {
  thread_pool_.Schedule(std::move(task));
}

void ThreadPoolExecutor::Start() {
  stack_size_ = thread_pool_.thread_options().stack_size();
  thread_pool_.StartWorkers();
  VLOG(2) << "Started thread pool with " << thread_pool_.num_threads()
          << " threads.";
}

REGISTER_EXECUTOR(ThreadPoolExecutor);

}  // namespace mediapipe


text:
package com.google.android.material.motion.operators;

import android.graphics.PointF;
import android.support.annotation.NonNull;

import com.google.android.indefinite.observable.IndefiniteObservable;
import com.google.android.material.motion.MotionObserver;
import com.google.android.material.motion.gestures.BuildConfig;
import com.google.android.material.motion.MotionObservable;
import com.google.android.material.motion.testing.TrackingMotionObserver;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.Arrays;

import static com.google.android.material.motion.operators.X.x;
import static com.google.android.material.motion.operators.Y.y;
import static com.google.common.truth.Truth.assertThat;

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class PointFOperatorsTests {

  @Test
  public void extractsX() {
    TrackingMotionObserver<Float> tracker = new TrackingMotionObserver<>();

    pointFSource()
      .compose(x())
      .subscribe(tracker);

    assertThat(tracker.values).isEqualTo(Arrays.asList(1f, 3f, 5f));
  }

  @Test
  public void extractsY() {
    TrackingMotionObserver<Float> tracker = new TrackingMotionObserver<>();

    pointFSource()
      .compose(y())
      .subscribe(tracker);

    assertThat(tracker.values).isEqualTo(Arrays.asList(2f, 4f, 6f));
  }

  @NonNull
  private MotionObservable<PointF> pointFSource() {
    return new MotionObservable<>(new IndefiniteObservable.Connector<MotionObserver<PointF>>() {
      @NonNull
      @Override
      public IndefiniteObservable.Disconnector connect(MotionObserver<PointF> observer) {
        observer.next(new PointF(1f, 2f));
        observer.next(new PointF(3f, 4f));
        observer.next(new PointF(5f, 6f));
        return IndefiniteObservable.Disconnector.NO_OP;
      }
    });
  }
}


text:
#ifndef _MIDEND_REMOVEPARAMETERS_H_
#define _MIDEND_REMOVEPARAMETERS_H_

#include "ir/ir.h"
#include "frontends/p4/typeChecking/typeChecker.h"
#include "frontends/common/resolveReferences/referenceMap.h"
#include "frontends/p4/typeMap.h"

namespace P4 {

/**
 * For each action that is invoked keep the list of arguments that
 * it's called with. There must be only one call of each action;
 * this is done by LocalizeActions.
 */
class ActionInvocation {
    std::map<const IR::P4Action*, const IR::MethodCallExpression*> invocations;
    std::set<const IR::P4Action*> all;  // for these actions remove all parameters
    std::set<const IR::MethodCallExpression*> calls;
    /// how many arguments to remove from each default action
    std::map<const IR::MethodCallExpression*, unsigned> defaultActions;

 public:
    void bind(const IR::P4Action* action, const IR::MethodCallExpression* invocation,
              bool allParams) {
        CHECK_NULL(action);
        BUG_CHECK(invocations.find(action) == invocations.end(),
                  "%1%: action called twice", action);
        invocations.emplace(action, invocation);
        if (allParams)
            all.emplace(action);
        calls.emplace(invocation);
    }
    void bindDefaultAction(const IR::P4Action* action,
                           const IR::MethodCallExpression* defaultInvocation) {
        // We must have a binding for this action already.
        auto actionCallInvocation = ::get(invocations, action);
        CHECK_NULL(actionCallInvocation);
        // We must remove all arguments which are bound in the action list.
        unsigned boundArgs = actionCallInvocation->arguments->size();
        defaultActions.emplace(defaultInvocation, boundArgs);
    }
    const IR::MethodCallExpression* get(const IR::P4Action* action) const {
        return ::get(invocations, action);
    }
    bool removeAllParameters(const IR::P4Action* action) const {
        return all.find(action) != all.end();
    }
    bool isCall(const IR::MethodCallExpression* expression) const {
        return calls.find(expression) != calls.end();
    }
    unsigned argsToRemove(const IR::MethodCallExpression* defaultCall) const {
        if (defaultActions.find(defaultCall) == defaultActions.end())
            return 0;
        return ::get(defaultActions, defaultCall);
    }
};

class FindActionParameters : public Inspector {
    ReferenceMap*     refMap;
    TypeMap*          typeMap;
    ActionInvocation* invocations;
 public:
    FindActionParameters(ReferenceMap* refMap,
                         TypeMap* typeMap, ActionInvocation* invocations) :
            refMap(refMap), typeMap(typeMap), invocations(invocations) {
        CHECK_NULL(refMap); CHECK_NULL(invocations); CHECK_NULL(typeMap);
        setName("FindActionParameters"); }

    void postorder(const IR::ActionListElement* element) override;
    void postorder(const IR::MethodCallExpression* expression) override;
};

/**
 * Removes parameters of an action which are in/inout/out.
 *
 * \code{.cpp}
 * control c(inout bit<32> x) {
 *    action a(in bit<32> arg) { x = arg; }
 *    table t() { actions = { a(10); } }
 *    apply { ... } }
 * \endcode
 *
 * is converted to
 *
 * \code{.cpp}
 * control c(inout bit<32> x) {
 *    bit<32> arg;
 *    action a() { arg = 10; x = arg; }
 *    table t() { actions = { a; } }
 *    apply { ... } }
 * \endcode
 *
 * @pre This pass requires each action to have a single caller.
 *      It must run after the LocalizeActions pass, which
 *      in turn must be run after actions inlining.
 * @post in/inout/out parameters of an action are removed.
 */
class DoRemoveActionParameters : public Transform {
    ActionInvocation* invocations;
 public:
    explicit DoRemoveActionParameters(ActionInvocation* invocations) :
            invocations(invocations)
    { CHECK_NULL(invocations); setName("DoRemoveActionParameters"); }

    const IR::Node* postorder(IR::P4Action* table) override;
    const IR::Node* postorder(IR::ActionListElement* element) override;
    const IR::Node* postorder(IR::MethodCallExpression* expression) override;
    ActionInvocation* getInvocations() {
        return invocations;
    }
};

class RemoveActionParameters : public PassManager {
 public:
    RemoveActionParameters(ReferenceMap* refMap, TypeMap* typeMap,
                           TypeChecking* typeChecking = nullptr);
};

}  // namespace P4

#endif /* _MIDEND_REMOVEPARAMETERS_H_ */


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Document;

use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiSubresource;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * Related Owning Dummy.
 *
 * @author Sergey V. Ryabov <sryabov@mhds.ru>
 * @author Alan Poulain <contact@alanpoulain.eu>
 *
 * @ApiResource(iri="https://schema.org/Product")
 * @ODM\Document
 */
class RelatedOwningDummy
{
    /**
     * @ODM\Id(strategy="INCREMENT", type="int")
     */
    private $id;

    /**
     * @var string A name
     *
     * @ODM\Field(type="string")
     */
    public $name;

    /**
     * @var Dummy
     *
     * @ODM\ReferenceOne(targetDocument=Dummy::class, cascade={"persist"}, mappedBy="relatedOwningDummy")
     * @ApiSubresource
     */
    public $ownedDummy;

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    /**
     * Get owned dummy.
     *
     * @return Dummy
     */
    public function getOwnedDummy()
    {
        return $this->ownedDummy;
    }

    /**
     * Set owned dummy.
     *
     * @param Dummy $ownedDummy the value to set
     */
    public function setOwnedDummy(Dummy $ownedDummy)
    {
        $this->ownedDummy = $ownedDummy;

        if ($this !== $this->ownedDummy->getRelatedOwningDummy()) {
            $this->ownedDummy->setRelatedOwningDummy($this);
        }
    }
}


text:
// Copyright 2016, 2015, 2014 Matthias Koch
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using TestFx.Utilities.Collections;

namespace TestFx.Utilities
{
  public interface IIdentifiableCollectionUtility
  {
    [CanBeNull]
    T SearchNode<T> (IEnumerable<T> nodes, IIdentity identity, Func<T, IEnumerable<T>> childrenSelector)
        where T : class, IIdentifiable;

    [CanBeNull]
    T SearchNode<T> (IEnumerable<T> nodes, IIdentity identity)
        where T : class, IIdentifiable;
  }

  internal class IdentifiableCollectionUtility : IIdentifiableCollectionUtility
  {
    public static IIdentifiableCollectionUtility Instance = new IdentifiableCollectionUtility();

    [CanBeNull]
    public T SearchNode<T> (IEnumerable<T> nodes, IIdentity identity, Func<T, IEnumerable<T>> childrenSelector)
        where T : class, IIdentifiable
    {
      var nodesList = nodes.ToList();

      var commonParentIdentity = nodesList.Select(x => x.Identity.Parent).Distinct().Single();
      var identityChain = identity.DescendantsAndSelf(x => x.Parent).TakeWhile(x => !x.Equals(commonParentIdentity));
      var identityStack = new Stack<IIdentity>(identityChain);

      T node = null;
      do
      {
        var children = node == null ? nodesList : childrenSelector(node);
        node = children.Search(identityStack.Pop());
      } while (node != null && identityStack.Count > 0);

      return node;
    }

    [CanBeNull]
    public T SearchNode<T> (IEnumerable<T> nodes, IIdentity identity)
        where T : class, IIdentifiable
    {
      Trace.Assert(identity.Parent != null, "Parent != null");

      // TODO: overwrite == operator?
      return nodes.SingleOrDefault(x => x.Identity.Equals(identity));
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Asterina rhabdodendri var. rhabdodendri

### Remarks
null


text:
package Boj_2822;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class Main {
	private static final String SPACE = " ";

	public static void main(String args[]) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Person[] persons = new Person[8];

		for (int i = 1; i <= 8; i++) {
			persons[i - 1] = new Person(i, Integer.parseInt(br.readLine().trim()));
		}

		br.close();

		Arrays.sort(persons, Person.comparatorByScore);
		Arrays.sort(persons, 0, 5, Person.comparatorByIdx);

		int sum = 0;
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < 5; i++) {
			sum += persons[i].score;
			sb.append(persons[i].idx).append(SPACE);
		}

		System.out.println(sum);
		System.out.println(sb.toString());
	}

	private static class Person {
		public int idx;
		public int score;

		public Person(int idx, int score) {
			this.idx = idx;
			this.score = score;
		}

		public static Comparator<Person> comparatorByScore = new Comparator<Main.Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				if (p1.score > p2.score) {
					return -1;
				}

				else if (p1.score == p2.score) {
					return 0;
				}

				else {
					return 1;
				}
			}
		};

		public static Comparator<Person> comparatorByIdx = new Comparator<Main.Person>() {
			@Override
			public int compare(Person p1, Person p2) {
				if (p1.idx < p2.idx) {
					return -1;
				}

				else if (p1.idx == p2.idx) {
					return 0;
				}

				else {
					return 1;
				}
			}
		};
	}
}


text:
package unnamed.network.event;

public interface INetworkEventType {
    NetworkEvent createPacket();

    EventDirection getDirection();

    boolean isCompressed();

    boolean isChunked();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hyménomycètes (Alençon) 159 (1874)

#### Original name
Agaricus cerinus Pers., 1794

### Remarks
null


text:
import {Build} from "./build.model";
export enum BuildBuildState {
  Pending,
  Running,
  Succeed,
  Failed
}

/*

export interface BuildDashboardItem extends DashboardItemView<Build>{

}
*/


text:
var express = require('express')
var http = require('http')
var influx = require('../../')

var app = express()
var serverInflux = influx()
var dbInflux = influx({host: 'localhost', username: 'example_response_dbuser', password: 'P85sw0rD', database: 'example_response'})

app.use(express.logger('dev'))

/**
 * LOOKING FOR JUST THE MIDDLEWARE?
 *
 *    THEN COPY THIS PART
 *
 *  WARNING: CHANGE THE ERROR THROW
 */

// TODO: Wait and then send multiple points within suitable timeframe.

app.use(function (req, res, next) {
  var startTime = new Date()
  function logRequest () {
    res.removeListener('finish', logRequest)
    res.removeListener('close', logRequest)
    dbInflux.writePoint('response_times', { time: startTime, value: (new Date()) - startTime }, function (err) {
      if (err) throw err
    })
  }
  res.on('finish', logRequest)
  res.on('close', logRequest)
  return next()
})

/**
 *      AND STOP HERE
 */

app.get('/', function (req, res) {
  setTimeout(function () {
    res.send('Good Day.')
  }, Math.random() * 500)
})

function startApp () {
  http.createServer(app).listen(3000, function () {
    console.log('Listening on port 3000')
  })
}

console.log('Checking DB Exists')
serverInflux.getDatabaseNames(function (err, dbs) {
  if (err) throw err
  if (dbs.indexOf('example_response') === -1) {
    console.log('Creating Database')
    serverInflux.createDatabase('example_response', function (err) {
      if (err) throw err
      console.log('Creating User')
      serverInflux.createUser('example_response', 'example_response_dbuser', 'P85sw0rD', function (err) {
        if (err) throw err
        startApp()
      })
    })
  } else {
    startApp()
  }
})


text:
"""
create a fake IRC server using some pretty simple techniques.  basically
meant as a way to allow easy pretend input.
"""

import getopt, os, select, socket, sys, threading, time

# go ahead and create a miniature 'server' class to make it easy to lock
# down for the threads...
class fake_server(object):
    def __init__(self, name, password, uplink):
        self.name = name
        self.password = password
        self.uplink = uplink

        self.lock = threading.Lock()
        self.iothread = threading.Thread(target = self.io)
        self.iothread.setDaemon(True)
        self.parsethread = threading.Thread(target = self.parser)
        self.parsethread.setDaemon(True)

        self.writeq = list()
        self.readq = list()
        self.readq_cv = threading.Condition()

        self.rbuf = ""
        self.sock = None
    # end of __init__

    def parse(self, line):
        """parse an individual line of input"""

        # output a slightly formatted version of the line
        print "<<< %s" % line

        # split the line.  first find (if any exists) the remaining
        # arguments from the command, they'll be preceded by a : that isn't
        # the first character in the string.
        lastarg = ""
        idx = line.rfind(":")
        if idx > 0:
            lastarg = line[idx + 1:]
            line = line[:idx].rstrip()
        args = line.split(" ")
        if lastarg:
            args.append(lastarg)

        sender = ""
        if args[0][0] == ":":
            sender = args[0][1:]
            args = args[1:]

        cmd = ""
        if args:
            cmd = args[0]
            args = args[1:]

        # okay, we've now got a sender, cmd, and arguments so we can decide
        # what to reply to.. right now we don't reply to a whole hell of a
        # lot
        if not cmd: return
        elif cmd.upper() == "PING":
            self.send("PONG %s :%s" % (self.name, args[0]))

    # end of parse

    def send(self, line):
        self.lock.acquire()
        self.writeq.append("%s\r\n" % line)
        self.lock.release()
        print ">>> %s" % line
    # end of send

    def start(self):
        self.iothread.start()
        self.parsethread.start()

        # make with the eating of input
        while True:
            try:
                line = raw_input()
                self.send(line)
            except KeyboardInterrupt:
                sys.exit(0)

    def io(self):
        """main I/O looping facility.  selects on the desciptor to see if
        I/O is ready and handles some very simple connectivity stuff"""

        while True:
            # infloop this stuff..
            if not self.sock:
                self.sock = socket.socket()
                self.sock.setblocking(True)
                self.sock.connect((self.uplink, 6667))
                self.sock.setblocking(False)
                self.send("PROTOCOL dreamforge")
                self.send("PASS %s" % self.password)
                self.send("SERVER %s 1 :test server" % self.name)

            # if the socket isn't connected an error will get thrown.  need
            # to wrap stuff to deal with this
            (rlist, wlist, xlist) = select.select([self.sock], [self.sock],
                                                  [], 0.05)
            # lock now in anticipation of changing stuff...
            if rlist:
                self.readq_cv.acquire()
                self.rbuf += self.sock.recv(1024)
                self.rbuf = self.rbuf.strip("\r")
                idx = 0
                while idx != -1:
                    idx = self.rbuf.find("\n")
                    if idx != -1:
                        self.readq.append(self.rbuf[:idx])
                        self.rbuf = self.rbuf[idx + 1:]
                if self.readq: self.readq_cv.notify()
                self.readq_cv.release()
            if wlist:
                # I have no interest in dealing with write failures.
                self.lock.acquire()
                self.sock.setblocking(True)
                for line in self.writeq:
                    self.sock.send(line)
                self.writeq = list()
                self.sock.setblocking(False)
                self.lock.release()

    # end of io

    def parser(self):
        while True:
            # loop on the work queue..
            self.readq_cv.acquire()
            while not self.readq:
                self.readq_cv.wait()
            # got it.
            for line in self.readq:
                self.parse(line)
            self.readq = list()
            self.readq_cv.release()

    # end of parser

# suck up options to override the above variables
my_name = "test.server"
my_password = "test.pass"
my_uplink = "127.0.0.1"
opts = getopt.getopt(sys.argv[1:], "n:p:u:")[0]
for opt, val in opts:
    if opt == "-n": my_name = val
    elif opt == "-p": my_password = val
    elif opt == "-u": my_uplink = val

server = fake_server(my_name, my_password, my_uplink)
server.start()


text:
package v1alpha1

import (
	v1alpha1 "github.com/google/kf/v2/pkg/apis/kf/v1alpha1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/tools/cache"
)

// AppLister helps list Apps.
// All objects returned here must be treated as read-only.
type AppLister interface {
	// List lists all Apps in the indexer.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha1.App, err error)
	// Apps returns an object that can list and get Apps.
	Apps(namespace string) AppNamespaceLister
	AppListerExpansion
}

// appLister implements the AppLister interface.
type appLister struct {
	indexer cache.Indexer
}

// NewAppLister returns a new AppLister.
func NewAppLister(indexer cache.Indexer) AppLister {
	return &appLister{indexer: indexer}
}

// List lists all Apps in the indexer.
func (s *appLister) List(selector labels.Selector) (ret []*v1alpha1.App, err error) {
	err = cache.ListAll(s.indexer, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha1.App))
	})
	return ret, err
}

// Apps returns an object that can list and get Apps.
func (s *appLister) Apps(namespace string) AppNamespaceLister {
	return appNamespaceLister{indexer: s.indexer, namespace: namespace}
}

// AppNamespaceLister helps list and get Apps.
// All objects returned here must be treated as read-only.
type AppNamespaceLister interface {
	// List lists all Apps in the indexer for a given namespace.
	// Objects returned here must be treated as read-only.
	List(selector labels.Selector) (ret []*v1alpha1.App, err error)
	// Get retrieves the App from the indexer for a given namespace and name.
	// Objects returned here must be treated as read-only.
	Get(name string) (*v1alpha1.App, error)
	AppNamespaceListerExpansion
}

// appNamespaceLister implements the AppNamespaceLister
// interface.
type appNamespaceLister struct {
	indexer   cache.Indexer
	namespace string
}

// List lists all Apps in the indexer for a given namespace.
func (s appNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.App, err error) {
	err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
		ret = append(ret, m.(*v1alpha1.App))
	})
	return ret, err
}

// Get retrieves the App from the indexer for a given namespace and name.
func (s appNamespaceLister) Get(name string) (*v1alpha1.App, error) {
	obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
	if err != nil {
		return nil, err
	}
	if !exists {
		return nil, errors.NewNotFound(v1alpha1.Resource("app"), name)
	}
	return obj.(*v1alpha1.App), nil
}


text:
namespace AngleSharp.Css.Declarations
{
    using AngleSharp.Css.Dom;
    using System;
    using static ValueConverters;

    static class BorderRightDeclaration
    {
        public static String Name = PropertyNames.BorderRight;

        public static String[] Shorthands = new[]
        {
            PropertyNames.Border,
        };

        public static IValueConverter Converter = WithBorderSide(
            InitialValues.BorderRightWidthDecl,
            InitialValues.BorderRightStyleDecl,
            InitialValues.BorderRightColorDecl);

        public static ICssValue InitialValue = null;

        public static PropertyFlags Flags = PropertyFlags.Animatable | PropertyFlags.Shorthand;

        public static String[] Longhands = new[]
        {
            PropertyNames.BorderRightWidth,
            PropertyNames.BorderRightStyle,
            PropertyNames.BorderRightColor,
        };
    }
}


text:
#include <gtest/gtest.h>

#include <iostream>
#include <numeric>

#if defined _MSC_VER
    #pragma warning (disable: 4521)
#endif

#include <pcl/point_cloud.h>
#include <pcl/octree/octree.h>

#if defined _MSC_VER
    #pragma warning (default: 4521)
#endif

#include <pcl/gpu/octree/octree.hpp>
#include <pcl/gpu/containers/device_array.h>

#include "data_source.hpp"

using namespace std;
using namespace pcl::gpu;

//TEST (PCL_GPU, DISABLED_bruteForceRadiusSeachGPU)
TEST (PCL_GPU, bruteForceRadiusSeachGPU)
{
    DataGenerator data;
    data.data_size = 871000;
    data.tests_num = 100;
    data.cube_size = 1024.f;
    data.max_radius    = data.cube_size/15.f;
    data.shared_radius = data.cube_size/20.f;
    data.printParams();

    //generate
    data();

    // brute force radius search
    data.bruteForceSearch();

    //prepare gpu cloud
    pcl::gpu::Octree::PointCloud cloud_device;
    cloud_device.upload(data.points);

    pcl::gpu::DeviceArray<int> results_device, buffer(cloud_device.size());

    vector<int> results_host;
    vector<size_t> sizes;
    for(size_t i = 0; i < data.tests_num; ++i)
    {
        pcl::gpu::bruteForceRadiusSearchGPU(cloud_device, data.queries[i], data.radiuses[i], results_device, buffer);

        results_device.download(results_host);
        std::sort(results_host.begin(), results_host.end());

        ASSERT_EQ ( (results_host == data.bfresutls[i]), true );
        sizes.push_back(results_device.size());
    }

    float avg_size = std::accumulate(sizes.begin(), sizes.end(), (size_t)0) * (1.f/sizes.size());;

    cout << "avg_result_size = " << avg_size << endl;
    ASSERT_GT(avg_size, 5);
}


text:
.class final Lcom/android/server/power/DisplayPowerRequest;
.super Ljava/lang/Object;
.source "DisplayPowerRequest.java"

# static fields
.field public static final SCREEN_STATE_BRIGHT:I = 0x2

.field public static final SCREEN_STATE_DIM:I = 0x1

.field public static final SCREEN_STATE_OFF:I

# instance fields
.field public blockScreenOn:Z

.field public screenAutoBrightnessAdjustment:F

.field public screenBrightness:I

.field public screenState:I

.field public useAutoBrightness:Z

.field public useProximitySensor:Z

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

    .prologue
    const/4 v1, 0x0

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

    .line 66
    const/4 v0, 0x2

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    .line 67
    iput-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    .line 68
    const/16 v0, 0xff

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    .line 69
    const/4 v0, 0x0

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    .line 70
    iput-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    .line 71
    iput-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    .line 72
    return-void
.end method

.method public constructor <init>(Lcom/android/server/power/DisplayPowerRequest;)V
    .locals 0
    .parameter "other"

    .prologue
    .line 74
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 75
    invoke-virtual {p0, p1}, Lcom/android/server/power/DisplayPowerRequest;->copyFrom(Lcom/android/server/power/DisplayPowerRequest;)V

    .line 76
    return-void
.end method

# virtual methods
.method public copyFrom(Lcom/android/server/power/DisplayPowerRequest;)V
    .locals 1
    .parameter "other"

    .prologue
    .line 79
    iget v0, p1, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    .line 80
    iget-boolean v0, p1, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    iput-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    .line 81
    iget v0, p1, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    .line 82
    iget v0, p1, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    iput v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    .line 83
    iget-boolean v0, p1, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    iput-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    .line 84
    iget-boolean v0, p1, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    iput-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    .line 85
    return-void
.end method

.method public equals(Lcom/android/server/power/DisplayPowerRequest;)Z
    .locals 2
    .parameter "other"

    .prologue
    .line 94
    if-eqz p1, :cond_0

    iget v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    iget v1, p1, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    if-ne v0, v1, :cond_0

    iget-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    iget-boolean v1, p1, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    if-ne v0, v1, :cond_0

    iget v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    iget v1, p1, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    if-ne v0, v1, :cond_0

    iget v0, p0, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    iget v1, p1, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    cmpl-float v0, v0, v1

    if-nez v0, :cond_0

    iget-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    iget-boolean v1, p1, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    if-ne v0, v1, :cond_0

    iget-boolean v0, p0, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    iget-boolean v1, p1, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    if-ne v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public equals(Ljava/lang/Object;)Z
    .locals 1
    .parameter "o"

    .prologue
    .line 89
    instance-of v0, p1, Lcom/android/server/power/DisplayPowerRequest;

    if-eqz v0, :cond_0

    check-cast p1, Lcom/android/server/power/DisplayPowerRequest;

    .end local p1
    invoke-virtual {p0, p1}, Lcom/android/server/power/DisplayPowerRequest;->equals(Lcom/android/server/power/DisplayPowerRequest;)Z

    move-result v0

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public hashCode()I
    .locals 1

    .prologue
    .line 105
    const/4 v0, 0x0

    return v0
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    .prologue
    .line 110
    new-instance v0, Ljava/lang/StringBuilder;

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

    const-string v1, "screenState="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Lcom/android/server/power/DisplayPowerRequest;->screenState:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", useProximitySensor="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->useProximitySensor:Z

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", screenBrightness="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Lcom/android/server/power/DisplayPowerRequest;->screenBrightness:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", screenAutoBrightnessAdjustment="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Lcom/android/server/power/DisplayPowerRequest;->screenAutoBrightnessAdjustment:F

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(F)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", useAutoBrightness="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->useAutoBrightness:Z

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, ", blockScreenOn="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-boolean v1, p0, Lcom/android/server/power/DisplayPowerRequest;->blockScreenOn:Z

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
var functions = require("./../js/functions.js");

describe("Functions:", function () {
    it("splitRows splits content by \\n", function () {
        expect(functions.splitRows("foo\nbar\nbaz", "\n")).toEqual(["foo", "bar", "baz"]);
    });

    it("splitColumns splits rows by ;", function () {
        expect(functions.splitColumns(["1;2", "3;4", "5;6"], ";")).toEqual([["1", "2"], ["3", "4"], ["5", "6"]]);
    });

    it("converts row to template data", function () {
        expect(functions.convertRowToTemplateData(["foo", "baz", "bar"])).toEqual({a: "foo", b: "baz", c: "bar"});
    });
});


text:
This is a test function library for testing that `NodeContext.compileLibrary` works as expected.

The file `expected-libtest.js` is the expected unminified bundle


text:
import React from 'react';

function mockViewComponent(type) {
  const Component = React.createClass({
    displayName: type,
    propTypes: { children: React.PropTypes.node },
    render() { return React.DOM.div(this.props, this.props.children); },
  });

  return Component;
}

export const View = mockViewComponent('View');
export const Text = mockViewComponent('Text');
export const ScrollView = mockViewComponent('ScrollView');

export const StyleSheet = {
  create: (ss) => ss
};

export const PropTypes = React.PropTypes;
export const NativeModules = {
  Constants: {
    app_id: 'testid'
  },
};

export default {
  ...React,
  StyleSheet,
  PropTypes,
  NativeModules,
  View,
  Text,
  ScrollView
};


text:
echo on
erase1 <data\erase

for %%i in (  capacity.exe erase2.exe find_ops.exe
			  find-str.exe refreshIter.exe stack.exe
			  str_assignOps.exe substr.exe useConvs.exe ) do %%i


text:
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.ProjectSystem;

namespace ZXSpectrumCodeDiscover
{
    /// <summary>
    /// Updates nodes in the project tree by overriding property values calculated so far by lower priority providers.
    /// </summary>
    [Export(typeof(IProjectTreePropertiesProvider))]
    [AppliesTo(MyUnconfiguredProject.UNIQUE_CAPABILITY)]
    public class CodeDiscoverProjectTreePropertiesProvider : IProjectTreePropertiesProvider
    {
        /// <summary>
        /// Calculates new property values for each node in the project tree.
        /// </summary>
        /// <param name="propertyContext">Context information that can be used for the calculation.</param>
        /// <param name="propertyValues">Values calculated so far for the current node by lower priority tree properties providers.</param>
        public void CalculatePropertyValues(
            IProjectTreeCustomizablePropertyContext propertyContext,
            IProjectTreeCustomizablePropertyValues propertyValues)
        {
            // Only set the icon for the root project node.  We could choose to set different icons for nodes based
            // on various criteria, not just Capabilities, if we wished.
            if (propertyValues.Flags.Contains(ProjectTreeFlags.Common.ProjectRoot))
            {
                propertyValues.Icon = ImageMonikers.ProjectIconImageMoniker.ToProjectSystemType();
            }
        }
    }
}


text:
layout: post
title: Wenn du Antworten zu C# in Deutsch brauchst, ...
date: 2015-10-20T06:00:00+02:00
excerpt: InspirationsMoment - myCSharp.de
modified:
share: false
categories: csharp-programmieren
lernmoment: C#
lm-newsletter-group-id: 1
show-lm-newsletter-subscribe-box: true
tags: [Inspiration, Lernen, Werkzeug]
image:
  feature: banner/lernmoment-csharp.jpg
---

... kannst du mir gerne deine Frage [schicken](mailto:jan@lernmoment.de). Du kannst allerdings auch zu dem größten Forum für C# und .NET im deutschsprachigem Raum gehen. Dieses findest du unter [myCSharp.de](http://www.mycsharp.de).

Es gibt dort zu vielen verschiedenen Themen wie beispielsweise [GUI: WPF und Silverlight](http://www.mycsharp.de/wbb2/board.php?boardid=85) oder auch [Entwicklungs- und Laufzeitumgebung](http://www.mycsharp.de/wbb2/board.php?boardid=50) ein eigenes Unterforum.

Zusätzlich machen sich manche *User* viel Mühe beim schreiben eigener [Artikel](http://www.mycsharp.de/wbb2/board.php?boardid=69) nur für das Forum. So gibt es zum Thema [Delegate, anonyme Methoden, Lambda-Ausdrücke & Co.](http://www.mycsharp.de/wbb2/thread.php?threadid=74181) einen Artikel der in viele kleine Details geht und endlich mal Licht ins Dunkel bringt.

Wenn du konkrete Fragen hast und diese auf Deutsch beantwortet haben möchtest, ist [myCSharp.de](http://www.mycsharp.de) sicherlich ein guter Startpunkt. Du solltest allerdings erst die *Regeln* lesen. Sonst wird der Ton der *User* und *Admins* schon mal rauer.

Viel Spaß beim Antworten Finden im Forum

Jan

PS: Hast du Fragen zu diesem InspirationsMoment, oder anderen Themen auf LernMoment.de? Dann schicke mir eine [E-Mail](mailto:jan@lernmoment.de)


text:
@interface FLOrderedCollection : NSObject<NSCopying, NSMutableCopying, NSFastEnumeration> {
@private
	NSMutableDictionary* _objectDictionary;
	NSMutableDictionary* _indexes;
	NSMutableArray* _keys;
	NSMutableArray* _objectArray;
    unsigned long _mutationCount;
}

@property (readonly, strong, nonatomic) NSArray* objectArray;
@property (readonly, assign, nonatomic) NSUInteger count;
@property (readonly, strong, nonatomic) id firstObject;
@property (readonly, strong, nonatomic) id lastObject;

@property (readonly, strong, nonatomic) id<NSFastEnumeration> forwardKeyEnumerator;
@property (readonly, strong, nonatomic) id<NSFastEnumeration> forwardObjectEnumerator;

- (id) initWithCapacity:(NSUInteger) capacity;

+ (FLOrderedCollection*) orderedCollection;
+ (FLOrderedCollection*) orderedCollectionWithCapacity:(NSUInteger) capacity;

// setting an object will add it to the end of the array if it's not already in collection
- (void) setObject:(id) object forKey:(id) key;
- (id) objectForKey:(id) key;
- (id) objectAtIndex:(NSUInteger) idx;

- (void) removeObjectForKey:(id) key;
- (void) removeObjectAtIndex:(NSUInteger) idx;

- (void) removeObject:(id) object;
- (void) removeAllObjects;

- (id) replaceObjectAtIndex:(NSUInteger) atIndex withObject:(id) object forKey:(id) forKey;

- (NSUInteger) indexForKey:(id) key;
- (id) keyAtIndex:(NSUInteger) aIndex;

- (id) removeFirstObject;
- (id) removeLastObject;

// TODO
//- (void)sortUsingFunction:(NSInteger (*)(id, id, void *))compare context:(void *)context;
//- (void)sortUsingSelector:(SEL)comparator;

@end

//@property (readonly, copy, nonatomic) NSArray* objectArray;
//@property (readonly, strong, nonatomic) NSDictionary* objectDictionary;
//@property (readonly, strong, nonatomic) NSArray* keys;
//@property (readonly, strong, nonatomic) NSMutableDictionary* indexes;
//- (void) addOrReplaceObject:(id) object forKey:(id) key;


text:
from django.template.context import Context
from functools import wraps

def private_context(f):
    """
    Simple decorator which avoids the need to a) copy-and-paste code to force
    context variables into inclusion_tag templates and b) carefully avoid
    inclusion tag variables conflicting with global variables.

    Instead each inclusion tag will be called with a *copy* of the provided
    context variable and its results will be merged in to avoid leaking into
    the global context

    Django's standard inclusion_tag doesn't include context variables by
    default. When you add takes_context you are required to manually merge the
    context variables into the dict which your tag returns, which tends to
    result in wasteful code or accidentally leaking variables into the global
    context with something like context.update() or name collisions.

    This decorator allows your inclusion tag to remain simple and still have
    safe access to the global context for things like MEDIA_URL:

    @register.inclusion_tag('my_template')
    @private_context
    def my_tag(context, …):
      return {"foo": 1, "bar": 2}

    See:
    http://www.djangosnippets.org/snippets/1687/

    """

    @wraps(f)
    def private_context_wrapper(context, *args, **kwargs):
        c = Context(context)
        rc = f(c, *args, **kwargs)
        c.update(rc)
        return c

    return private_context_wrapper


text:
using System;

namespace WallNetCoreTest
{
    public static class TestExtensions
    {
        public static void RunMultipleTimes(this Action function)
        {
            const int numRunTimes = 10000;
            RunMultipleTimes(function, numRunTimes);
        }

        public static void RunMultipleTimes(this Action function, int numRunTimes)
        {
            for(int i = 0; i < numRunTimes; ++i)
            {
                function();
            }
        }
    }
}


text:
package net.chriswareham.gui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import javax.swing.AbstractListModel;
import javax.swing.ComboBoxModel;

/**
 * This class provides a combo box model that maintains the natural ordering of
 * rows.
 *
 * @author Chris Wareham
 * @param <T> type of the objects that make up the rows of the model
 */
public class SortedComboBoxModel<T extends Comparable<? super T>> extends AbstractListModel<T> implements ComboBoxModel<T> {
    /**
     * The serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The list of rows that make up the model.
     */
    private final List<T> rows = new ArrayList<>();
    /**
     * The selected row index.
     */
    private T selectedRow;

    /**
     * Get the number of rows in the model.
     *
     * @return the number of rows
     */
    @Override
    public int getSize() {
        return rows.size();
    }

    /**
     * Get a row from the model.
     *
     * @param ri the row index
     * @return the row
     */
    @Override
    public T getElementAt(final int ri) {
        return rows.get(ri);
    }

    /**
     * Get the selected row.
     *
     * @return the selected row, or null if no row is selected
     */
    @Override
    public Object getSelectedItem() {
        return selectedRow;
    }

    /**
     * Set the selected row.
     *
     * @param o the selected row
     */
    @Override
    public void setSelectedItem(final Object o) {
        if ((selectedRow != null && !selectedRow.equals(o)) || (selectedRow == null && o != null)) {
            selectedRow = getRow(rows.indexOf(o));
            fireContentsChanged(this, -1, -1);
        }
    }

    /**
     * Set the index of the selected row from the model.
     *
     * @param ri the index of the selected row
     */
    public void setSelectedRowIndex(final int ri) {
        setSelectedItem(getRow(ri));
    }

    /**
     * Get the index of the selected row from the model.
     *
     * @return the index of the selected row, or -1 if no row is selected
     */
    public int getSelectedRowIndex() {
        return selectedRow != null ? rows.indexOf(selectedRow) : -1;
    }

    /**
     * Get the selected row from the model.
     *
     * @return the selected row, or null if no row is selected
     */
    public T getSelectedRow() {
        return selectedRow;
    }

    /**
     * Get a row from the model.
     *
     * @param ri the row index
     * @return the row, or null if the row index is out of range
     */
    public T getRow(final int ri) {
        return ri > -1 && ri < rows.size() ? rows.get(ri) : null;
    }

    /**
     * Get all the rows from the model.
     *
     * @return all the rows from the model
     */
    public List<T> getRows() {
        return Collections.unmodifiableList(rows);
    }

    /**
     * Add a row to the model.
     *
     * @param r the row to add
     */
    public void addRow(final T r) {
        int ri = addSortedRow(r);
        if (ri == 0 && selectedRow == null) {
            setSelectedRowIndex(0);
        }
    }

    /**
     * Add multiple rows to the model.
     *
     * @param r the rows to add
     */
    public void addRows(final T[] r) {
        addRows(Arrays.asList(r));
    }

    /**
     * Add multiple rows to the model.
     *
     * @param r the rows to add
     */
    public void addRows(final Collection<T> r) {
        for (T row : r) {
            addSortedRow(row);
        }
        if (!r.isEmpty() && selectedRow == null) {
            setSelectedRowIndex(0);
        }
    }

    /**
     * Remove a particular row from the model.
     *
     * @param r the row to remove
     */
    public void removeRow(final T r) {
        int ri = rows.indexOf(r);
        if (ri != -1) {
            removeRow(ri);
        }
    }

    /**
     * Remove a particular row from the model.
     *
     * @param ri the row index
     */
    public void removeRow(final int ri) {
        if (rows.get(ri) == selectedRow) {
            if (ri == 0) {
                setSelectedItem(rows.size() == 1 ? null : getRow(ri + 1));
            } else {
                setSelectedItem(getRow(ri - 1));
            }
        }
        rows.remove(ri);
        fireIntervalRemoved(this, ri, ri);
    }

    /**
     * Removes all rows from the model.
     */
    public void removeRows() {
        if (!rows.isEmpty()) {
            int ri = rows.size() - 1;
            rows.clear();
            selectedRow = null;
            fireIntervalRemoved(this, 0, ri);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void fireContentsChanged(final Object source, final int index0, final int index1) {
        Collections.sort(rows);
        super.fireContentsChanged(source, 0, rows.size() - 1);
    }

    /**
     * Add a row, maintaining the sort order.
     *
     * @param r the row to add
     * @return the index the row was added at
     */
    private int addSortedRow(final T r) {
        int ri = Collections.binarySearch(rows, r);
        if (ri < 0) {
            ri = ~ri;
        }
        rows.add(ri, r);
        fireIntervalAdded(this, ri, ri);
        return ri;
    }
}


text:
var EPSILON = require('./epsilon')

var Size = function (width, height) {
  // Parameters:
  //   width
  //     number, must be 0 or positive
  //   height
  //     number, must be 0 or positive
  //
  if (typeof width !== 'number' || typeof height !== 'number') {
    throw new Error('Missing or invalid (width, height) parameters')
  }
  if (width < 0 || height < 0) {
    throw new Error('Width and height must be zero or positive.')
  }

  this.width = width
  this.height = height
}

var proto = Size.prototype

proto.almostEqual = function (size) {
  return Math.abs(this.width - size.width) +
    Math.abs(this.height - size.height) < EPSILON
}

proto.equal = function (size) {
  return (this.width === size.width && this.height === size.height)
}

proto.getHeight = function () {
  return this.height
}

proto.getWidth = function () {
  return this.width
}

proto.min = function () {
  return Math.min(this.width, this.height)
}

proto.max = function () {
  return Math.max(this.width, this.height)
}

proto.toArray = function () {
  return [this.width, this.height]
}

proto.transform = function (tr) {
  // Transform the Size. Only scaling affects to the size.
  //
  // Parameters:
  //   tr
  //     a Transform
  //
  var s = tr.getScale()
  var w = this.width * s
  var h = this.height * s
  return new Size(w, h)
}

module.exports = Size


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.SDLK_KP0.html">

Redirecting to constant.SDLK_KP0.html...


text:
package com.digirati.elucidate.service.query;

import com.digirati.elucidate.common.model.annotation.oa.OAAnnotation;
import com.digirati.elucidate.common.model.annotation.oa.OAAnnotationCollection;

public interface OAAnnotationCollectionService extends AbstractAnnotationCollectionService<OAAnnotation, OAAnnotationCollection> {

}


text:
//-----------------------------------------------------------------------
// <copyright file="JuniorPlayerGridRow.cs" company="Hyperar">
//     Copyright (c) Hyperar. All rights reserved.
// </copyright>
// <author>Matías Ezequiel Sánchez</author>
//-----------------------------------------------------------------------
namespace Hyperar.HattrickUltimate.BusinessObjects.UI
{
    using Interface;

    /// <summary>
    /// Represents a Junior Player Grid Row.
    /// </summary>
    public class JuniorPlayerGridRow : HattrickEntityBase, IHattrickEntity
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets the Age.
        /// </summary>
        public byte Age { get; set; }

        /// <summary>
        /// Gets or sets the Age Days.
        /// </summary>
        public byte AgeDays { get; set; }

        /// <summary>
        /// Gets or sets Avatar image bytes.
        /// </summary>
        public byte[] Avatar { get; set; }

        /// <summary>
        /// Gets or sets the Booking Status.
        /// </summary>
        public byte BookingStatus { get; set; }

        /// <summary>
        /// Gets or sets the Career Goals.
        /// </summary>
        public short CareerGoals { get; set; }

        /// <summary>
        /// Gets or sets the Career Goals Delta.
        /// </summary>
        public int? CareerGoalsDelta { get; set; }

        /// <summary>
        /// Gets or sets the Career Hattricks.
        /// </summary>
        public short CareerHattricks { get; set; }

        /// <summary>
        /// Gets or sets the Career Hattricks Delta.
        /// </summary>
        public int? CareerHattricksDelta { get; set; }

        /// <summary>
        /// Gets or sets the Category.
        /// </summary>
        public byte? Category { get; set; }

        /// <summary>
        /// Gets or sets the Defending.
        /// </summary>
        public int? Defending { get; set; }

        /// <summary>
        /// Gets or sets the Defending Delta.
        /// </summary>
        public int? DefendingDelta { get; set; }

        /// <summary>
        /// Gets or sets the Defending Max.
        /// </summary>
        public int? DefendingMax { get; set; }

        /// <summary>
        /// Gets or sets the First Name.
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Gets or sets the Health Status.
        /// </summary>
        public int HealthStatus { get; set; }

        /// <summary>
        /// Gets or sets the Health Status Delta.
        /// </summary>
        public int? HealthStatusDelta { get; set; }

        /// <summary>
        /// Gets or sets the Junior Team ID.
        /// </summary>
        public int JuniorTeamId { get; set; }

        /// <summary>
        /// Gets or sets the Keeper.
        /// </summary>
        public int? Keeper { get; set; }

        /// <summary>
        /// Gets or sets the Keeper Delta.
        /// </summary>
        public int? KeeperDelta { get; set; }

        /// <summary>
        /// Gets or sets the KeeperMax.
        /// </summary>
        public int? KeeperMax { get; set; }

        /// <summary>
        /// Gets or sets the Age.
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// Gets or sets the Nick Name.
        /// </summary>
        public string NickName { get; set; }

        /// <summary>
        /// Gets or sets the Passing.
        /// </summary>
        public int? Passing { get; set; }

        /// <summary>
        /// Gets or sets the Passing Delta.
        /// </summary>
        public int? PassingDelta { get; set; }

        /// <summary>
        /// Gets or sets the Passing Max.
        /// </summary>
        public int? PassingMax { get; set; }

        /// <summary>
        /// Gets or sets the Playmaking.
        /// </summary>
        public int? Playmaking { get; set; }

        /// <summary>
        /// Gets or sets the Playmaking Delta.
        /// </summary>
        public int? PlaymakingDelta { get; set; }

        /// <summary>
        /// Gets or sets the Playmaking Max.
        /// </summary>
        public int? PlaymakingMax { get; set; }

        /// <summary>
        /// Gets or sets the Scoring.
        /// </summary>
        public int? Scoring { get; set; }

        /// <summary>
        /// Gets or sets the Scoring Delta.
        /// </summary>
        public int? ScoringDelta { get; set; }

        /// <summary>
        /// Gets or sets the Scoring Max.
        /// </summary>
        public int? ScoringMax { get; set; }

        /// <summary>
        /// Gets or sets the Set Pieces.
        /// </summary>
        public int? SetPieces { get; set; }

        /// <summary>
        /// Gets or sets the Set Pieces Delta.
        /// </summary>
        public int? SetPiecesDelta { get; set; }

        /// <summary>
        /// Gets or sets the Set Pieces Max.
        /// </summary>
        public int? SetPiecesMax { get; set; }

        /// <summary>
        /// Gets or sets the Shirt Number.
        /// </summary>
        public byte? ShirtNumber { get; set; }

        /// <summary>
        /// Gets or sets the Specialty.
        /// </summary>
        public byte? Specialty { get; set; }

        /// <summary>
        /// Gets or sets the Winger.
        /// </summary>
        public int? Winger { get; set; }

        /// <summary>
        /// Gets or sets the Winger Delta.
        /// </summary>
        public int? WingerDelta { get; set; }

        /// <summary>
        /// Gets or sets the Winger Max.
        /// </summary>
        public int? WingerMax { get; set; }

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        /// Returns a System.String that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return string.IsNullOrWhiteSpace(this.NickName)
                 ? $"{this.FirstName} {this.LastName} ({this.HattrickId})"
                 : $"{this.FirstName} \"{this.NickName}\" {this.LastName} ({this.HattrickId})";
        }

        #endregion Public Methods
    }
}


text:
<p>
  Home Works!
</p>
<button class="btn btn-success"></button>


text:
<?php
/**
 * Created by PhpStorm.
 * User: exodus4d
 * Date: 29.07.2017
 * Time: 16:49
 */

namespace Exodus4D\Pathfinder\Model\Universe;

use DB\SQL\Schema;

class ConstellationModel extends AbstractUniverseModel {

    /**
     * @var string
     */
    protected $table = 'constellation';

    /**
     * @var array
     */
    protected $fieldConf = [
        'name' => [
            'type' => Schema::DT_VARCHAR128,
            'nullable' => false,
            'default' => ''
        ],
        'regionId' => [
            'type' => Schema::DT_INT,
            'index' => true,
            'belongs-to-one' => 'Exodus4D\Pathfinder\Model\Universe\RegionModel',
            'constraint' => [
                [
                    'table' => 'region',
                    'on-delete' => 'CASCADE'
                ]
            ],
            'validate' => 'notDry'
        ],
        'x' => [
            'type' => Schema::DT_BIGINT,
            'nullable' => false,
            'default' => 0
        ],
        'y' => [
            'type' => Schema::DT_BIGINT,
            'nullable' => false,
            'default' => 0
        ],
        'z' => [
            'type' => Schema::DT_BIGINT,
            'nullable' => false,
            'default' => 0
        ],
        'systems' => [
            'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemModel', 'constellationId']
        ],
        'systemNeighbours' => [
            'has-many' => ['Exodus4D\Pathfinder\Model\Universe\SystemNeighbourModel', 'constellationId']
        ]
    ];

    /**
     * get data
     * @return \stdClass
     */
    public function getData(){
        $constellationData          = (object) [];
        $constellationData->id      = $this->_id;
        $constellationData->name    = $this->name;
        $constellationData->region  = $this->regionId->getData();

        return $constellationData;
    }

    /**
     * @param int $id
     * @param string $accessToken
     * @param array $additionalOptions
     */
    protected function loadData(int $id, string $accessToken = '', array $additionalOptions = []){
        $data = self::getF3()->ccpClient()->send('getUniverseConstellation', $id);
        if(!empty($data)){
            /**
             * @var $region RegionModel
             */
            $region = $this->rel('regionId');
            $region->loadById($data['regionId'], $accessToken, $additionalOptions);
            $data['regionId'] = $region;

            $this->copyfrom($data, ['id', 'name', 'regionId', 'position']);
            $this->save();
        }
    }

    /**
     * load systems data for this constellation
     */
    public function loadSystemsData(){
        if( !$this->dry() ){
            $data = self::getF3()->ccpClient()->send('getUniverseConstellation', $this->_id);
            if(!empty($data)){
                foreach((array)$data['systems'] as $systemId){
                    /**
                     * @var $system SystemModel
                     */
                    $system = $this->rel('systems');
                    $system->loadById($systemId);
                    $system->reset();
                }
            }
        }
    }

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Bull. Soc. Bot. France 52(Mém. 3a):19. 1905

#### Original name
null

### Remarks
null


text:
<?php
namespace TYPO3\CMS\Backend\Form\Wizard;

use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Wizard for rendering an AJAX selector for records
 */
class ValueSliderWizard
{
    /**
     * Renders the slider value wizard
     *
     * @param array $params
     * @return string
     */
    public function renderWizard($params)
    {
        $field = $params['field'];
        if (is_array($params['row'][$field])) {
            $value = $params['row'][$field][0];
        } else {
            $value = $params['row'][$field];
        }
        // If Slider is used in a flexform
        if (!empty($params['flexFormPath'])) {
            $flexFormTools = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Configuration\FlexForm\FlexFormTools::class);
            $flexFormValue = $flexFormTools->getArrayValueByPath($params['flexFormPath'], $params['row'][$field]);
            if ($flexFormValue !== null) {
                $value = $flexFormValue;
            }
        }
        $itemName = $params['itemName'];
        // Set default values (which correspond to those of the JS component)
        $min = 0;
        $max = 10000;
        // Use the range property, if defined, to set min and max values
        if (isset($params['fieldConfig']['range'])) {
            $min = isset($params['fieldConfig']['range']['lower']) ? (int)$params['fieldConfig']['range']['lower'] : 0;
            $max = isset($params['fieldConfig']['range']['upper']) ? (int)$params['fieldConfig']['range']['upper'] : 10000;
        }
        $elementType = $params['fieldConfig']['type'];
        $step = $params['wConf']['step'] ?: 1;
        $width = (int)$params['wConf']['width'] ?: 400;
        $type = 'null';
        if (isset($params['fieldConfig']['eval'])) {
            $eval = GeneralUtility::trimExplode(',', $params['fieldConfig']['eval'], true);
            if (in_array('int', $eval, true)) {
                $type = 'int';
                $value = (int)$value;
            } elseif (in_array('double2', $eval, true)) {
                $type = 'double';
                $value = (double)$value;
            }
        }
        if (isset($params['fieldConfig']['items'])) {
            $type = 'array';
            $index = 0;
            $itemAmount = count($params['fieldConfig']['items']);
            for (; $index < $itemAmount; ++$index) {
                $item = $params['fieldConfig']['items'][$index];
                if ((string)$item[1] === $value) {
                    break;
                }
            }
            $min = 0;
            $max = $itemAmount -1;
            $step = 1;
            $value = $index;
        }
        $callbackParams = [ $params['table'], $params['row']['uid'], $params['field'], $params['itemName'] ];
        $id = 'slider-' . $params['md5ID'];
        $content =
            '<div'
                . ' id="' . $id . '"'
                . ' data-slider-id="' . $id . '"'
                . ' data-slider-min="' . $min . '"'
                . ' data-slider-max="' . $max . '"'
                . ' data-slider-step="' . htmlspecialchars($step) . '"'
                . ' data-slider-value="' . htmlspecialchars($value) . '"'
                . ' data-slider-value-type="' . htmlspecialchars($type) . '"'
                . ' data-slider-item-name="' . htmlspecialchars($itemName) . '"'
                . ' data-slider-element-type="' . htmlspecialchars($elementType) . '"'
                . ' data-slider-callback-params="' . htmlspecialchars(json_encode($callbackParams)) . '"'
                . ' style="width: ' . $width . 'px;"'
            . '></div>';

        return $content;
    }
}