text:
package com.fishercoder;

import com.fishercoder.solutions._504;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;

/**
 * Created by fishercoder on 1/15/17.
 */
public class _504Test {
    private static _504 test;
    private static String expected;
    private static String actual;
    private static int num;

    @BeforeClass
    public static void setup() {
        test = new _504();
    }

    @Before
    public void setupForEachTest() {
        expected = "";
        actual = "";
        num = 0;
    }

    @Test
    public void test1() {
        num = 100;
        expected = "202";
        actual = test.convertToBase7(num);
        assertEquals(expected, actual);
    }

    @Test
    public void test2() {
        num = -7;
        expected = "-10";
        actual = test.convertToBase7(num);
        assertEquals(expected, actual);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>cmput301w16t08.scaling_pancake.activities Class Hierarchy</title>
<meta name="date" content="2016-04-03">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package cmput301w16t08.scaling_pancake.activities

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

android.content.Context

android.content.ContextWrapper

android.view.ContextThemeWrapper

android.app.Activity (implements android.content.ComponentCallbacks2, android.view.KeyEvent.Callback, android.view.LayoutInflater.Factory2, android.view.View.OnCreateContextMenuListener, android.view.Window.Callback)

cmput301w16t08.scaling_pancake.activities.AddInstrumentActivity

android.support.v4.app.FragmentActivity (implements android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback, android.support.v4.app.ActivityCompatApi23.RequestPermissionsRequestCodeValidator)

android.support.v7.app.AppCompatActivity (implements android.support.v7.app.ActionBarDrawerToggle.DelegateProvider, android.support.v7.app.AppCompatCallback, android.support.v4.app.TaskStackBuilder.SupportParentable)

cmput301w16t08.scaling_pancake.activities.CreateProfileActivity

cmput301w16t08.scaling_pancake.activities.EditInstrumentActivity

cmput301w16t08.scaling_pancake.activities.EditProfileActivity

cmput301w16t08.scaling_pancake.activities.MainActivity

cmput301w16t08.scaling_pancake.activities.MenuActivity

cmput301w16t08.scaling_pancake.activities.RecordAudioActivity

cmput301w16t08.scaling_pancake.activities.SearchInstrumentsActivity

cmput301w16t08.scaling_pancake.activities.ViewInstrumentActivity

cmput301w16t08.scaling_pancake.activities.ViewLocationActivity (implements com.google.android.gms.maps.OnMapReadyCallback)

cmput301w16t08.scaling_pancake.activities.ViewProfileActivity

android.app.ListActivity

cmput301w16t08.scaling_pancake.activities.BidListActivity

cmput301w16t08.scaling_pancake.activities.DisplaySearchResultsActivity

cmput301w16t08.scaling_pancake.activities.InstrumentListActivity (implements android.widget.AdapterView.OnItemSelectedListener)

cmput301w16t08.scaling_pancake.activities.ViewBidActivity

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
/**
 * Container for routig configs
 *
 * @author ab
 */
package btools.router;

import java.io.File;

import btools.expressions.BExpressionContextNode;
import btools.expressions.BExpressionContextWay;
import btools.expressions.BExpressionMetaData;

public final class ProfileCache
{

  private static File lastLookupFile;
  private static long lastLookupTimestamp;

  private BExpressionContextWay expctxWay;
  private BExpressionContextNode expctxNode;
  private File lastProfileFile;
  private long lastProfileTimestamp;
  private boolean profilesBusy;
  private long lastUseTime;

  private static ProfileCache[] apc = new ProfileCache[1];
  private static boolean debug = Boolean.getBoolean( "debugProfileCache" );

  public static synchronized void setSize( int size )
  {
    apc = new ProfileCache[size];
  }

  public static synchronized boolean parseProfile( RoutingContext rc )
  {
      String profileBaseDir = System.getProperty( "profileBaseDir" );
      File profileDir;
      File profileFile;
      if ( profileBaseDir == null )
      {
        profileDir = new File( rc.localFunction ).getParentFile();
        profileFile = new File( rc.localFunction ) ;
      }
      else
      {
        profileDir = new File( profileBaseDir );
        profileFile = new File( profileDir, rc.localFunction + ".brf" ) ;
      }

      rc.profileTimestamp = profileFile.lastModified() + rc.getKeyValueChecksum()<<24;
      File lookupFile = new File( profileDir, "lookups.dat" );

      // invalidate cache at lookup-table update
      if ( !(lookupFile.equals( lastLookupFile ) && lookupFile.lastModified() == lastLookupTimestamp ) )
      {
        if ( lastLookupFile != null )
        {
          System.out.println( "******** invalidating profile-cache after lookup-file update ******** " );
        }
        apc = new ProfileCache[apc.length];
        lastLookupFile = lookupFile;
        lastLookupTimestamp = lookupFile.lastModified();
      }

      ProfileCache lru = null;
      int unusedSlot =-1;

      // check for re-use
      for( int i=0; i<apc.length; i++)
      {
        ProfileCache pc = apc[i];

        if ( pc != null )
        {
          if ( (!pc.profilesBusy) && profileFile.equals( pc.lastProfileFile ) )
          {
            if ( rc.profileTimestamp == pc.lastProfileTimestamp )
            {
              rc.expctxWay = pc.expctxWay;
              rc.expctxNode = pc.expctxNode;
              rc.readGlobalConfig();
              pc.profilesBusy = true;
              return true;
            }
            lru = pc; // name-match but timestamp-mismatch -> we overide this one
            unusedSlot = -1;
            break;
          }
          if ( lru == null || lru.lastUseTime > pc.lastUseTime )
          {
            lru = pc;
          }
        }
        else if ( unusedSlot < 0 )
        {
          unusedSlot = i;
        }
      }

      BExpressionMetaData meta = new BExpressionMetaData();

      rc.expctxWay = new BExpressionContextWay( rc.memoryclass * 512, meta );
      rc.expctxNode = new BExpressionContextNode( 0, meta );
      rc.expctxNode.setForeignContext( rc.expctxWay );

      meta.readMetaData( new File( profileDir, "lookups.dat" ) );

      rc.expctxWay.parseFile( profileFile, "global" );
      rc.expctxNode.parseFile( profileFile, "global" );

      rc.readGlobalConfig();

      if ( rc.processUnusedTags )
      {
        rc.expctxWay.setAllTagsUsed();
      }

      if ( lru == null || unusedSlot >= 0 )
      {
        lru = new ProfileCache();
        if ( unusedSlot >= 0 )
        {
          apc[unusedSlot] = lru;
          if ( debug ) System.out.println( "******* adding new profile at idx=" + unusedSlot + " for " +  profileFile );
        }
      }

      if ( lru.lastProfileFile != null )
      {
        if ( debug ) System.out.println( "******* replacing profile of age " + ((System.currentTimeMillis()-lru.lastUseTime)/1000L) + " sec " + lru.lastProfileFile + "->" + profileFile );
      }

      lru.lastProfileTimestamp = rc.profileTimestamp;
      lru.lastProfileFile = profileFile;
      lru.expctxWay = rc.expctxWay;
      lru.expctxNode = rc.expctxNode;
      lru.profilesBusy = true;
      lru.lastUseTime = System.currentTimeMillis();
      return false;
  }

  public static synchronized void releaseProfile( RoutingContext rc )
  {
    for( int i=0; i<apc.length; i++)
    {
      ProfileCache pc = apc[i];

      if ( pc != null )
      {
        // only the thread that holds the cached instance can release it
        if ( rc.expctxWay == pc.expctxWay && rc.expctxNode == pc.expctxNode )
        {
          pc.profilesBusy = false;
          break;
        }
      }
    }
    rc.expctxWay = null;
    rc.expctxNode = null;
  }

}


text:
using base::android::ScopedJavaLocalRef;

namespace gl {

ScopedJavaSurface::ScopedJavaSurface() {
}

ScopedJavaSurface::ScopedJavaSurface(
    const base::android::JavaRef<jobject>& surface) {
  JNIEnv* env = base::android::AttachCurrentThread();
  DCHECK(env->IsInstanceOf(surface.obj(), android_view_Surface_clazz(env)));
  j_surface_.Reset(surface);
}

ScopedJavaSurface::ScopedJavaSurface(const SurfaceTexture* surface_texture) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jobject> tmp(JNI_Surface::Java_Surface_ConstructorAVS_AGST(
      env, surface_texture->j_surface_texture()));
  DCHECK(!tmp.is_null());
  j_surface_.Reset(tmp);
}

ScopedJavaSurface::ScopedJavaSurface(ScopedJavaSurface&& rvalue) {
  MoveFrom(rvalue);
}

ScopedJavaSurface& ScopedJavaSurface::operator=(ScopedJavaSurface&& rhs) {
  MoveFrom(rhs);
  return *this;
}

ScopedJavaSurface::~ScopedJavaSurface() {
  ReleaseSurfaceIfNeeded();
}

void ScopedJavaSurface::ReleaseSurfaceIfNeeded() {
  if (auto_release_ && !j_surface_.is_null()) {
    JNIEnv* env = base::android::AttachCurrentThread();
    JNI_Surface::Java_Surface_releaseV(env, j_surface_);
  }
}

void ScopedJavaSurface::MoveFrom(ScopedJavaSurface& other) {
  ReleaseSurfaceIfNeeded();
  JNIEnv* env = base::android::AttachCurrentThread();
  j_surface_.Reset(env, other.j_surface_.Release());
  auto_release_ = other.auto_release_;
  is_protected_ = other.is_protected_;
}

bool ScopedJavaSurface::IsEmpty() const {
  return j_surface_.is_null();
}

bool ScopedJavaSurface::IsValid() const {
  JNIEnv* env = base::android::AttachCurrentThread();
  return !IsEmpty() && JNI_Surface::Java_Surface_isValidZ(env, j_surface_);
}

// static
ScopedJavaSurface ScopedJavaSurface::AcquireExternalSurface(jobject surface) {
  JNIEnv* env = base::android::AttachCurrentThread();
  ScopedJavaLocalRef<jobject> surface_ref;
  surface_ref.Reset(env, surface);
  ScopedJavaSurface scoped_surface(surface_ref);
  scoped_surface.auto_release_ = false;
  scoped_surface.is_protected_ = true;
  return scoped_surface;
}

}  // namespace gl


text:
package org.gradle.api.internal.classpath;

import org.gradle.util.GUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

public class DefaultPluginModuleRegistry implements PluginModuleRegistry {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPluginModuleRegistry.class);
    private final ModuleRegistry moduleRegistry;

    public DefaultPluginModuleRegistry(ModuleRegistry moduleRegistry) {
        this.moduleRegistry = moduleRegistry;
    }

    @Override
    public Set<Module> getApiModules() {
        Properties properties = loadPluginProperties("/gradle-plugins.properties");
        return loadModules(properties);
    }

    @Override
    public Set<Module> getImplementationModules() {
        Properties properties = loadPluginProperties("/gradle-implementation-plugins.properties");
        return loadModules(properties);
    }

    private Set<Module> loadModules(Properties properties) {
        Set<Module> modules = new LinkedHashSet<Module>();
        for (String pluginModule : properties.getProperty("plugins").split(",")) {
            try {
                modules.add(moduleRegistry.getModule(pluginModule));
            } catch (UnknownModuleException e) {
                // Ignore
                LOGGER.debug("Cannot find module for plugin {}. Ignoring.", pluginModule);
            }
        }
        return modules;
    }

    private Properties loadPluginProperties(String resource) {
        return GUtil.loadProperties(getClass().getResource(resource));
    }
}


text: require 'yui4rails'


text:
import { LitElement, html } from 'lit-element';

/**
 * This element renders its template contents as children, instead of
 * rendering into a shadow tree.
 */
class LightDom extends LitElement {
  render(){
    return html`

Render root overridden. Template renders without shadow DOM.

    `;
  }
  /**
   * To customize an element's render root, implement createRenderRoot. Return
   * the node into which to render the element's template.
   *
   * This element renders without shadow DOM.
   */
  createRenderRoot(){
    return this;
  }
}
customElements.define('light-dom', LightDom);


text:
using System;
using System.Globalization;
using Xamarin.Forms;

namespace TabbedPageDemo
{
    class NonNullToBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
            {
                return !String.IsNullOrEmpty((string)value);
            }

            return value != null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <link href="http://gmpg.org/xfn/11" rel="profile">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      404: Page not found · GroupGets

  </title>

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

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/atom+xml" title="GroupGets" href="/atom.xml">
  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

             24 Apr 2015 »

             Installation guide for Pure Breakout Board on Raspberry Pi 2

             30 Mar 2015 »

             Updated FLIR Lepton PocketCam GUI

             10 Mar 2015 »

             How to Create A GroupGet Campaign

             08 Mar 2015 »

             Springing Ahead

             23 Feb 2015 »

             Flir Lepton Pocketcam GUI

404: Page not found

Sorry, we've misplaced that URL or it's pointing to something that doesn't exist. Head back home to try finding it again.

          © GroupGets LLC • Santa Barbara, California


text:
import re

from . import utils, errors, cmd
from .helpnode import HelpNode
from .enums import PrivilegeLevel

class ServerModuleGroup(HelpNode):

   # TODO: Implement more efficient data structures. Too much linear searching is going on.

   # PRECONDITION: initial_modules is a list of unique modules.
   # PRECONDITION: initial_modules is already sorted by desired appearance
   #               when getting summary help content.
   def __init__(self, initial_modules=[], core_help_pages=[]):
      # Initialize our module collections.
      # Two collections for efficiency (dict for calling commands, list for iterating).
      self._modules_cmd_dict = {}
      self._modules_list = initial_modules
      for module in self._modules_list:
         for cmd_name in module.all_cmd_aliases:
            self._modules_cmd_dict[cmd_name] = module
      self._core_pages_dict = {}
      self._core_pages_list = list(core_help_pages)
      for help_page in self._core_pages_list:
         for alias in help_page.get_all_aliases():
            self._core_pages_dict[alias] = help_page
      return

   async def msg_preprocessor(self, content, msg, default_cmd_prefix):
      for module in self._modules_list:
         content = await module.msg_preprocessor(content, msg, default_cmd_prefix)
      return content

   async def on_message(self, msg, privilege_level):
      for module in self._modules_list:
         await module.on_message(msg, privilege_level)
      return

   async def process_cmd(self, substr, msg, privilege_level, silentfail=False):
      (left, right) = utils.separate_left_word(substr)
      try:
         await self._modules_cmd_dict[left].process_cmd(right, msg, privilege_level, left)
      except KeyError:
         if silentfail:
            raise errors.SilentUnknownCommandError
         else:
            raise errors.UnknownCommandError
      return

   async def on_member_join(self, member):
      for module in self._modules_list:
         await module.on_member_join(member)
      return

   async def on_member_remove(self, member):
      for module in self._modules_list:
         await module.on_member_remove(member)
      return

   async def on_member_ban(self, member):
      for module in self._modules_list:
         await module.on_member_ban(member)
      return

   async def on_member_unban(self, user):
      for module in self._modules_list:
         await module.on_member_unban(user)
      return

   async def on_member_update(self, before, after):
      for module in self._modules_list:
         await module.on_member_update(before, after)
      return

   # Like the original get_extra_user_info method, except the tuple's
   # two fields are lists. Field 1 is a list of field 1 content from the
   # original method, and similarly with field 2.
   async def get_extra_user_info(self, member):
      ret0 = []
      ret1 = []
      for module in self._modules_list:
         info_tuple = await module.get_extra_user_info(member)
         if not info_tuple is None:
            # TODO: Are these asserts redundant?
            assert isinstance(info_tuple, tuple)
            assert len(info_tuple) == 2
            if not info_tuple[0] is None:
               assert isinstance(info_tuple[0], str)
               ret0.append(info_tuple[0])
            if not info_tuple[1] is None:
               assert isinstance(info_tuple[1], str)
               ret1.append(info_tuple[1])
      ret0.sort(key=lambda x: x.lower())
      ret1.sort(key=lambda x: x.lower())
      return (ret0, ret1)

   # Module is referenced by its module name.
   def module_is_installed(self, module_name):
      for module in self._modules_list:
         if module.module_name == module_name:
            return True
      return False

   # PRECONDITION: Module isn't already installed.
   #               This means duplicates are allowed in the same ServerModuleGroup,
   #               but its use often requires
   async def add_server_module(self, new_module):
      self._modules_list.append(new_module)
      for cmd_name in new_module.all_cmd_aliases:
         if cmd_name in self._modules_cmd_dict:
            print("WARNING: Module with alias '{}' already exists.".format(cmd_name))
         self._modules_cmd_dict[cmd_name] = new_module

   # Installs the module referenced by its base command name.
   # PRECONDITION: Module is currently installed.
   async def remove_server_module(self, module_name):
      module_to_remove = None
      for module in self._modules_list:
         if module.module_name == module_name:
            module_to_remove = module
            break
      await module_to_remove.kill()
      for cmd_name in module_to_remove.all_cmd_aliases:
         del self._modules_cmd_dict[cmd_name]
      self._modules_list.remove(module_to_remove)

   # Returns list of all installed modules in this instance.
   # RETURNS: A list of tuples, each tuple in the format:
   #          (module_name, module_short_description, is_active)
   def gen_module_info(self):
      for module in self._modules_list:
         yield (module.module_name, module.module_short_description, module.is_active())

   # PRECONDITION: module_is_installed(module_name)
   def module_is_active(self, module_name):
      for module in self._modules_list:
         if module.module_name == module_name:
            return module.is_active()
      raise RuntimeError("No such server module exists.")

   # PRECONDITION: module_is_installed(module_name)
   async def activate_module(self, module_name):
      for module in self._modules_list:
         if module.module_name == module_name:
            await module.activate()
            return
      raise RuntimeError("No such server module exists.")

   # PRECONDITION: module_is_installed(module_name)
   async def kill_module(self, module_name):
      for module in self._modules_list:
         if module.module_name == module_name:
            await module.kill()
            return
      raise RuntimeError("No such server module exists.")

   ################################
   ### HelpNode Implementations ###
   ################################

   async def get_help_detail(self, locator_string, entry_string, privilege_level):
      assert isinstance(locator_string, str) and isinstance(entry_string, str)
      assert isinstance(privilege_level, PrivilegeLevel)
      buf = None
      if locator_string is "":
         # Serve module help content.
         buf = ""
         if len(self._core_pages_list) > 0:
            buf += await cmd.summarise_server_modules(self._core_pages_list, privilege_level)
            buf += "\n\n"
         buf += await cmd.summarise_server_modules(self._modules_list, privilege_level)
      else:
         # Get the next node's help content.
         (left, right) = utils.separate_left_word(locator_string)
         if left in self._core_pages_dict:
            buf = await self._core_pages_dict[left].get_help_detail(right, left, privilege_level)
            if not buf is None:
               buf = buf.format(p="{p}", grp="")
         if left in self._modules_cmd_dict:
            buf = await self._modules_cmd_dict[left].get_help_detail(right, left, privilege_level)
            if not buf is None:
               buf = buf.format(p="{p}", grp="{grp}" + left + " ")
      return buf

   async def get_help_summary(self, privilege_level):
      assert isinstance(privilege_level, PrivilegeLevel)
      return "ServerModuleGroup objects have no help summary yet."

   async def node_min_priv(self):
      return PrivilegeLevel.get_lowest_privilege()

   async def node_category(self):
      return ""


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

import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.log.Logger;
import io.airlift.units.DataSize;
import io.trino.Session;
import io.trino.connector.CatalogHandle;
import io.trino.metadata.InternalNode;
import io.trino.spi.TrinoException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import javax.inject.Inject;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Sets.newConcurrentHashSet;
import static com.google.common.util.concurrent.Futures.immediateFailedFuture;
import static com.google.common.util.concurrent.Futures.immediateFuture;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.trino.spi.StandardErrorCode.NO_NODES_AVAILABLE;
import static java.util.Comparator.comparing;
import static java.util.Objects.requireNonNull;

/**
 * A simplistic node allocation service which only limits number of allocations per node within each
 * {@link FixedCountNodeAllocator} instance. Each allocator will allow each node to be acquired up to {@link FixedCountNodeAllocatorService#MAXIMUM_ALLOCATIONS_PER_NODE}
 * times at the same time.
 */
@ThreadSafe
public class FixedCountNodeAllocatorService
        implements NodeAllocatorService
{
    private static final Logger log = Logger.get(FixedCountNodeAllocatorService.class);

    // Single FixedCountNodeAllocator will allow for at most MAXIMUM_ALLOCATIONS_PER_NODE.
    // If we reach this state subsequent calls to acquire will return blocked lease.
    private static final int MAXIMUM_ALLOCATIONS_PER_NODE = 1; // TODO make configurable?

    private final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, daemonThreadsNamed("fixed-count-node-allocator"));
    private final NodeScheduler nodeScheduler;

    private final Set<FixedCountNodeAllocator> allocators = newConcurrentHashSet();
    private final AtomicBoolean started = new AtomicBoolean();

    @Inject
    public FixedCountNodeAllocatorService(NodeScheduler nodeScheduler)
    {
        this.nodeScheduler = requireNonNull(nodeScheduler, "nodeScheduler is null");
    }

    @PostConstruct
    public void start()
    {
        if (!started.compareAndSet(false, true)) {
            // already started
            return;
        }
        executor.scheduleWithFixedDelay(() -> {
            try {
                updateNodes();
            }
            catch (Throwable e) {
                // ignore to avoid getting unscheduled
                log.warn(e, "Error updating nodes");
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void stop()
    {
        executor.shutdownNow();
    }

    @VisibleForTesting
    void updateNodes()
    {
        allocators.forEach(FixedCountNodeAllocator::updateNodes);
    }

    @Override
    public NodeAllocator getNodeAllocator(Session session)
    {
        requireNonNull(session, "session is null");
        return getNodeAllocator(session, MAXIMUM_ALLOCATIONS_PER_NODE);
    }

    @VisibleForTesting
    NodeAllocator getNodeAllocator(Session session, int maximumAllocationsPerNode)
    {
        FixedCountNodeAllocator allocator = new FixedCountNodeAllocator(session, maximumAllocationsPerNode);
        allocators.add(allocator);
        return allocator;
    }

    private class FixedCountNodeAllocator
            implements NodeAllocator
    {
        private final Session session;
        private final int maximumAllocationsPerNode;

        @GuardedBy("this")
        private final Map<Optional<CatalogHandle>, NodeSelector> nodeSelectorCache = new HashMap<>();

        @GuardedBy("this")
        private final Map<InternalNode, Integer> allocationCountMap = new HashMap<>();

        @GuardedBy("this")
        private final List<PendingAcquire> pendingAcquires = new LinkedList<>();

        public FixedCountNodeAllocator(
                Session session,
                int maximumAllocationsPerNode)
        {
            this.session = requireNonNull(session, "session is null");
            this.maximumAllocationsPerNode = maximumAllocationsPerNode;
        }

        @Override
        public synchronized NodeLease acquire(NodeRequirements nodeRequirements, DataSize memoryRequirement)
        {
            try {
                Optional<InternalNode> node = tryAcquireNode(nodeRequirements);
                if (node.isPresent()) {
                    return new FixedCountNodeLease(immediateFuture(node.get()));
                }
            }
            catch (RuntimeException e) {
                return new FixedCountNodeLease(immediateFailedFuture(e));
            }

            SettableFuture<InternalNode> future = SettableFuture.create();
            PendingAcquire pendingAcquire = new PendingAcquire(nodeRequirements, future);
            pendingAcquires.add(pendingAcquire);

            return new FixedCountNodeLease(future);
        }

        public void updateNodes()
        {
            processPendingAcquires();
        }

        private synchronized Optional<InternalNode> tryAcquireNode(NodeRequirements requirements)
        {
            NodeSelector nodeSelector = nodeSelectorCache.computeIfAbsent(requirements.getCatalogHandle(), catalogHandle -> nodeScheduler.createNodeSelector(session, catalogHandle));

            List<InternalNode> nodes = nodeSelector.allNodes();
            if (nodes.isEmpty()) {
                throw new TrinoException(NO_NODES_AVAILABLE, "No nodes available to run query");
            }

            List<InternalNode> nodesMatchingRequirements = nodes.stream()
                    .filter(node -> requirements.getAddresses().isEmpty() || requirements.getAddresses().contains(node.getHostAndPort()))
                    .collect(toImmutableList());

            if (nodesMatchingRequirements.isEmpty()) {
                throw new TrinoException(NO_NODES_AVAILABLE, "No nodes available to run query");
            }

            Optional<InternalNode> selectedNode = nodesMatchingRequirements.stream()
                    .filter(node -> allocationCountMap.getOrDefault(node, 0) < maximumAllocationsPerNode)
                    .min(comparing(node -> allocationCountMap.getOrDefault(node, 0)));

            if (selectedNode.isEmpty()) {
                return Optional.empty();
            }

            allocationCountMap.compute(selectedNode.get(), (key, value) -> value == null ? 1 : value + 1);
            return selectedNode;
        }

        private void releaseNode(InternalNode node)
        {
            synchronized (this) {
                int allocationCount = allocationCountMap.compute(node, (key, value) -> value == null ? 0 : value - 1);
                checkState(allocationCount >= 0, "allocation count for node %s is expected to be greater than or equal to zero: %s", node, allocationCount);
            }
            processPendingAcquires();
        }

        private void processPendingAcquires()
        {
            verify(!Thread.holdsLock(this));

            IdentityHashMap<PendingAcquire, InternalNode> assignedNodes = new IdentityHashMap<>();
            IdentityHashMap<PendingAcquire, RuntimeException> failures = new IdentityHashMap<>();
            synchronized (this) {
                Iterator<PendingAcquire> iterator = pendingAcquires.iterator();
                while (iterator.hasNext()) {
                    PendingAcquire pendingAcquire = iterator.next();
                    if (pendingAcquire.getFuture().isCancelled()) {
                        iterator.remove();
                        continue;
                    }
                    try {
                        Optional<InternalNode> node = tryAcquireNode(pendingAcquire.getNodeRequirements());
                        if (node.isPresent()) {
                            iterator.remove();
                            assignedNodes.put(pendingAcquire, node.get());
                        }
                    }
                    catch (RuntimeException e) {
                        iterator.remove();
                        failures.put(pendingAcquire, e);
                    }
                }
            }

            // set futures outside of critical section
            assignedNodes.forEach((pendingAcquire, node) -> {
                SettableFuture<InternalNode> future = pendingAcquire.getFuture();
                future.set(node);
                if (future.isCancelled()) {
                    releaseNode(node);
                }
            });

            failures.forEach((pendingAcquire, failure) -> {
                SettableFuture<InternalNode> future = pendingAcquire.getFuture();
                future.setException(failure);
            });
        }

        @Override
        public synchronized void close()
        {
            allocators.remove(this);
        }

        private class FixedCountNodeLease
                implements NodeAllocator.NodeLease
        {
            private final ListenableFuture<InternalNode> node;
            private final AtomicBoolean released = new AtomicBoolean();

            private FixedCountNodeLease(ListenableFuture<InternalNode> node)
            {
                this.node = requireNonNull(node, "node is null");
            }

            @Override
            public ListenableFuture<InternalNode> getNode()
            {
                return node;
            }

            @Override
            public void release()
            {
                if (released.compareAndSet(false, true)) {
                    node.cancel(true);
                    if (node.isDone() && !node.isCancelled()) {
                        releaseNode(getFutureValue(node));
                    }
                }
                else {
                    throw new IllegalStateException("Node " + node + " already released");
                }
            }
        }
    }

    private static class PendingAcquire
    {
        private final NodeRequirements nodeRequirements;
        private final SettableFuture<InternalNode> future;

        private PendingAcquire(NodeRequirements nodeRequirements, SettableFuture<InternalNode> future)
        {
            this.nodeRequirements = requireNonNull(nodeRequirements, "nodeRequirements is null");
            this.future = requireNonNull(future, "future is null");
        }

        public NodeRequirements getNodeRequirements()
        {
            return nodeRequirements;
        }

        public SettableFuture<InternalNode> getFuture()
        {
            return future;
        }
    }
}


text:
namespace gpu {

using testing::Return;
using testing::Mock;
using testing::Truly;
using testing::Sequence;
using testing::_;

// Test fixture for CommandParser test - Creates a mock AsyncAPIInterface, and
// a fixed size memory buffer. Also provides a simple API to create a
// CommandParser.
class CommandParserTest : public testing::Test {
 protected:
  virtual void SetUp() {
    api_mock_.reset(new AsyncAPIMock);
    buffer_entry_count_ = 20;
    buffer_.reset(new CommandBufferEntry[buffer_entry_count_]);
  }
  virtual void TearDown() {}

  // Adds a DoCommand expectation in the mock.
  void AddDoCommandExpect(parse_error::ParseError _return,
                          unsigned int command,
                          unsigned int arg_count,
                          CommandBufferEntry *args) {
    EXPECT_CALL(*api_mock(), DoCommand(command, arg_count,
        Truly(AsyncAPIMock::IsArgs(arg_count, args))))
        .InSequence(sequence_)
        .WillOnce(Return(_return));
  }

  // Creates a parser, with a buffer of the specified size (in entries).
  CommandParser *MakeParser(unsigned int entry_count) {
    size_t shm_size = buffer_entry_count_ *
                      sizeof(CommandBufferEntry);  // NOLINT
    size_t command_buffer_size = entry_count *
                                 sizeof(CommandBufferEntry);  // NOLINT
    DCHECK_LE(command_buffer_size, shm_size);
    return new CommandParser(buffer(),
                             shm_size,
                             0,
                             command_buffer_size,
                             0,
                             api_mock());
  }

  unsigned int buffer_entry_count() { return 20; }
  AsyncAPIMock *api_mock() { return api_mock_.get(); }
  CommandBufferEntry *buffer() { return buffer_.get(); }
 private:
  unsigned int buffer_entry_count_;
  scoped_ptr<AsyncAPIMock> api_mock_;
  scoped_array<CommandBufferEntry> buffer_;
  Sequence sequence_;
};

// Tests initialization conditions.
TEST_F(CommandParserTest, TestInit) {
  scoped_ptr<CommandParser> parser(MakeParser(10));
  EXPECT_EQ(0u, parser->get());
  EXPECT_EQ(0u, parser->put());
  EXPECT_TRUE(parser->IsEmpty());
}

// Tests simple commands.
TEST_F(CommandParserTest, TestSimple) {
  scoped_ptr<CommandParser> parser(MakeParser(10));
  CommandBufferOffset put = parser->put();
  CommandHeader header;

  // add a single command, no args
  header.size = 1;
  header.command = 123;
  buffer()[put++].value_header = header;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());

  AddDoCommandExpect(parse_error::kParseNoError, 123, 0, NULL);
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());

  // add a single command, 2 args
  header.size = 3;
  header.command = 456;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 2134;
  buffer()[put++].value_float = 1.f;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());

  CommandBufferEntry param_array[2];
  param_array[0].value_int32 = 2134;
  param_array[1].value_float = 1.f;
  AddDoCommandExpect(parse_error::kParseNoError, 456, 2, param_array);
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());
}

// Tests having multiple commands in the buffer.
TEST_F(CommandParserTest, TestMultipleCommands) {
  scoped_ptr<CommandParser> parser(MakeParser(10));
  CommandBufferOffset put = parser->put();
  CommandHeader header;

  // add 2 commands, test with single ProcessCommand()
  header.size = 2;
  header.command = 789;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 5151;

  CommandBufferOffset put_cmd2 = put;
  header.size = 2;
  header.command = 876;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 3434;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());

  CommandBufferEntry param_array[2];
  param_array[0].value_int32 = 5151;
  AddDoCommandExpect(parse_error::kParseNoError, 789, 1, param_array);
  param_array[1].value_int32 = 3434;
  AddDoCommandExpect(parse_error::kParseNoError, 876, 1,
                     param_array+1);

  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand());
  EXPECT_EQ(put_cmd2, parser->get());
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessCommand());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());

  // add 2 commands again, test with ProcessAllCommands()
  header.size = 2;
  header.command = 123;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 5656;

  header.size = 2;
  header.command = 321;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 7878;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());

  param_array[0].value_int32 = 5656;
  AddDoCommandExpect(parse_error::kParseNoError, 123, 1, param_array);
  param_array[1].value_int32 = 7878;
  AddDoCommandExpect(parse_error::kParseNoError, 321, 1,
                     param_array+1);

  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());
}

// Tests that the parser will wrap correctly at the end of the buffer.
TEST_F(CommandParserTest, TestWrap) {
  scoped_ptr<CommandParser> parser(MakeParser(5));
  CommandBufferOffset put = parser->put();
  CommandHeader header;

  // add 3 commands with no args (1 word each)
  for (unsigned int i = 0; i < 3; ++i) {
    header.size = 1;
    header.command = i;
    buffer()[put++].value_header = header;
    AddDoCommandExpect(parse_error::kParseNoError, i, 0, NULL);
  }
  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());

  // add 1 command with 1 arg (2 words). That should put us at the end of the
  // buffer.
  header.size = 2;
  header.command = 3;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 5;
  CommandBufferEntry param;
  param.value_int32 = 5;
  AddDoCommandExpect(parse_error::kParseNoError, 3, 1, &param);

  DCHECK_EQ(5u, put);
  put = 0;
  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());

  // add 1 command with 1 arg (2 words).
  header.size = 2;
  header.command = 4;
  buffer()[put++].value_header = header;
  buffer()[put++].value_int32 = 6;
  param.value_int32 = 6;
  AddDoCommandExpect(parse_error::kParseNoError, 4, 1, &param);
  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());
}

// Tests error conditions.
TEST_F(CommandParserTest, TestError) {
  scoped_ptr<CommandParser> parser(MakeParser(5));
  CommandBufferOffset put = parser->put();
  CommandHeader header;

  // Generate a command with size 0.
  header.size = 0;
  header.command = 3;
  buffer()[put++].value_header = header;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  EXPECT_EQ(parse_error::kParseInvalidSize,
            parser->ProcessAllCommands());
  // check that no DoCommand call was made.
  Mock::VerifyAndClearExpectations(api_mock());

  parser.reset(MakeParser(5));
  put = parser->put();

  // Generate a command with size 6, extends beyond the end of the buffer.
  header.size = 6;
  header.command = 3;
  buffer()[put++].value_header = header;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  EXPECT_EQ(parse_error::kParseOutOfBounds,
            parser->ProcessAllCommands());
  // check that no DoCommand call was made.
  Mock::VerifyAndClearExpectations(api_mock());

  parser.reset(MakeParser(5));
  put = parser->put();

  // Generates 2 commands.
  header.size = 1;
  header.command = 3;
  buffer()[put++].value_header = header;
  CommandBufferOffset put_post_fail = put;
  header.size = 1;
  header.command = 4;
  buffer()[put++].value_header = header;

  parser->set_put(put);
  EXPECT_EQ(put, parser->put());
  // have the first command fail to parse.
  AddDoCommandExpect(parse_error::kParseUnknownCommand, 3, 0, NULL);
  EXPECT_EQ(parse_error::kParseUnknownCommand,
            parser->ProcessAllCommands());
  // check that only one command was executed, and that get reflects that
  // correctly.
  EXPECT_EQ(put_post_fail, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());
  // make the second one succeed, and check that the parser recovered fine.
  AddDoCommandExpect(parse_error::kParseNoError, 4, 0, NULL);
  EXPECT_EQ(parse_error::kParseNoError, parser->ProcessAllCommands());
  EXPECT_EQ(put, parser->get());
  Mock::VerifyAndClearExpectations(api_mock());
}

}  // namespace gpu


text:
using System;
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace YesSql.Utils
{
    public class RentedStringBuilder : IStringBuilder
    {
        private char[] _arrayToReturnToPool;
        private char[] _chars;
        private int _pos;

        public RentedStringBuilder(char[] initialBuffer)
        {
            _arrayToReturnToPool = null;
            _chars = initialBuffer;
            _pos = 0;
        }

        public RentedStringBuilder(int initialCapacity)
        {
            _arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
            _chars = _arrayToReturnToPool;
            _pos = 0;
        }

        public int Length
        {
            get => _pos;
            set
            {
                Debug.Assert(value >= 0);
                Debug.Assert(value <= _chars.Length);
                _pos = value;
            }
        }

        public int Capacity => _chars.Length;

        public void EnsureCapacity(int capacity)
        {
            // This is not expected to be called this with negative capacity
            Debug.Assert(capacity >= 0);

            // If the caller has a bug and calls this with negative capacity, make sure to call Grow to throw an exception.
            if ((uint)capacity > (uint)_chars.Length)
                Grow(capacity - _pos);
        }

        public ref char this[int index]
        {
            get
            {
                Debug.Assert(index < _pos);
                return ref _chars[index];
            }
        }

        public override string ToString()
        {
            string s = _chars.AsSpan(0, _pos).ToString();
            return s;
        }

        public ReadOnlySpan<char> AsSpan() => _chars.AsSpan(0, _pos);
        public ReadOnlySpan<char> AsSpan(int start) => _chars.AsSpan(start, _pos - start);
        public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.AsSpan(start, length);

        public bool TryCopyTo(Span<char> destination, out int charsWritten)
        {
            if (_chars.AsSpan(0, _pos).TryCopyTo(destination))
            {
                charsWritten = _pos;
                Clear();
                return true;
            }
            else
            {
                charsWritten = 0;
                Clear();
                return false;
            }
        }

        public void Insert(int index, char value, int count)
        {
            if (_pos > _chars.Length - count)
            {
                Grow(count);
            }

            int remaining = _pos - index;
            _chars.AsSpan(index, remaining).CopyTo(_chars.AsSpan(index + count));
            _chars.AsSpan(index, count).Fill(value);
            _pos += count;
        }

        public void Insert(int index, string s)
        {
            if (s == null)
            {
                return;
            }

            int count = s.Length;

            if (_pos > (_chars.Length - count))
            {
                Grow(count);
            }

            int remaining = _pos - index;
            _chars.AsSpan(index, remaining).CopyTo(_chars.AsSpan(index + count));
            s.AsSpan().CopyTo(_chars.AsSpan(index));
            _pos += count;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Append(char c)
        {
            int pos = _pos;
            if ((uint)pos < (uint)_chars.Length)
            {
                _chars[pos] = c;
                _pos = pos + 1;
            }
            else
            {
                GrowAndAppend(c);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Append(string s)
        {
            if (s == null)
            {
                return;
            }

            int pos = _pos;
            if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
            {
                _chars[pos] = s[0];
                _pos = pos + 1;
            }
            else
            {
                AppendSlow(s);
            }
        }

        private void AppendSlow(string s)
        {
            int pos = _pos;
            if (pos > _chars.Length - s.Length)
            {
                Grow(s.Length);
            }

            s.AsSpan().CopyTo(_chars.AsSpan(pos));
            _pos += s.Length;
        }

        public void Append(ReadOnlySpan<char> value)
        {
            int pos = _pos;
            if (pos > _chars.Length - value.Length)
            {
                Grow(value.Length);
            }

            value.CopyTo(_chars.AsSpan(_pos));
            _pos += value.Length;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private void GrowAndAppend(char c)
        {
            Grow(1);
            Append(c);
        }

        /// <summary>
        /// Resize the internal buffer either by doubling current buffer size or
        /// by adding <paramref name="additionalCapacityBeyondPos"/> to
        /// <see cref="_pos"/> whichever is greater.
        /// </summary>
        /// <param name="additionalCapacityBeyondPos">
        /// Number of chars requested beyond current position.
        /// </param>
        [MethodImpl(MethodImplOptions.NoInlining)]
        private void Grow(int additionalCapacityBeyondPos)
        {
            Debug.Assert(additionalCapacityBeyondPos > 0);
            Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");

            // Make sure to let Rent throw an exception if the caller has a bug and the desired capacity is negative
            char[] poolArray = ArrayPool<char>.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)_chars.Length * 2));

            _chars.AsSpan(0, _pos).CopyTo(poolArray);

            char[] toReturn = _arrayToReturnToPool;
            _chars = _arrayToReturnToPool = poolArray;
            if (toReturn != null)
            {
                ArrayPool<char>.Shared.Return(toReturn);
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Clear()
        {
            _pos = 0;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Dispose()
        {
            char[] toReturn = _arrayToReturnToPool;
            if (toReturn != null)
            {
                ArrayPool<char>.Shared.Return(toReturn);
            }

            _pos = 0;
            _chars = null;
        }
    }
}


text:
use crate::cases::{self, Case, Cases, EpochTransition, LoadCase, Operation};
use crate::type_name;
use crate::type_name::TypeName;
use derivative::Derivative;
use std::fs::{self, DirEntry};
use std::marker::PhantomData;
use std::path::PathBuf;
use types::{BeaconState, EthSpec, ForkName};

pub trait Handler {
    type Case: Case + LoadCase;

    fn config_name() -> &'static str {
        "general"
    }

    fn runner_name() -> &'static str;

    fn handler_name(&self) -> String;

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        Self::Case::is_enabled_for_fork(fork_name)
    }

    fn run(&self) {
        for fork_name in ForkName::list_all() {
            if self.is_enabled_for_fork(fork_name) {
                self.run_for_fork(fork_name)
            }
        }
    }

    fn use_rayon() -> bool {
        true
    }

    fn run_for_fork(&self, fork_name: ForkName) {
        let fork_name_str = fork_name.to_string();

        let handler_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("consensus-spec-tests")
            .join("tests")
            .join(Self::config_name())
            .join(&fork_name_str)
            .join(Self::runner_name())
            .join(self.handler_name());

        // Iterate through test suites
        let as_directory = |entry: Result<DirEntry, std::io::Error>| -> Option<DirEntry> {
            entry
                .ok()
                .filter(|e| e.file_type().map(|ty| ty.is_dir()).unwrap())
        };

        let test_cases = fs::read_dir(&handler_path)
            .unwrap_or_else(|e| panic!("handler dir {} exists: {:?}", handler_path.display(), e))
            .filter_map(as_directory)
            .flat_map(|suite| fs::read_dir(suite.path()).expect("suite dir exists"))
            .filter_map(as_directory)
            .map(|test_case_dir| {
                let path = test_case_dir.path();

                let case = Self::Case::load_from_dir(&path, fork_name).expect("test should load");
                (path, case)
            })
            .collect();

        let results = Cases { test_cases }.test_results(fork_name, Self::use_rayon());

        let name = format!(
            "{}/{}/{}",
            fork_name_str,
            Self::runner_name(),
            self.handler_name()
        );
        crate::results::assert_tests_pass(&name, &handler_path, &results);
    }
}

macro_rules! bls_eth_handler {
    ($runner_name: ident, $case_name:ident, $handler_name:expr) => {
        #[derive(Derivative)]
        #[derivative(Default(bound = ""))]
        pub struct $runner_name;

        impl Handler for $runner_name {
            type Case = cases::$case_name;

            fn runner_name() -> &'static str {
                "bls"
            }

            fn handler_name(&self) -> String {
                $handler_name.into()
            }
        }
    };
}

macro_rules! bls_handler {
    ($runner_name: ident, $case_name:ident, $handler_name:expr) => {
        #[derive(Derivative)]
        #[derivative(Default(bound = ""))]
        pub struct $runner_name;

        impl Handler for $runner_name {
            type Case = cases::$case_name;

            fn runner_name() -> &'static str {
                "bls"
            }

            fn config_name() -> &'static str {
                "bls12-381-tests"
            }

            fn handler_name(&self) -> String {
                $handler_name.into()
            }

            fn run(&self) {
                let fork_name = ForkName::Base;
                let fork_name_str = fork_name.to_string();
                let handler_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                    .join("consensus-spec-tests")
                    .join(Self::config_name())
                    .join(self.handler_name());

                let as_file = |entry: Result<DirEntry, std::io::Error>| -> Option<DirEntry> {
                    entry
                        .ok()
                        .filter(|e| e.file_type().map(|ty| ty.is_file()).unwrap_or(false))
                };
                let test_cases: Vec<(PathBuf, Self::Case)> = fs::read_dir(&handler_path)
                    .expect("handler dir exists")
                    .filter_map(as_file)
                    .map(|test_case_path| {
                        let path = test_case_path.path();
                        let case =
                            Self::Case::load_from_dir(&path, fork_name).expect("test should load");

                        (path, case)
                    })
                    .collect();

                let results = Cases { test_cases }.test_results(fork_name, Self::use_rayon());

                let name = format!(
                    "{}/{}/{}",
                    fork_name_str,
                    Self::runner_name(),
                    self.handler_name()
                );
                crate::results::assert_tests_pass(&name, &handler_path, &results);
            }
        }
    };
}

bls_handler!(BlsAggregateSigsHandler, BlsAggregateSigs, "aggregate");
bls_handler!(BlsSignMsgHandler, BlsSign, "sign");
bls_handler!(BlsBatchVerifyHandler, BlsBatchVerify, "batch_verify");
bls_handler!(BlsVerifyMsgHandler, BlsVerify, "verify");
bls_handler!(
    BlsAggregateVerifyHandler,
    BlsAggregateVerify,
    "aggregate_verify"
);
bls_handler!(
    BlsFastAggregateVerifyHandler,
    BlsFastAggregateVerify,
    "fast_aggregate_verify"
);
bls_eth_handler!(
    BlsEthAggregatePubkeysHandler,
    BlsEthAggregatePubkeys,
    "eth_aggregate_pubkeys"
);
bls_eth_handler!(
    BlsEthFastAggregateVerifyHandler,
    BlsEthFastAggregateVerify,
    "eth_fast_aggregate_verify"
);

/// Handler for SSZ types.
pub struct SszStaticHandler<T, E> {
    supported_forks: Vec<ForkName>,
    _phantom: PhantomData<(T, E)>,
}

impl<T, E> Default for SszStaticHandler<T, E> {
    fn default() -> Self {
        Self::for_forks(ForkName::list_all())
    }
}

impl<T, E> SszStaticHandler<T, E> {
    pub fn for_forks(supported_forks: Vec<ForkName>) -> Self {
        SszStaticHandler {
            supported_forks,
            _phantom: PhantomData,
        }
    }

    pub fn base_only() -> Self {
        Self::for_forks(vec![ForkName::Base])
    }

    pub fn altair_only() -> Self {
        Self::for_forks(vec![ForkName::Altair])
    }

    pub fn altair_and_later() -> Self {
        Self::for_forks(ForkName::list_all()[1..].to_vec())
    }

    pub fn merge_only() -> Self {
        Self::for_forks(vec![ForkName::Merge])
    }

    pub fn merge_and_later() -> Self {
        Self::for_forks(ForkName::list_all()[2..].to_vec())
    }
}

/// Handler for SSZ types that implement `CachedTreeHash`.
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct SszStaticTHCHandler<T, E>(PhantomData<(T, E)>);

/// Handler for SSZ types that don't implement `ssz::Decode`.
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct SszStaticWithSpecHandler<T, E>(PhantomData<(T, E)>);

impl<T, E> Handler for SszStaticHandler<T, E>
where
    T: cases::SszStaticType + ssz::Decode + TypeName,
    E: TypeName,
{
    type Case = cases::SszStatic<T>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "ssz_static"
    }

    fn handler_name(&self) -> String {
        T::name().into()
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        self.supported_forks.contains(&fork_name)
    }
}

impl<E> Handler for SszStaticTHCHandler<BeaconState<E>, E>
where
    E: EthSpec + TypeName,
{
    type Case = cases::SszStaticTHC<BeaconState<E>>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "ssz_static"
    }

    fn handler_name(&self) -> String {
        BeaconState::<E>::name().into()
    }
}

impl<T, E> Handler for SszStaticWithSpecHandler<T, E>
where
    T: TypeName,
    E: EthSpec + TypeName,
    cases::SszStaticWithSpec<T>: Case + LoadCase,
{
    type Case = cases::SszStaticWithSpec<T>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "ssz_static"
    }

    fn handler_name(&self) -> String {
        T::name().into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct ShufflingHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for ShufflingHandler<E> {
    type Case = cases::Shuffling<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "shuffling"
    }

    fn handler_name(&self) -> String {
        "core".into()
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        fork_name == ForkName::Base
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct SanityBlocksHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for SanityBlocksHandler<E> {
    type Case = cases::SanityBlocks<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "sanity"
    }

    fn handler_name(&self) -> String {
        "blocks".into()
    }

    fn is_enabled_for_fork(&self, _fork_name: ForkName) -> bool {
        // NOTE: v1.1.0-beta.4 doesn't mark the historical blocks test as requiring real crypto, so
        // only run these tests with real crypto for now.
        cfg!(not(feature = "fake_crypto"))
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct SanitySlotsHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for SanitySlotsHandler<E> {
    type Case = cases::SanitySlots<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "sanity"
    }

    fn handler_name(&self) -> String {
        "slots".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct RandomHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for RandomHandler<E> {
    type Case = cases::SanityBlocks<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "random"
    }

    fn handler_name(&self) -> String {
        "random".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct EpochProcessingHandler<E, T>(PhantomData<(E, T)>);

impl<E: EthSpec + TypeName, T: EpochTransition<E>> Handler for EpochProcessingHandler<E, T> {
    type Case = cases::EpochProcessing<E, T>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "epoch_processing"
    }

    fn handler_name(&self) -> String {
        T::name().into()
    }
}

pub struct RewardsHandler<E: EthSpec> {
    handler_name: &'static str,
    _phantom: PhantomData<E>,
}

impl<E: EthSpec> RewardsHandler<E> {
    pub fn new(handler_name: &'static str) -> Self {
        Self {
            handler_name,
            _phantom: PhantomData,
        }
    }
}

impl<E: EthSpec + TypeName> Handler for RewardsHandler<E> {
    type Case = cases::RewardsTest<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "rewards"
    }

    fn handler_name(&self) -> String {
        self.handler_name.to_string()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct ForkHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for ForkHandler<E> {
    type Case = cases::ForkTest<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "fork"
    }

    fn handler_name(&self) -> String {
        "fork".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct TransitionHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for TransitionHandler<E> {
    type Case = cases::TransitionTest<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "transition"
    }

    fn handler_name(&self) -> String {
        "core".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct FinalityHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for FinalityHandler<E> {
    // Reuse the blocks case runner.
    type Case = cases::SanityBlocks<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "finality"
    }

    fn handler_name(&self) -> String {
        "finality".into()
    }
}

pub struct ForkChoiceHandler<E> {
    handler_name: String,
    _phantom: PhantomData<E>,
}

impl<E: EthSpec> ForkChoiceHandler<E> {
    pub fn new(handler_name: &str) -> Self {
        Self {
            handler_name: handler_name.into(),
            _phantom: PhantomData,
        }
    }
}

impl<E: EthSpec + TypeName> Handler for ForkChoiceHandler<E> {
    type Case = cases::ForkChoiceTest<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "fork_choice"
    }

    fn handler_name(&self) -> String {
        self.handler_name.clone()
    }

    fn use_rayon() -> bool {
        // The fork choice tests use `block_on` which can cause panics with rayon.
        false
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        // Merge block tests are only enabled for Bellatrix or later.
        if self.handler_name == "on_merge_block"
            && (fork_name == ForkName::Base || fork_name == ForkName::Altair)
        {
            return false;
        }

        // These tests check block validity (which may include signatures) and there is no need to
        // run them with fake crypto.
        cfg!(not(feature = "fake_crypto"))
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct OptimisticSyncHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for OptimisticSyncHandler<E> {
    type Case = cases::ForkChoiceTest<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "sync"
    }

    fn handler_name(&self) -> String {
        "optimistic".into()
    }

    fn use_rayon() -> bool {
        // The opt sync tests use `block_on` which can cause panics with rayon.
        false
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        fork_name != ForkName::Base
            && fork_name != ForkName::Altair
            && cfg!(not(feature = "fake_crypto"))
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct GenesisValidityHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for GenesisValidityHandler<E> {
    type Case = cases::GenesisValidity<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "genesis"
    }

    fn handler_name(&self) -> String {
        "validity".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct GenesisInitializationHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for GenesisInitializationHandler<E> {
    type Case = cases::GenesisInitialization<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "genesis"
    }

    fn handler_name(&self) -> String {
        "initialization".into()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct MerkleProofValidityHandler<E>(PhantomData<E>);

impl<E: EthSpec + TypeName> Handler for MerkleProofValidityHandler<E> {
    type Case = cases::MerkleProofValidity<E>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "light_client"
    }

    fn handler_name(&self) -> String {
        "single_merkle_proof".into()
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        fork_name != ForkName::Base
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct OperationsHandler<E, O>(PhantomData<(E, O)>);

impl<E: EthSpec + TypeName, O: Operation<E>> Handler for OperationsHandler<E, O> {
    type Case = cases::Operations<E, O>;

    fn config_name() -> &'static str {
        E::name()
    }

    fn runner_name() -> &'static str {
        "operations"
    }

    fn handler_name(&self) -> String {
        O::handler_name()
    }
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct SszGenericHandler<H>(PhantomData<H>);

impl<H: TypeName> Handler for SszGenericHandler<H> {
    type Case = cases::SszGeneric;

    fn config_name() -> &'static str {
        "general"
    }

    fn runner_name() -> &'static str {
        "ssz_generic"
    }

    fn is_enabled_for_fork(&self, fork_name: ForkName) -> bool {
        // SSZ generic tests are genesis only
        fork_name == ForkName::Base
    }

    fn handler_name(&self) -> String {
        H::name().into()
    }
}

// Supported SSZ generic handlers
pub struct BasicVector;
type_name!(BasicVector, "basic_vector");
pub struct Bitlist;
type_name!(Bitlist, "bitlist");
pub struct Bitvector;
type_name!(Bitvector, "bitvector");
pub struct Boolean;
type_name!(Boolean, "boolean");
pub struct Uints;
type_name!(Uints, "uints");
pub struct Containers;
type_name!(Containers, "containers");


text:
package msp

import "testing"

func TestNoopMSP(t *testing.T) {
	noopmsp := NewNoopMsp()

	id, err := noopmsp.GetDefaultSigningIdentity()
	if err != nil {
		t.Fatalf("GetSigningIdentity should have succeeded")
		return
	}

	serializedID, err := id.Serialize()
	if err != nil {
		t.Fatalf("Serialize should have succeeded")
		return
	}

	idBack, err := noopmsp.DeserializeIdentity(serializedID)
	if err != nil {
		t.Fatalf("DeserializeIdentity should have succeeded")
		return
	}

	msg := []byte("foo")
	sig, err := id.Sign(msg)
	if err != nil {
		t.Fatalf("Sign should have succeeded")
		return
	}

	err = id.Verify(msg, sig)
	if err != nil {
		t.Fatalf("The signature should be valid")
		return
	}

	err = idBack.Verify(msg, sig)
	if err != nil {
		t.Fatalf("The signature should be valid")
		return
	}
}


text:
namespace glm
{
	namespace test{
		bool main_img_wrap();
	}//namespace test

	namespace img{
	//! GLM_IMG_wrap: Wrapping mode using my texture samping.
	namespace wrap
	{
		//! Simulate GL_CLAMP OpenGL wrap mode
		//! From GLM_IMG_wrap extension.
		template <typename genType>
		genType clamp(genType const & Texcoord);

		//! Simulate GL_REPEAT OpenGL wrap mode
		//! From GLM_IMG_wrap extension.
		template <typename genType>
		genType repeat(genType const & Texcoord);

		//! Simulate GL_MIRROR_REPEAT OpenGL wrap mode
		//! From GLM_IMG_wrap extension.
		template <typename genType>
		genType mirrorRepeat(genType const & Texcoord);

	}//namespace wrap
	}//namespace img
}//namespace glm

#include "wrap.inl"

namespace glm{using namespace img::wrap;}

#endif//glm_img_wrap


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace xgc3.GameObjects
{
    public class Container : View
    {
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>java.rmi.activation (Java Platform SE 8 )</title>
<meta name="date" content="2014-12-17">
<meta name="keywords" content="java.rmi.activation package">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Package

Next Package

Frames

No Frames

All Classes

compact2

Package java.rmi.activation

Provides support for RMI Object Activation.

See: Description

Interface Summary

Interface
Description

ActivationInstantiator

An ActivationInstantiator is responsible for creating
 instances of "activatable" objects.

ActivationMonitor

An ActivationMonitor is specific to an
 ActivationGroup and is obtained when a group is
 reported active via a call to
 ActivationSystem.activeGroup (this is done
 internally).

ActivationSystem

The ActivationSystem provides a means for registering
 groups and "activatable" objects to be activated within those groups.

Activator

The Activator facilitates remote object activation.

Class Summary

Class
Description

Activatable

The Activatable class provides support for remote
 objects that require persistent access over time and that
 can be activated by the system.

ActivationDesc

An activation descriptor contains the information necessary to
 activate an object:
  the object's group identifier,
  the object's fully-qualified class name,
  the object's code location (the location of the class), a codebase URL
 path,
  the object's restart "mode", and,
  a "marshalled" object that can contain object specific
 initialization data.

ActivationGroup

An ActivationGroup is responsible for creating new
 instances of "activatable" objects in its group, informing its
 ActivationMonitor when either: its object's become
 active or inactive, or the group as a whole becomes inactive.

ActivationGroup_Stub

ActivationGroup_Stub is a stub class
 for the subclasses of java.rmi.activation.ActivationGroup
 that are exported as a java.rmi.server.UnicastRemoteObject.

ActivationGroupDesc

An activation group descriptor contains the information necessary to
 create/recreate an activation group in which to activate objects.

ActivationGroupDesc.CommandEnvironment

Startup options for ActivationGroup implementations.

ActivationGroupID

The identifier for a registered activation group serves several
 purposes:
 identifies the group uniquely within the activation system, and
 contains a reference to the group's activation system so that the
 group can contact its activation system when necessary.

ActivationID

Activation makes use of special identifiers to denote remote
 objects that can be activated over time.

Exception Summary

Exception
Description

ActivateFailedException

This exception is thrown by the RMI runtime when activation
 fails during a remote call to an activatable object.

ActivationException

General exception used by the activation interfaces.

UnknownGroupException

An UnknownGroupException is thrown by methods of classes and
 interfaces in the java.rmi.activation package when the
 ActivationGroupID parameter to the method is determined to be
 invalid, i.e., not known by the ActivationSystem.

UnknownObjectException

An UnknownObjectException is thrown by methods of classes and
 interfaces in the java.rmi.activation package when the
 ActivationID parameter to the method is determined to be
 invalid.

Package java.rmi.activation Description

Provides support for RMI Object Activation.  A remote
object's reference can be made ``persistent'' and later activated into a
``live'' object using the RMI activation mechanism.

Implementations are not required to support the activation
mechanism. If activation is not supported by this implementation,
several specific activation API methods are all required to throw
UnsupportedOperationException. If activation is supported by this
implementation, these methods must never throw UnsupportedOperationException. These methods are denoted by the
presence of an entry for UnsupportedOperationException in the
Throws section of each method's specification.

Since:

1.2

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Java™ Platform
Standard Ed. 8

Prev Package

Next Package

Frames

No Frames

All Classes

 Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
 Copyright © 1993, 2015, Oracle and/or its affiliates.  All rights reserved.


text:
package com.lovecws.mumu.system.dao.impl;

import com.lovecws.mumu.common.core.dao.impl.BaseDaoImpl;
import com.lovecws.mumu.system.dao.SysMenuDao;
import com.lovecws.mumu.system.entity.SysMenu;
import org.springframework.stereotype.Repository;

@Repository
public class SysMenuDaoImpl extends BaseDaoImpl<SysMenu> implements SysMenuDao {

}


text:
function [p,d] = checkset(X)
% CHECKSET(F)  Displays/calculates constraint residuals on constraint F
%
% [pres,dres] = CHECKSET(F)
%
% pres : Primal constraint residuals
% dres : Dual constraint residuals
%
% If no output argument is supplied, tabulated results are displayed
%
% Primal constraint residuals are calculated as:
%
%  Semidefinite constraint F(x)>0 : min(eig(F))
%  Element-wise constraint F(x)>0 : min(min(F))
%  Equality constraint F==0       : -max(max(abs(F)))
%  Second order cone t>||x||      : t-||x||
%  Integrality constraint on x    : max(abs(x-round(x)))
%  Rank constraint rank(X) < r     : r-rank(X)
%  Sum-of-square constraint       : Minus value of largest (absolute value) coefficient
%                                   in the polynomial p-v'*v
%
% Dual constraints are evaluated similarily.
%
%    See also   SET, SOLVESDP, SOLVESOS, SOSD, DUAL

% Author Johan Löfberg
% $Id: checkset.m,v 1.19 2008-02-21 15:32:09 joloef Exp $

switch nargout
    case 0
        checkset(lmi(X));
    case 1
        p = checkset(lmi(X));
    case 2
        [p,d] = checkset(lmi(X));
end


text:
/**
 * Shared Schemas.
 */

var addressSchema = {
    country: {type: String},
    state: {type: String},
    city: {type: String},
    postCode:{type: String},
    street:{type: String}
};

var personalDataSchema = {
    firstName: {type: String},
    middleName: {type: String},
    lastName: {type: String},
    alias:{type: String},
    birthday:{type: Date},
    bio:{type: String}
};

var contactSchema = {
    code: {type:String},
    description: {type:String},
    value: {type:String}
};

/**
 * Exports.
 */

module.exports = {
    address: addressSchema,
    personalData: personalDataSchema,
    contact: contactSchema
};


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
using InteractorLib.ViewModels;

namespace XBrowser.Views
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ProblemView : Page
    {
        public ProblemView()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.DataContext = e.Parameter as ProblemViewModel;
        }
    }
}


text:
<?php

include_once($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/admin-config.inc.php');

$session->redirectIfNotLoggedIn();

if(isset($_POST['post_id']) && !empty($_POST['post_id']))
{
	if(!isset($_POST['date_published']) || empty($_POST['date_published']))
	{
		$stmt = $db->prepare("UPDATE posts SET date_published = now() WHERE post_id = ?");
	}
	else
	{
		$stmt = $db->prepare("UPDATE posts SET date_published = NULL WHERE post_id = ?");
	}

    $stmt->bind_param("s", $_POST['post_id']);

    if ($stmt->execute())
    {
        header('Location: /admin');
    }
    else
    {
         die('There was an error running the query [' . $db->error . ']');
    }
}
else
{
	//todo - error codes
	header('Location: /admin');
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea demissa var. demissa (Rutstr.) Ach.

### Remarks
null


text:
// This file is generated from PrimVector.template. DO NOT EDIT!
// Copyright (c) 2001, 2002, 2015  Per M.A. Bothner and Brainfood Inc.
// This is free software;  for terms and warranty disclaimer see ./COPYING.

package gnu.lists;
import java.io.*;

/** Simple adjustable-length vector of signed 64-bit integers (longs). */

public  class S64Vector extends LongVector<Long>
{
    public S64Vector() {
        data = empty;
    }

    public S64Vector(int size, long value) {
        long[] array = new long[size];
        data = array;
        if (value != 0) {
            while (--size >= 0)
                array[size] = value;
        }
    }

    public S64Vector(int size) {
        this(new long[size]);
    }

    /** Reuses the argument without making a copy. */
    public S64Vector(long[] data) {
        this.data = data;
    }

    /*
    public S64Vector(Sequence seq) {
        data = new long[seq.size()];
        addAll(seq);
    }
    */

    public S64Vector(long[] data, IntSequence indexes) {
        this.data = data;
        this.indexes = indexes;
    }

    /** Makes a copy of (part of) the argument array. */
    public S64Vector(long[] values, int offset, int length) {
        this(length);
        System.arraycopy(values, offset, data, 0, length);
    }

    public final Long get(int index) {
        if (indexes != null)
            index = indexes.intAt(index);
        return Long.valueOf(data[index]);
    }

    public final Long getBuffer(int index) {
        return Long.valueOf(data[index]);
    }

    @Override
    public final void setBuffer(int index, Long value) {
        data[index] = value.longValue();
    }

    @Override
    protected S64Vector withIndexes(IntSequence ind) {
        return new S64Vector(data, ind);
    }

    @Override
    public S64Vector subList(int fromIx, int toIx) {
        return new S64Vector(data, indexesSubList(fromIx, toIx));
    }

    public int getElementKind() { return INT_S64_VALUE; }

    public String getTag() { return "s64"; }

    public void consumePosRange(int iposStart, int iposEnd, Consumer out) {
        if (out.ignoring())
            return;
        int i = nextIndex(iposStart);
        int end = nextIndex(iposEnd);
        for (;  i < end;  i++)
            out.writeLong(longAt(i));
    }

    public int compareTo(Object obj) {
        S64Vector vec2 = (S64Vector) obj;
        long[] arr1 = data;
        long[] arr2 = vec2.data;
        int n1 = size();
        int n2 = vec2.size();
        IntSequence inds1 = getIndexesForce();
        IntSequence inds2 = vec2.getIndexesForce();
        int n = n1 > n2 ? n2 : n1;
        for (int i = 0;  i < n;  i++) {
            long v1 = arr1[inds1.intAt(i)];
            long v2 = arr2[inds2.intAt(i)];
            if (v1 != v2)
                return v1 > v2 ? 1 : -1;
        }
        return n1 - n2;
    }

}


text:
set -e

if [ -n "${MESOS_HOST}" ]; then
    if [ -z "${COLLECTD_HOST}" ]; then
        export COLLECTD_HOST="${MESOS_HOST}"
    fi
fi

if [ ! -e "/.initialized" ]; then
    touch "/.initialized"
    envtpl /etc/collectd/collectd.conf.tpl
fi

exec gosu nobody collectd -f > /dev/null


text:
<?php

namespace Oro\Bundle\EntityBundle\Form\Guesser;

use Doctrine\Common\Persistence\ManagerRegistry;

use Oro\Bundle\EntityConfigBundle\Provider\ConfigProviderInterface;

class FormConfigGuesser extends AbstractFormGuesser
{
    /**
     * @var ConfigProviderInterface
     */
    protected $formConfigProvider;

    /**
     * @param ManagerRegistry $managerRegistry
     * @param ConfigProviderInterface $entityConfigProvider
     * @param ConfigProviderInterface $formConfigProvider
     */
    public function __construct(
        ManagerRegistry $managerRegistry,
        ConfigProviderInterface $entityConfigProvider,
        ConfigProviderInterface $formConfigProvider
    ) {
        parent::__construct($managerRegistry, $entityConfigProvider);
        $this->formConfigProvider = $formConfigProvider;
    }

    /**
     * {@inheritDoc}
     */
    public function guessType($class, $property)
    {
        $metadata = $this->getMetadataForClass($class);
        if (!$metadata) {
            return $this->createDefaultTypeGuess();
        }

        if (!$this->formConfigProvider->hasConfig($class, $property)) {
            return $this->createDefaultTypeGuess();
        }

        $formConfig = $this->formConfigProvider->getConfig($class, $property);
        if (!$formConfig->has('form_type')) {
            // try to find form config for target class
            if ($property && $metadata->hasAssociation($property) && $metadata->isSingleValuedAssociation($property)) {
                return $this->guessType($metadata->getAssociationTargetClass($property), null);
            }

            return $this->createDefaultTypeGuess();
        }

        $formType = $formConfig->get('form_type');
        $formOptions = $formConfig->has('form_options') ? $formConfig->get('form_options') : array();
        $formOptions = $this->addLabelOption($formOptions, $class, $property);

        return $this->createTypeGuess($formType, $formOptions);
    }
}


text:
=pod

=head1 NAME

provider-digest - The digest library E<lt>-E<gt> provider functions

=head1 SYNOPSIS

=for openssl multiple includes

 #include <openssl/core_dispatch.h>
 #include <openssl/core_names.h>

 /*
  * Digests support the following function signatures in OSSL_DISPATCH arrays.
  * (The function signatures are not actual functions).
  */

 /* Context management */
 void *OSSL_FUNC_digest_newctx(void *provctx);
 void OSSL_FUNC_digest_freectx(void *dctx);
 void *OSSL_FUNC_digest_dupctx(void *dctx);

 /* Digest generation */
 int OSSL_FUNC_digest_init(void *dctx, const OSSL_PARAM params[]);
 int OSSL_FUNC_digest_update(void *dctx, const unsigned char *in, size_t inl);
 int OSSL_FUNC_digest_final(void *dctx, unsigned char *out, size_t *outl,
                            size_t outsz);
 int OSSL_FUNC_digest_digest(void *provctx, const unsigned char *in, size_t inl,
                             unsigned char *out, size_t *outl, size_t outsz);

 /* Digest parameter descriptors */
 const OSSL_PARAM *OSSL_FUNC_digest_gettable_params(void *provctx);

 /* Digest operation parameter descriptors */
 const OSSL_PARAM *OSSL_FUNC_digest_gettable_ctx_params(void *dctx,
                                                        void *provctx);
 const OSSL_PARAM *OSSL_FUNC_digest_settable_ctx_params(void *dctx,
                                                        void *provctx);

 /* Digest parameters */
 int OSSL_FUNC_digest_get_params(OSSL_PARAM params[]);

 /* Digest operation parameters */
 int OSSL_FUNC_digest_set_ctx_params(void *dctx, const OSSL_PARAM params[]);
 int OSSL_FUNC_digest_get_ctx_params(void *dctx, OSSL_PARAM params[]);

=head1 DESCRIPTION

This documentation is primarily aimed at provider authors. See L<provider(7)>
for further information.

The DIGEST operation enables providers to implement digest algorithms and make
them available to applications via the API functions L<EVP_DigestInit_ex(3)>,
L<EVP_DigestUpdate(3)> and L<EVP_DigestFinal(3)> (and other related functions).

All "functions" mentioned here are passed as function pointers between
F<libcrypto> and the provider in B<OSSL_DISPATCH> arrays via
B<OSSL_ALGORITHM> arrays that are returned by the provider's
provider_query_operation() function
(see L<provider-base(7)/Provider Functions>).

All these "functions" have a corresponding function type definition
named B<OSSL_FUNC_{name}_fn>, and a helper function to retrieve the
function pointer from an B<OSSL_DISPATCH> element named
B<OSSL_FUNC_{name}>.
For example, the "function" OSSL_FUNC_digest_newctx() has these:

 typedef void *(OSSL_FUNC_digest_newctx_fn)(void *provctx);
 static ossl_inline OSSL_FUNC_digest_newctx_fn
     OSSL_FUNC_digest_newctx(const OSSL_DISPATCH *opf);

B<OSSL_DISPATCH> arrays are indexed by numbers that are provided as
macros in L<openssl-core_dispatch.h(7)>, as follows:

 OSSL_FUNC_digest_newctx               OSSL_FUNC_DIGEST_NEWCTX
 OSSL_FUNC_digest_freectx              OSSL_FUNC_DIGEST_FREECTX
 OSSL_FUNC_digest_dupctx               OSSL_FUNC_DIGEST_DUPCTX

 OSSL_FUNC_digest_init                 OSSL_FUNC_DIGEST_INIT
 OSSL_FUNC_digest_update               OSSL_FUNC_DIGEST_UPDATE
 OSSL_FUNC_digest_final                OSSL_FUNC_DIGEST_FINAL
 OSSL_FUNC_digest_digest               OSSL_FUNC_DIGEST_DIGEST

 OSSL_FUNC_digest_get_params           OSSL_FUNC_DIGEST_GET_PARAMS
 OSSL_FUNC_digest_get_ctx_params       OSSL_FUNC_DIGEST_GET_CTX_PARAMS
 OSSL_FUNC_digest_set_ctx_params       OSSL_FUNC_DIGEST_SET_CTX_PARAMS

 OSSL_FUNC_digest_gettable_params      OSSL_FUNC_DIGEST_GETTABLE_PARAMS
 OSSL_FUNC_digest_gettable_ctx_params  OSSL_FUNC_DIGEST_GETTABLE_CTX_PARAMS
 OSSL_FUNC_digest_settable_ctx_params  OSSL_FUNC_DIGEST_SETTABLE_CTX_PARAMS

A digest algorithm implementation may not implement all of these functions.
In order to be usable all or none of OSSL_FUNC_digest_newctx, OSSL_FUNC_digest_freectx,
OSSL_FUNC_digest_init, OSSL_FUNC_digest_update and OSSL_FUNC_digest_final should be implemented.
All other functions are optional.

=head2 Context Management Functions

OSSL_FUNC_digest_newctx() should create and return a pointer to a provider side
structure for holding context information during a digest operation.
A pointer to this context will be passed back in a number of the other digest
operation function calls.
The parameter I<provctx> is the provider context generated during provider
initialisation (see L<provider(7)>).

OSSL_FUNC_digest_freectx() is passed a pointer to the provider side digest context in
the I<dctx> parameter.
This function should free any resources associated with that context.

OSSL_FUNC_digest_dupctx() should duplicate the provider side digest context in the
I<dctx> parameter and return the duplicate copy.

=head2 Digest Generation Functions

OSSL_FUNC_digest_init() initialises a digest operation given a newly created
provider side digest context in the I<dctx> parameter.
The I<params>, if not NULL, should be set on the context in a manner similar to
using OSSL_FUNC_digest_set_ctx_params().

OSSL_FUNC_digest_update() is called to supply data to be digested as part of a
previously initialised digest operation.
The I<dctx> parameter contains a pointer to a previously initialised provider
side context.
OSSL_FUNC_digest_update() should digest I<inl> bytes of data at the location pointed to
by I<in>.
OSSL_FUNC_digest_update() may be called multiple times for a single digest operation.

OSSL_FUNC_digest_final() generates a digest started through previous OSSL_FUNC_digest_init()
and OSSL_FUNC_digest_update() calls.
The I<dctx> parameter contains a pointer to the provider side context.
The digest should be written to I<*out> and the length of the digest to
I<*outl>.
The digest should not exceed I<outsz> bytes.

OSSL_FUNC_digest_digest() is a "oneshot" digest function.
No provider side digest context is used.
Instead the provider context that was created during provider initialisation is
passed in the I<provctx> parameter (see L<provider(7)>).
I<inl> bytes at I<in> should be digested and the result should be stored at
I<out>. The length of the digest should be stored in I<*outl> which should not
exceed I<outsz> bytes.

=head2 Digest Parameters

See L<OSSL_PARAM(3)> for further details on the parameters structure used by
these functions.

OSSL_FUNC_digest_get_params() gets details of the algorithm implementation
and stores them in I<params>.

OSSL_FUNC_digest_set_ctx_params() sets digest operation parameters for the
provider side digest context I<dctx> to I<params>.
Any parameter settings are additional to any that were previously set.
Passing NULL for I<params> should return true.

OSSL_FUNC_digest_get_ctx_params() gets digest operation details details from
the given provider side digest context I<dctx> and stores them in I<params>.
Passing NULL for I<params> should return true.

OSSL_FUNC_digest_gettable_params() returns a constant B<OSSL_PARAM> array
containing descriptors of the parameters that OSSL_FUNC_digest_get_params()
can handle.

OSSL_FUNC_digest_gettable_ctx_params() and
OSSL_FUNC_digest_settable_ctx_params() both return constant
B<OSSL_PARAM> arrays as descriptors of the parameters that
OSSL_FUNC_digest_get_ctx_params() and OSSL_FUNC_digest_set_ctx_params()
can handle, respectively.  The array is based on the current state of
the provider side context if I<dctx> is not NULL and on the provider
side algorithm I<provctx> otherwise.

Parameters currently recognised by built-in digests with this function
are as follows. Not all parameters are relevant to, or are understood
by all digests:

=over 4

=item "blocksize" (B<OSSL_DIGEST_PARAM_BLOCK_SIZE>) <unsigned integer>

The digest block size.
The length of the "blocksize" parameter should not exceed that of a B<size_t>.

=item "size" (B<OSSL_DIGEST_PARAM_SIZE>) <unsigned integer>

The digest output size.
The length of the "size" parameter should not exceed that of a B<size_t>.

=item "flags" (B<OSSL_DIGEST_PARAM_FLAGS>) <unsigned integer>

Diverse flags that describe exceptional behaviour for the digest:

=over 4

=item B<EVP_MD_FLAG_ONESHOT>

This digest method can only handle one block of input.

=item B<EVP_MD_FLAG_XOF>

This digest method is an extensible-output function (XOF) and supports
setting the B<OSSL_DIGEST_PARAM_XOFLEN> parameter.

=item B<EVP_MD_FLAG_DIGALGID_NULL>

When setting up a DigestAlgorithmIdentifier, this flag will have the
parameter set to NULL by default.  Use this for PKCS#1.  I<Note: if
combined with EVP_MD_FLAG_DIGALGID_ABSENT, the latter will override.>

=item B<EVP_MD_FLAG_DIGALGID_ABSENT>

When setting up a DigestAlgorithmIdentifier, this flag will have the
parameter be left absent by default.  I<Note: if combined with
EVP_MD_FLAG_DIGALGID_NULL, the latter will be overridden.>

=item B<EVP_MD_FLAG_DIGALGID_CUSTOM>

Custom DigestAlgorithmIdentifier handling via ctrl, with
B<EVP_MD_FLAG_DIGALGID_ABSENT> as default.  I<Note: if combined with
EVP_MD_FLAG_DIGALGID_NULL, the latter will be overridden.>
Currently unused.

=back

The length of the "flags" parameter should equal that of an
B<unsigned long int>.

=back

=head2 Digest Context Parameters

OSSL_FUNC_digest_set_ctx_params() sets digest parameters associated with the
given provider side digest context I<dctx> to I<params>.
Any parameter settings are additional to any that were previously set.
See L<OSSL_PARAM(3)> for further details on the parameters structure.

OSSL_FUNC_digest_get_ctx_params() gets details of currently set parameters
values associated with the give provider side digest context I<dctx>
and stores them in I<params>.
See L<OSSL_PARAM(3)> for further details on the parameters structure.

=head1 RETURN VALUES

OSSL_FUNC_digest_newctx() and OSSL_FUNC_digest_dupctx() should return the newly created
provider side digest context, or NULL on failure.

OSSL_FUNC_digest_init(), OSSL_FUNC_digest_update(), OSSL_FUNC_digest_final(), OSSL_FUNC_digest_digest(),
OSSL_FUNC_digest_set_params() and OSSL_FUNC_digest_get_params() should return 1 for success or
0 on error.

OSSL_FUNC_digest_size() should return the digest size.

OSSL_FUNC_digest_block_size() should return the block size of the underlying digest
algorithm.

=head1 BUGS

The EVP_Q_digest(), EVP_Digest() and EVP_DigestFinal_ex() API calls do not
expect the digest size to be larger than EVP_MAX_MD_SIZE. Any algorithm which
produces larger digests is unusable with those API calls.

=head1 SEE ALSO

L<provider(7)>, L<OSSL_PROVIDER-FIPS(7)>, L<OSSL_PROVIDER-default(7)>,
L<OSSL_PROVIDER-legacy(7)>,
L<EVP_MD-common(7)>, L<EVP_MD-BLAKE2(7)>, L<EVP_MD-MD2(7)>,
L<EVP_MD-MD4(7)>, L<EVP_MD-MD5(7)>, L<EVP_MD-MD5-SHA1(7)>,
L<EVP_MD-MDC2(7)>, L<EVP_MD-RIPEMD160(7)>, L<EVP_MD-SHA1(7)>,
L<EVP_MD-SHA2(7)>, L<EVP_MD-SHA3(7)>, L<EVP_MD-SHAKE(7)>,
L<EVP_MD-SM3(7)>, L<EVP_MD-WHIRLPOOL(7)>,
L<life_cycle-digest(7)>, L<EVP_DigestInit(3)>

=head1 HISTORY

The provider DIGEST interface was introduced in OpenSSL 3.0.

=head1 COPYRIGHT

Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved.

Licensed under the Apache License 2.0 (the "License").  You may not use
this file except in compliance with the License.  You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.

=cut


text:
require 'active_support/core_ext/hash/indifferent_access'

module ActionCable
  module Server
    # An instance of this configuration object is available via ActionCable.server.config, which allows you to tweak the configuration points
    # in a Rails config initializer.
    class Configuration
      attr_accessor :logger, :log_tags
      attr_accessor :connection_class, :worker_pool_size
      attr_accessor :redis_path, :channels_path
      attr_accessor :disable_request_forgery_protection, :allowed_request_origins

      def initialize
        @logger   = Rails.logger
        @log_tags = []

        @connection_class  = ApplicationCable::Connection
        @worker_pool_size  = 100

        @redis_path    = Rails.root.join('config/redis/cable.yml')
        @channels_path = Rails.root.join('app/channels')

        @disable_request_forgery_protection = false
      end

      def channel_paths
        @channels ||= Dir["#{channels_path}/**/*_channel.rb"]
      end

      def channel_class_names
        @channel_class_names ||= channel_paths.collect do |channel_path|
          Pathname.new(channel_path).basename.to_s.split('.').first.camelize
        end
      end

      def redis
        @redis ||= config_for(redis_path).with_indifferent_access
      end

      private
        # FIXME: Extract this from Rails::Application in a way it can be used here.
        def config_for(path)
          if path.exist?
            require "yaml"
            require "erb"
            (YAML.load(ERB.new(path.read).result) || {})[Rails.env] || {}
          else
            raise "Could not load configuration. No such file - #{path}"
          end
        rescue Psych::SyntaxError => e
          raise "YAML syntax error occurred while parsing #{path}. " \
            "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
            "Error: #{e.message}"
        end
    end
  end
end


text:
<!doctype html>
<html lang="en">

<head>
  <meta http-equiv="X-UA-Compatible" content="IE=11">
  <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
  <META HTTP-EQUIV="Expires" CONTENT="-1">
  <meta charset="utf-8">
  <title>MedTimeLine</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <script> if (global === undefined) { var global = window; }</script>
</head>

<body class="mat-app-background">
  <app-root></app-root>
</body>

</html>


text:
GoLearn
=======

[![GoDoc](https://godoc.org/github.com/sjwhitworth/golearn?status.png)](https://godoc.org/github.com/sjwhitworth/golearn)
[![Build Status](https://travis-ci.org/sjwhitworth/golearn.png?branch=master)](https://travis-ci.org/sjwhitworth/golearn)

[![Support via Gittip](https://rawgithub.com/twolfson/gittip-badge/0.2.0/dist/gittip.png)](https://www.gittip.com/sjwhitworth/)

GoLearn is a 'batteries included' machine learning library for Go. **Simplicity**, paired with customisability, is the goal.
We are in active development, and would love comments from users out in the wild. Drop us a line on Twitter.

twitter: [@golearn_ml](http://www.twitter.com/golearn_ml)

Install
=======

See [here](https://github.com/sjwhitworth/golearn/wiki/Installation) for installation instructions.

Getting Started
=======

Data are loaded in as Instances. You can then perform matrix like operations on them, and pass them to estimators.
GoLearn implements the scikit-learn interface of Fit/Predict, so you can easily swap out estimators for trial and error.
GoLearn also includes helper functions for data, like cross validation, and train and test splitting.

```go
// Load in a dataset, with headers. Header attributes will be stored.
// Think of instances as a Data Frame structure in R or Pandas.
// You can also create instances from scratch.
data, err := base.ParseCSVToInstances("datasets/iris_headers.csv", true)

// Print a pleasant summary of your data.
fmt.Println(data)

// Split your dataframe into a training set, and a test set, with an 80/20 proportion.
trainTest := base.InstancesTrainTestSplit(rawData, 0.8)
trainData := trainTest[0]
testData := trainTest[1]

// Instantiate a new KNN classifier. Euclidean distance, with 2 neighbours.
cls := knn.NewKnnClassifier("euclidean", 2)

// Fit it on your training data.
cls.Fit(trainData)

// Get your predictions against test instances.
predictions := cls.Predict(testData)

// Print a confusion matrix with precision and recall metrics.
confusionMat := evaluation.GetConfusionMatrix(testData, predictions)
fmt.Println(evaluation.GetSummary(confusionMat))
```

```
Iris-virginica	28	2	  56	0.9333	0.9333  0.9333
Iris-setosa	    29	0	  59	1.0000  1.0000	1.0000
Iris-versicolor	27	2	  57	0.9310	0.9310  0.9310
Overall accuracy: 0.9545
```

Examples
========

GoLearn comes with practical examples. Dive in and see what is going on.

```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/knnclassifier
go run knnclassifier_iris.go
```
```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/instances
go run instances.go
```
```bash
cd $GOPATH/src/github.com/sjwhitworth/golearn/examples/trees
go run trees.go
```

Join the team
=============

Please send me a mail at stephen dot whitworth at hailocab dot com.