text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.xml.parsers.ParserConfigurationException;

import com.google.common.collect.ImmutableList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy;
import org.xml.sax.SAXException;

import com.google.common.annotations.VisibleForTesting;
import java.util.Iterator;
import java.util.Set;
import org.apache.hadoop.yarn.api.records.Resource;

/**
 * Maintains a list of queues as well as scheduling parameters for each queue,
 * such as guaranteed share allocations, from the fair scheduler config file.
 */
@Private
@Unstable
public class QueueManager {
  public static final Log LOG = LogFactory.getLog(
    QueueManager.class.getName());

  public static final String ROOT_QUEUE = "root";

  private final FairScheduler scheduler;

  private final Collection<FSLeafQueue> leafQueues =
      new CopyOnWriteArrayList<FSLeafQueue>();
  private final Map<String, FSQueue> queues = new HashMap<String, FSQueue>();
  private FSParentQueue rootQueue;

  public QueueManager(FairScheduler scheduler) {
    this.scheduler = scheduler;
  }

  public FSParentQueue getRootQueue() {
    return rootQueue;
  }

  public void initialize(Configuration conf) throws IOException,
      SAXException, AllocationConfigurationException, ParserConfigurationException {
    // Policies of root and default queue are set to
    // SchedulingPolicy.DEFAULT_POLICY since the allocation file hasn't been
    // loaded yet.
    rootQueue = new FSParentQueue("root", scheduler, null);
    queues.put(rootQueue.getName(), rootQueue);

    // Create the default queue
    getLeafQueue(YarnConfiguration.DEFAULT_QUEUE_NAME, true);
    // Recursively reinitialize to propagate queue properties
    rootQueue.reinit(true);
  }

  /**
   * Get a leaf queue by name, creating it if the create param is true and is necessary.
   * If the queue is not or can not be a leaf queue, i.e. it already exists as a
   * parent queue, or one of the parents in its name is already a leaf queue,
   * null is returned.
   *
   * The root part of the name is optional, so a queue underneath the root
   * named "queue1" could be referred to  as just "queue1", and a queue named
   * "queue2" underneath a parent named "parent1" that is underneath the root
   * could be referred to as just "parent1.queue2".
   */
  public FSLeafQueue getLeafQueue(String name, boolean create) {
    return getLeafQueue(name, create, true);
  }

  public FSLeafQueue getLeafQueue(
      String name,
      boolean create,
      boolean recomputeSteadyShares) {
    FSQueue queue = getQueue(
        name,
        create,
        FSQueueType.LEAF,
        recomputeSteadyShares
    );
    if (queue instanceof FSParentQueue) {
      return null;
    }
    return (FSLeafQueue) queue;
  }

  /**
   * Remove a leaf queue if empty
   * @param name name of the queue
   * @return true if queue was removed or false otherwise
   */
  public boolean removeLeafQueue(String name) {
    name = ensureRootPrefix(name);
    return removeEmptyIncompatibleQueues(name, FSQueueType.PARENT);
  }

  /**
   * Get a parent queue by name, creating it if the create param is true and is necessary.
   * If the queue is not or can not be a parent queue, i.e. it already exists as a
   * leaf queue, or one of the parents in its name is already a leaf queue,
   * null is returned.
   *
   * The root part of the name is optional, so a queue underneath the root
   * named "queue1" could be referred to  as just "queue1", and a queue named
   * "queue2" underneath a parent named "parent1" that is underneath the root
   * could be referred to as just "parent1.queue2".
   */
  public FSParentQueue getParentQueue(String name, boolean create) {
    return getParentQueue(name, create, true);
  }

  public FSParentQueue getParentQueue(
      String name,
      boolean create,
      boolean recomputeSteadyShares) {
    FSQueue queue = getQueue(
        name,
        create,
        FSQueueType.PARENT,
        recomputeSteadyShares
    );
    if (queue instanceof FSLeafQueue) {
      return null;
    }
    return (FSParentQueue) queue;
  }

  private FSQueue getQueue(
      String name,
      boolean create,
      FSQueueType queueType,
      boolean recomputeSteadyShares) {
    boolean recompute = recomputeSteadyShares;
    name = ensureRootPrefix(name);
    FSQueue queue;
    synchronized (queues) {
      queue = queues.get(name);
      if (queue == null && create) {
        // if the queue doesn't exist,create it and return
        queue = createQueue(name, queueType);
      } else {
        recompute = false;
      }
    }
    if (recompute) {
      rootQueue.recomputeSteadyShares();
    }
    return queue;
  }

  /**
   * Create a leaf or parent queue based on what is specified in
   * {@code queueType} and place it in the tree. Create any parents that don't
   * already exist.
   *
   * @return the created queue, if successful or null if not allowed (one of the
   * parent queues in the queue name is already a leaf queue)
   */
  @VisibleForTesting
  FSQueue createQueue(String name, FSQueueType queueType) {
    List<String> newQueueNames = new ArrayList<>();
    FSParentQueue parent = buildNewQueueList(name, newQueueNames);
    FSQueue queue = null;

    if (parent != null) {
      // Now that we know everything worked out, make all the queues
      // and add them to the map.
      queue = createNewQueues(queueType, parent, newQueueNames);
    }

    return queue;
  }

  /**
   * Compile a list of all parent queues of the given queue name that do not
   * already exist. The queue names will be added to the {@code newQueueNames}
   * list. The list will be in order of increasing queue depth. The first
   * element of the list will be the parent closest to the root. The last
   * element added will be the queue to be created. This method returns the
   * deepest parent that does exist.
   *
   * @param name the fully qualified name of the queue to create
   * @param newQueueNames the list to which to add non-existent queues
   * @return the deepest existing parent queue
   */
  private FSParentQueue buildNewQueueList(String name,
      List<String> newQueueNames) {
    newQueueNames.add(name);
    int sepIndex = name.length();
    FSParentQueue parent = null;

    // Move up the queue tree until we reach one that exists.
    while (sepIndex != -1) {
      int prevSepIndex = sepIndex;
      sepIndex = name.lastIndexOf('.', sepIndex-1);
      String node = name.substring(sepIndex+1, prevSepIndex);
      if (!isQueueNameValid(node)) {
        throw new InvalidQueueNameException("Illegal node name at offset " +
            (sepIndex+1) + " for queue name " + name);
      }

      String curName = name.substring(0, sepIndex);
      FSQueue queue = queues.get(curName);

      if (queue == null) {
        newQueueNames.add(0, curName);
      } else {
        if (queue instanceof FSParentQueue) {
          parent = (FSParentQueue)queue;
        }

        // If the queue isn't a parent queue, parent will still be null when
        // we break

        break;
      }
    }

    return parent;
  }

  /**
   * Create all queues in the {@code newQueueNames} list. The list must be in
   * order of increasing depth. All but the last element in the list will be
   * created as parent queues. The last element will be created as the type
   * specified by the {@code queueType} parameter. The first queue will be
   * created as a child of the {@code topParent} queue. All subsequent queues
   * will be created as a child of the previously created queue.
   *
   * @param queueType the type of the last queue to create
   * @param topParent the parent of the first queue to create
   * @param newQueueNames the list of queues to create
   * @return the last queue created
   */
  private FSQueue createNewQueues(FSQueueType queueType,
      FSParentQueue topParent, List<String> newQueueNames) {
    AllocationConfiguration queueConf = scheduler.getAllocationConfiguration();
    Iterator<String> i = newQueueNames.iterator();
    FSParentQueue parent = topParent;
    FSQueue queue = null;

    while (i.hasNext()) {
      FSParentQueue newParent = null;
      String queueName = i.next();

      // Check if child policy is allowed
      SchedulingPolicy childPolicy = scheduler.getAllocationConfiguration().
          getSchedulingPolicy(queueName);
      if (!parent.getPolicy().isChildPolicyAllowed(childPolicy)) {
        LOG.error("Can't create queue '" + queueName + "'.");
        return null;
      }

      // Only create a leaf queue at the very end
      if (!i.hasNext() && (queueType != FSQueueType.PARENT)) {
        FSLeafQueue leafQueue = new FSLeafQueue(queueName, scheduler, parent);
        leafQueues.add(leafQueue);
        queue = leafQueue;
      } else {
        if (childPolicy instanceof FifoPolicy) {
          LOG.error("Can't create queue '" + queueName + "', since "
              + FifoPolicy.NAME + " is only for leaf queues.");
          return null;
        }
        newParent = new FSParentQueue(queueName, scheduler, parent);
        queue = newParent;
      }

      parent.addChildQueue(queue);
      setChildResourceLimits(parent, queue, queueConf);
      queues.put(queue.getName(), queue);

      // If we just created a leaf node, the newParent is null, but that's OK
      // because we only create a leaf node in the very last iteration.
      parent = newParent;
    }

    return queue;
  }

  /**
   * For the given child queue, set the max resources based on the
   * parent queue's default child resource settings. This method assumes that
   * the child queue is ad hoc and hence does not do any safety checks around
   * overwriting existing max resource settings.
   *
   * @param parent the parent queue
   * @param child the child queue
   * @param queueConf the {@link AllocationConfiguration}
   */
  void setChildResourceLimits(FSParentQueue parent, FSQueue child,
      AllocationConfiguration queueConf) {
    Map<FSQueueType, Set<String>> configuredQueues =
        queueConf.getConfiguredQueues();

    // Ad hoc queues do not exist in the configured queues map
    if (!configuredQueues.get(FSQueueType.LEAF).contains(child.getName()) &&
        !configuredQueues.get(FSQueueType.PARENT).contains(child.getName())) {
      // For ad hoc queues, set their max reource allocations based on
      // their parents' default child settings.
      Resource maxChild = parent.getMaxChildQueueResource();

      if (maxChild != null) {
        child.setMaxShare(maxChild);
      }
    }
  }

  /**
   * Make way for the given queue if possible, by removing incompatible
   * queues with no apps in them. Incompatibility could be due to
   * (1) queueToCreate being currently a parent but needs to change to leaf
   * (2) queueToCreate being currently a leaf but needs to change to parent
   * (3) an existing leaf queue in the ancestry of queueToCreate.
   *
   * We will never remove the root queue or the default queue in this way.
   *
   * @return true if we can create queueToCreate or it already exists.
   */
  private boolean removeEmptyIncompatibleQueues(String queueToCreate,
      FSQueueType queueType) {
    queueToCreate = ensureRootPrefix(queueToCreate);

    // Ensure queueToCreate is not root and doesn't have the default queue in its
    // ancestry.
    if (queueToCreate.equals(ROOT_QUEUE) ||
        queueToCreate.startsWith(
            ROOT_QUEUE + "." + YarnConfiguration.DEFAULT_QUEUE_NAME + ".")) {
      return false;
    }

    FSQueue queue = queues.get(queueToCreate);
    // Queue exists already.
    if (queue != null) {
      if (queue instanceof FSLeafQueue) {
        if (queueType == FSQueueType.LEAF) {
          // if queue is already a leaf then return true
          return true;
        }
        // remove incompatibility since queue is a leaf currently
        // needs to change to a parent.
        return removeQueueIfEmpty(queue);
      } else {
        if (queueType == FSQueueType.PARENT) {
          return true;
        }
        // If it's an existing parent queue and needs to change to leaf,
        // remove it if it's empty.
        return removeQueueIfEmpty(queue);
      }
    }

    // Queue doesn't exist already. Check if the new queue would be created
    // under an existing leaf queue. If so, try removing that leaf queue.
    int sepIndex = queueToCreate.length();
    sepIndex = queueToCreate.lastIndexOf('.', sepIndex-1);
    while (sepIndex != -1) {
      String prefixString = queueToCreate.substring(0, sepIndex);
      FSQueue prefixQueue = queues.get(prefixString);
      if (prefixQueue != null && prefixQueue instanceof FSLeafQueue) {
        return removeQueueIfEmpty(prefixQueue);
      }
      sepIndex = queueToCreate.lastIndexOf('.', sepIndex-1);
    }
    return true;
  }

  /**
   * Remove the queue if it and its descendents are all empty.
   * @param queue
   * @return true if removed, false otherwise
   */
  private boolean removeQueueIfEmpty(FSQueue queue) {
    if (isEmpty(queue)) {
      removeQueue(queue);
      return true;
    }
    return false;
  }

  /**
   * Remove a queue and all its descendents.
   */
  private void removeQueue(FSQueue queue) {
    synchronized (queues) {
      if (queue instanceof FSLeafQueue) {
        leafQueues.remove(queue);
      } else {
        for (FSQueue childQueue:queue.getChildQueues()) {
          removeQueue(childQueue);
        }
      }
      queues.remove(queue.getName());
      FSParentQueue parent = queue.getParent();
      parent.removeChildQueue(queue);
    }
  }

  /**
   * Returns true if there are no applications, running or not, in the given
   * queue or any of its descendents.
   */
  protected boolean isEmpty(FSQueue queue) {
    if (queue instanceof FSLeafQueue) {
      FSLeafQueue leafQueue = (FSLeafQueue)queue;
      return queue.getNumRunnableApps() == 0 &&
          leafQueue.getNumNonRunnableApps() == 0;
    } else {
      for (FSQueue child : queue.getChildQueues()) {
        if (!isEmpty(child)) {
          return false;
        }
      }
      return true;
    }
  }

  /**
   * Gets a queue by name.
   */
  public FSQueue getQueue(String name) {
    name = ensureRootPrefix(name);
    synchronized (queues) {
      return queues.get(name);
    }
  }

  /**
   * Return whether a queue exists already.
   */
  public boolean exists(String name) {
    name = ensureRootPrefix(name);
    synchronized (queues) {
      return queues.containsKey(name);
    }
  }

  /**
   * Get a collection of all leaf queues
   */
  public Collection<FSLeafQueue> getLeafQueues() {
    synchronized (queues) {
      return leafQueues;
    }
  }

  /**
   * Get a collection of all queues
   */
  public Collection<FSQueue> getQueues() {
    synchronized (queues) {
      return ImmutableList.copyOf(queues.values());
    }
  }

  private String ensureRootPrefix(String name) {
    if (!name.startsWith(ROOT_QUEUE + ".") && !name.equals(ROOT_QUEUE)) {
      name = ROOT_QUEUE + "." + name;
    }
    return name;
  }

  public void updateAllocationConfiguration(AllocationConfiguration queueConf) {
    // Create leaf queues and the parent queues in a leaf's ancestry if they do not exist
    synchronized (queues) {
      // Verify and set scheduling policies for existing queues before creating
      // any queue, since we need parent policies to determine if we can create
      // its children.
      if (!rootQueue.verifyAndSetPolicyFromConf(queueConf)) {
        LOG.error("Setting scheduling policies for existing queues failed!");
      }

      for (String name : queueConf.getConfiguredQueues().get(
              FSQueueType.LEAF)) {
        if (removeEmptyIncompatibleQueues(name, FSQueueType.LEAF)) {
          getLeafQueue(name, true, false);
        }
      }
      // At this point all leaves and 'parents with
      // at least one child' would have been created.
      // Now create parents with no configured leaf.
      for (String name : queueConf.getConfiguredQueues().get(
          FSQueueType.PARENT)) {
        if (removeEmptyIncompatibleQueues(name, FSQueueType.PARENT)) {
          getParentQueue(name, true, false);
        }
      }
    }

    // Initialize all queues recursively
    rootQueue.reinit(true);
    // Update steady fair shares for all queues
    rootQueue.recomputeSteadyShares();
  }

  /**
   * Check whether queue name is valid,
   * return true if it is valid, otherwise return false.
   */
  @VisibleForTesting
  boolean isQueueNameValid(String node) {
    // use the same white space trim as in QueueMetrics() otherwise things fail
    // This needs to trim additional Unicode whitespace characters beyond what
    // the built-in JDK methods consider whitespace. See YARN-5272.
    return !node.isEmpty() &&
        node.equals(FairSchedulerUtilities.trimQueueName(node));
  }
}


text:
use std::{
    convert::Infallible,
    io::{Read, Write},
    net, thread,
    time::{Duration, Instant},
};

use actix_http::{
    body::{self, BodyStream, BoxBody, SizedStream},
    header, Error, HttpService, KeepAlive, Request, Response, StatusCode,
};
use actix_http_test::test_server;
use actix_rt::time::sleep;
use actix_service::fn_service;
use actix_utils::future::{err, ok, ready};
use bytes::Bytes;
use derive_more::{Display, Error};
use futures_util::{
    stream::{once, StreamExt as _},
    FutureExt as _,
};
use regex::Regex;

#[actix_rt::test]
async fn h1_basic() {
    let mut srv = test_server(|| {
        HttpService::build()
            .keep_alive(KeepAlive::Disabled)
            .client_request_timeout(Duration::from_secs(1))
            .client_disconnect_timeout(Duration::from_secs(1))
            .h1(|req: Request| {
                assert!(req.peer_addr().is_some());
                ok::<_, Infallible>(Response::ok())
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_2() {
    let mut srv = test_server(|| {
        HttpService::build()
            .keep_alive(KeepAlive::Disabled)
            .client_request_timeout(Duration::from_secs(1))
            .client_disconnect_timeout(Duration::from_secs(1))
            .finish(|req: Request| {
                assert!(req.peer_addr().is_some());
                assert_eq!(req.version(), http::Version::HTTP_11);
                ok::<_, Infallible>(Response::ok())
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    srv.stop().await;
}

#[derive(Debug, Display, Error)]
#[display(fmt = "expect failed")]
struct ExpectFailed;

impl From<ExpectFailed> for Response<BoxBody> {
    fn from(_: ExpectFailed) -> Self {
        Response::new(StatusCode::EXPECTATION_FAILED)
    }
}

#[actix_rt::test]
async fn expect_continue() {
    let mut srv = test_server(|| {
        HttpService::build()
            .expect(fn_service(|req: Request| {
                if req.head().uri.query() == Some("yes=") {
                    ok(req)
                } else {
                    err(ExpectFailed)
                }
            }))
            .finish(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 417 Expectation Failed\r\ncontent-length"));

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));

    srv.stop().await;
}

#[actix_rt::test]
async fn expect_continue_h1() {
    let mut srv = test_server(|| {
        HttpService::build()
            .expect(fn_service(|req: Request| {
                sleep(Duration::from_millis(20)).then(move |_| {
                    if req.head().uri.query() == Some("yes=") {
                        ok(req)
                    } else {
                        err(ExpectFailed)
                    }
                })
            }))
            .h1(fn_service(|_| ok::<_, Infallible>(Response::ok())))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 417 Expectation Failed\r\ncontent-length"));

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test?yes= HTTP/1.1\r\nexpect: 100-continue\r\n\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n"));

    srv.stop().await;
}

#[actix_rt::test]
async fn chunked_payload() {
    let chunk_sizes = vec![32768, 32, 32768];
    let total_size: usize = chunk_sizes.iter().sum();

    let mut srv = test_server(|| {
        HttpService::build()
            .h1(fn_service(|mut request: Request| {
                request
                    .take_payload()
                    .map(|res| match res {
                        Ok(pl) => pl,
                        Err(e) => panic!("Error reading payload: {}", e),
                    })
                    .fold(0usize, |acc, chunk| ready(acc + chunk.len()))
                    .map(|req_size| {
                        Ok::<_, Error>(Response::ok().set_body(format!("size={}", req_size)))
                    })
            }))
            .tcp()
    })
    .await;

    let returned_size = {
        let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
        let _ = stream.write_all(b"POST /test HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n");

        for chunk_size in chunk_sizes.iter() {
            let mut bytes = Vec::new();
            let random_bytes: Vec<u8> =
                (0..*chunk_size).map(|_| rand::random::<u8>()).collect();

            bytes.extend(format!("{:X}\r\n", chunk_size).as_bytes());
            bytes.extend(&random_bytes[..]);
            bytes.extend(b"\r\n");
            let _ = stream.write_all(&bytes);
        }

        let _ = stream.write_all(b"0\r\n\r\n");
        stream.shutdown(net::Shutdown::Write).unwrap();

        let mut data = String::new();
        let _ = stream.read_to_string(&mut data);

        let re = Regex::new(r"size=(\d+)").unwrap();
        let size: usize = match re.captures(&data) {
            Some(caps) => caps.get(1).unwrap().as_str().parse().unwrap(),
            None => panic!("Failed to find size in HTTP Response: {}", data),
        };

        size
    };

    assert_eq!(returned_size, total_size);

    srv.stop().await;
}

#[actix_rt::test]
async fn slow_request_408() {
    let mut srv = test_server(|| {
        HttpService::build()
            .client_request_timeout(Duration::from_millis(200))
            .keep_alive(Duration::from_secs(2))
            .finish(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let start = Instant::now();

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test HTTP/1.1\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(
        data.starts_with("HTTP/1.1 408 Request Timeout"),
        "response was not 408: {}",
        data
    );

    let diff = start.elapsed();

    if diff < Duration::from_secs(1) {
        // test success
    } else if diff < Duration::from_secs(3) {
        panic!("request seems to have wrongly timed-out according to keep-alive");
    } else {
        panic!("request took way too long to time out");
    }

    srv.stop().await;
}

#[actix_rt::test]
async fn http1_malformed_request() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP1.1\r\n");
    let mut data = String::new();
    let _ = stream.read_to_string(&mut data);
    assert!(data.starts_with("HTTP/1.1 400 Bad Request"));

    srv.stop().await;
}

#[actix_rt::test]
async fn http1_keepalive() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    srv.stop().await;
}

#[actix_rt::test]
async fn http1_keepalive_timeout() {
    let mut srv = test_server(|| {
        HttpService::build()
            .keep_alive(Duration::from_secs(1))
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();

    let _ = stream.write_all(b"GET /test HTTP/1.1\r\n\r\n");
    let mut data = vec![0; 256];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    thread::sleep(Duration::from_millis(1100));

    let mut data = vec![0; 256];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);

    srv.stop().await;
}

#[actix_rt::test]
async fn http1_keepalive_close() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\nconnection: close\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);

    srv.stop().await;
}

#[actix_rt::test]
async fn http10_keepalive_default_close() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);

    srv.stop().await;
}

#[actix_rt::test]
async fn http10_keepalive() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ =
        stream.write_all(b"GET /test/tests/test HTTP/1.0\r\nconnection: keep-alive\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n");

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.0\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.0 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);

    srv.stop().await;
}

#[actix_rt::test]
async fn http1_keepalive_disabled() {
    let mut srv = test_server(|| {
        HttpService::build()
            .keep_alive(KeepAlive::Disabled)
            .h1(|_| ok::<_, Infallible>(Response::ok()))
            .tcp()
    })
    .await;

    let mut stream = net::TcpStream::connect(srv.addr()).unwrap();
    let _ = stream.write_all(b"GET /test/tests/test HTTP/1.1\r\n\r\n");
    let mut data = vec![0; 1024];
    let _ = stream.read(&mut data);
    assert_eq!(&data[..17], b"HTTP/1.1 200 OK\r\n");

    let mut data = vec![0; 1024];
    let res = stream.read(&mut data).unwrap();
    assert_eq!(res, 0);

    srv.stop().await;
}

#[actix_rt::test]
async fn content_length() {
    use actix_http::{
        header::{HeaderName, HeaderValue},
        StatusCode,
    };

    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|req: Request| {
                let indx: usize = req.uri().path()[1..].parse().unwrap();
                let statuses = [
                    StatusCode::NO_CONTENT,
                    StatusCode::CONTINUE,
                    StatusCode::SWITCHING_PROTOCOLS,
                    StatusCode::PROCESSING,
                    StatusCode::OK,
                    StatusCode::NOT_FOUND,
                ];
                ok::<_, Infallible>(Response::new(statuses[indx]))
            })
            .tcp()
    })
    .await;

    let header = HeaderName::from_static("content-length");
    let value = HeaderValue::from_static("0");

    {
        for i in 0..4 {
            let req = srv.request(http::Method::GET, srv.url(&format!("/{}", i)));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), None);

            let req = srv.request(http::Method::HEAD, srv.url(&format!("/{}", i)));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), None);
        }

        for i in 4..6 {
            let req = srv.request(http::Method::GET, srv.url(&format!("/{}", i)));
            let response = req.send().await.unwrap();
            assert_eq!(response.headers().get(&header), Some(&value));
        }
    }

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_headers() {
    let data = STR.repeat(10);
    let data2 = data.clone();

    let mut srv = test_server(move || {
        let data = data.clone();
        HttpService::build()
            .h1(move |_| {
                let mut builder = Response::build(StatusCode::OK);
                for idx in 0..90 {
                    builder.insert_header((
                    format!("X-TEST-{}", idx).as_str(),
                    "TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST \
                        TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST ",
                ));
                }
                ok::<_, Infallible>(builder.body(data.clone()))
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from(data2));

    srv.stop().await;
}

const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World \
                   Hello World Hello World Hello World Hello World Hello World";

#[actix_rt::test]
async fn h1_body() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_head_empty() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
            .tcp()
    })
    .await;

    let response = srv.head("/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response
            .headers()
            .get(http::header::CONTENT_LENGTH)
            .unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert!(bytes.is_empty());

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_head_binary() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
            .tcp()
    })
    .await;

    let response = srv.head("/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response
            .headers()
            .get(http::header::CONTENT_LENGTH)
            .unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert!(bytes.is_empty());

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_head_binary2() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
            .tcp()
    })
    .await;

    let response = srv.head("/").send().await.unwrap();
    assert!(response.status().is_success());

    {
        let len = response
            .headers()
            .get(http::header::CONTENT_LENGTH)
            .unwrap();
        assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
    }

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_body_length() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| {
                let body = once(ok::<_, Infallible>(Bytes::from_static(STR.as_ref())));
                ok::<_, Infallible>(
                    Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
                )
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_body_chunked_explicit() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| {
                let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
                ok::<_, Infallible>(
                    Response::build(StatusCode::OK)
                        .insert_header((header::TRANSFER_ENCODING, "chunked"))
                        .body(BodyStream::new(body)),
                )
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());
    assert_eq!(
        response
            .headers()
            .get(header::TRANSFER_ENCODING)
            .unwrap()
            .to_str()
            .unwrap(),
        "chunked"
    );

    // read response
    let bytes = srv.load_body(response).await.unwrap();

    // decode
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_body_chunked_implicit() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| {
                let body = once(ok::<_, Error>(Bytes::from_static(STR.as_ref())));
                ok::<_, Infallible>(Response::build(StatusCode::OK).body(BodyStream::new(body)))
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());
    assert_eq!(
        response
            .headers()
            .get(header::TRANSFER_ENCODING)
            .unwrap()
            .to_str()
            .unwrap(),
        "chunked"
    );

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(STR.as_ref()));

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_response_http_error_handling() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(fn_service(|_| {
                let broken_header = Bytes::from_static(b"\0\0\0");
                ok::<_, Infallible>(
                    Response::build(StatusCode::OK)
                        .insert_header((http::header::CONTENT_TYPE, broken_header))
                        .body(STR),
                )
            }))
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert_eq!(response.status(), http::StatusCode::INTERNAL_SERVER_ERROR);

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(
        bytes,
        Bytes::from_static(b"error processing HTTP: failed to parse header value")
    );

    srv.stop().await;
}

#[derive(Debug, Display, Error)]
#[display(fmt = "error")]
struct BadRequest;

impl From<BadRequest> for Response<BoxBody> {
    fn from(_: BadRequest) -> Self {
        Response::bad_request().set_body(BoxBody::new("error"))
    }
}

#[actix_rt::test]
async fn h1_service_error() {
    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|_| err::<Response<()>, _>(BadRequest))
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert_eq!(response.status(), http::StatusCode::BAD_REQUEST);

    // read response
    let bytes = srv.load_body(response).await.unwrap();
    assert_eq!(bytes, Bytes::from_static(b"error"));

    srv.stop().await;
}

#[actix_rt::test]
async fn h1_on_connect() {
    let mut srv = test_server(|| {
        HttpService::build()
            .on_connect_ext(|_, data| {
                data.insert(20isize);
            })
            .h1(|req: Request| {
                assert!(req.conn_data::<isize>().is_some());
                ok::<_, Infallible>(Response::ok())
            })
            .tcp()
    })
    .await;

    let response = srv.get("/").send().await.unwrap();
    assert!(response.status().is_success());

    srv.stop().await;
}

/// Tests compliance with 304 Not Modified spec in RFC 7232 §4.1.
/// https://datatracker.ietf.org/doc/html/rfc7232#section-4.1
#[actix_rt::test]
async fn not_modified_spec_h1() {
    // TODO: this test needing a few seconds to complete reveals some weirdness with either the
    // dispatcher or the client, though similar hangs occur on other tests in this file, only
    // succeeding, it seems, because of the keepalive timer

    static CL: header::HeaderName = header::CONTENT_LENGTH;

    let mut srv = test_server(|| {
        HttpService::build()
            .h1(|req: Request| {
                let res: Response<BoxBody> = match req.path() {
                    // with no content-length
                    "/none" => Response::with_body(StatusCode::NOT_MODIFIED, body::None::new())
                        .map_into_boxed_body(),

                    // with no content-length
                    "/body" => Response::with_body(StatusCode::NOT_MODIFIED, "1234")
                        .map_into_boxed_body(),

                    // with manual content-length header and specific None body
                    "/cl-none" => {
                        let mut res =
                            Response::with_body(StatusCode::NOT_MODIFIED, body::None::new());
                        res.headers_mut()
                            .insert(CL.clone(), header::HeaderValue::from_static("24"));
                        res.map_into_boxed_body()
                    }

                    // with manual content-length header and ignore-able body
                    "/cl-body" => {
                        let mut res = Response::with_body(StatusCode::NOT_MODIFIED, "1234");
                        res.headers_mut()
                            .insert(CL.clone(), header::HeaderValue::from_static("4"));
                        res.map_into_boxed_body()
                    }

                    _ => panic!("unknown route"),
                };

                ok::<_, Infallible>(res)
            })
            .tcp()
    })
    .await;

    let res = srv.get("/none").send().await.unwrap();
    assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED);
    assert_eq!(res.headers().get(&CL), None);
    assert!(srv.load_body(res).await.unwrap().is_empty());

    let res = srv.get("/body").send().await.unwrap();
    assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED);
    assert_eq!(res.headers().get(&CL), None);
    assert!(srv.load_body(res).await.unwrap().is_empty());

    let res = srv.get("/cl-none").send().await.unwrap();
    assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED);
    assert_eq!(
        res.headers().get(&CL),
        Some(&header::HeaderValue::from_static("24")),
    );
    assert!(srv.load_body(res).await.unwrap().is_empty());

    let res = srv.get("/cl-body").send().await.unwrap();
    assert_eq!(res.status(), http::StatusCode::NOT_MODIFIED);
    assert_eq!(
        res.headers().get(&CL),
        Some(&header::HeaderValue::from_static("4")),
    );
    // server does not prevent payload from being sent but clients may choose not to read it
    // TODO: this is probably a bug in the client, especially since CL header can differ in length
    // from the body
    assert!(!srv.load_body(res).await.unwrap().is_empty());

    // TODO: add stream response tests

    srv.stop().await;
}

redpajama_set_name: RedPajamaGithub


text:
class Form < ActiveRecord::Base
  include DynamicForms::Models::Form
end


text:
cask "openboard" do
  version "1.6.1"
  sha256 "feb8cc1a9182df28a422602a683923d40f650c815d089fa6e15eff7880edf38e"

  url "https://github.com/OpenBoard-org/OpenBoard/releases/download/v#{version}/OpenBoard-#{version}.dmg",
      verified: "github.com/OpenBoard-org/OpenBoard/"
  name "OpenBoard"
  desc "Interactive whiteboard application"
  homepage "https://openboard.ch/index.en.html"

  livecheck do
    url :url
    strategy :github_latest
  end

  app "OpenBoard.app"

  zap trash: [
    "~/Library/Application Support/OpenBoard",
    "~/Movies/OpenBoard",
    "~/Music/OpenBoard",
    "~/Pictures/OpenBoard",
  ]
end


text:
layout: docs
title: useConst
id: class.Facebook.HackCodegen.CodegenFile.useConst
docid: class.Facebook.HackCodegen.CodegenFile.useConst
permalink: /docs/reference/class.Facebook.HackCodegen.CodegenFile.useConst/
---
# Facebook\\HackCodegen\\CodegenFile::useConst()

``` Hack
public function useConst(
  string $ns,
  ?string $as = NULL,
): this;
```

## Parameters

+ ` string $ns `
+ ` ?string $as = NULL `

## Returns

* ` this `


text:
require "csv"
require "logstash/namespace"
require "logstash/outputs/file"
require "logstash/json"

# CSV output.
#
# Write events to disk in CSV or other delimited format
# Based on the file output, many config values are shared
# Uses the Ruby csv library internally
class LogStash::Outputs::CSV < LogStash::Outputs::File

  config_name "csv"

  # The field names from the event that should be written to the CSV file.
  # Fields are written to the CSV in the same order as the array.
  # If a field does not exist on the event, an empty string will be written.
  # Supports field reference syntax eg: `fields => ["field1", "[nested][field]"]`.
  config :fields, :validate => :array, :required => true

  # Options for CSV output. This is passed directly to the Ruby stdlib to_csv function.
  # Full documentation is available on the http://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/index.html[Ruby CSV documentation page].
  # A typical use case would be to use alternative column or row seperators eg: `csv_options => {"col_sep" => "\t" "row_sep" => "\r\n"}` gives tab seperated data with windows line endings
  config :csv_options, :validate => :hash, :required => false, :default => Hash.new

  public
  def register
    super
    @csv_options = Hash[@csv_options.map{|(k, v)|[k.to_sym, v]}]
  end

  public
  def receive(event)

    path = event.sprintf(@path)
    fd = open(path)
    csv_values = @fields.map {|name| get_value(name, event)}
    fd.write(csv_values.to_csv(@csv_options))

    flush(fd)
    close_stale_files
  end #def receive

  private
  def get_value(name, event)
    val = event[name]
    val.is_a?(Hash) ? LogStash::Json.dump(val) : val
  end
end # class LogStash::Outputs::CSV


text:
#ifndef __CASS_TYPES_HPP_INCLUDED__
#define __CASS_TYPES_HPP_INCLUDED__

#include "cassandra.h"

namespace cass {

struct CassNull { };

struct CassBytes {
  CassBytes(const cass_byte_t* data, size_t size)
    : data(data), size(size) { }
  const cass_byte_t* data;
  size_t size;
};

struct CassString {
  CassString(const char* data, size_t length)
    : data(data), length(length) { }
  const char* data;
  size_t length;
};

struct CassDecimal {
  CassDecimal(const cass_byte_t* varint,
              size_t varint_size,
              int scale)
    : varint(varint)
    , varint_size(varint_size)
    , scale(scale) { }
  const cass_byte_t* varint;
  size_t varint_size;
  cass_int32_t scale;
};

} // namespace cass

#endif


text:
package za.co.praxis.helpdesk.escalation.domain;
// Generated Oct 21, 2013 9:18:53 AM by Hibernate Tools 3.4.0.CR1

import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * SpaceSequence generated by hbm2java
 */
@Entity
@Table(name = "space_sequence")//, schema = "dbo", catalog = "jtrac_test_db")
public class SpaceSequence implements java.io.Serializable {

	private BigDecimal id;
	private BigDecimal nextSeqNum;

	public SpaceSequence() {
	}

	public SpaceSequence(BigDecimal id) {
		this.id = id;
	}

	public SpaceSequence(BigDecimal id, BigDecimal nextSeqNum) {
		this.id = id;
		this.nextSeqNum = nextSeqNum;
	}

	@Id
	@Column(name = "id", unique = true, nullable = false, scale = 0)
	public BigDecimal getId() {
		return this.id;
	}

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

	@Column(name = "next_seq_num", scale = 0)
	public BigDecimal getNextSeqNum() {
		return this.nextSeqNum;
	}

	public void setNextSeqNum(BigDecimal nextSeqNum) {
		this.nextSeqNum = nextSeqNum;
	}

}


text:
package com.iotake.suller.sullerj.binder.value;

import java.lang.reflect.Field;
import java.math.BigDecimal;

public class BigDecimalValueConverterFactory extends
    AbstractValueConverterFactory {

  public static class BigDecimalValueConverter extends
      AbstractSingleSlotValueConverter {

    public BigDecimalValueConverter(Class<?> targetType,
        Class<?> documentClass, Field field, String path) {
      super(BigDecimal.class, targetType, documentClass, field, path);
    }

    public Class<?> getSlotType() {
      return String.class;
    }

    public Object toDocumentValue(Object beanValue) {
      if (beanValue == null) {
        return null;
      }
      checkBeanValueType(beanValue);
      return beanValue.toString();

    }

    public Object toBeanValue(Object documentValue) {
      if (documentValue == null) {
        return null;
      }
      checkDocumentValueType(documentValue, getSlot());
      try {
        return new BigDecimal((String) documentValue);
      } catch (NumberFormatException e) {
        throw reportInvalidDocumentValue(documentValue, getSlot(),
            "Invalid BigInteger string format.", e);
      }
    }
  }

  public BigDecimalValueConverterFactory() {
    super(BigDecimal.class);
  }

  protected ValueConverter doCreate(Class<?> targetType,
      Class<?> documentClass, Field field, String slotName,
      String slotNameSeparator) {
    return new BigDecimalValueConverter(targetType, documentClass, field,
        slotName);
  }
}


text:
#pragma once
#include <aws/pinpoint-email/PinpointEmail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace PinpointEmail
{
namespace Model
{

  /**
   *
An object that represents the content of the email, and optionally a
   * character set specification.

See Also:
   AWS
   * API Reference

   */
  class AWS_PINPOINTEMAIL_API Content
  {
  public:
    Content();
    Content(Aws::Utils::Json::JsonView jsonValue);
    Content& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The content of the message itself.

     */
    inline const Aws::String& GetData() const{ return m_data; }

    /**
     *
The content of the message itself.

     */
    inline bool DataHasBeenSet() const { return m_dataHasBeenSet; }

    /**
     *
The content of the message itself.

     */
    inline void SetData(const Aws::String& value) { m_dataHasBeenSet = true; m_data = value; }

    /**
     *
The content of the message itself.

     */
    inline void SetData(Aws::String&& value) { m_dataHasBeenSet = true; m_data = std::move(value); }

    /**
     *
The content of the message itself.

     */
    inline void SetData(const char* value) { m_dataHasBeenSet = true; m_data.assign(value); }

    /**
     *
The content of the message itself.

     */
    inline Content& WithData(const Aws::String& value) { SetData(value); return *this;}

    /**
     *
The content of the message itself.

     */
    inline Content& WithData(Aws::String&& value) { SetData(std::move(value)); return *this;}

    /**
     *
The content of the message itself.

     */
    inline Content& WithData(const char* value) { SetData(value); return *this;}

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline const Aws::String& GetCharset() const{ return m_charset; }

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline bool CharsetHasBeenSet() const { return m_charsetHasBeenSet; }

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline void SetCharset(const Aws::String& value) { m_charsetHasBeenSet = true; m_charset = value; }

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline void SetCharset(Aws::String&& value) { m_charsetHasBeenSet = true; m_charset = std::move(value); }

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline void SetCharset(const char* value) { m_charsetHasBeenSet = true; m_charset.assign(value); }

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline Content& WithCharset(const Aws::String& value) { SetCharset(value); return *this;}

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline Content& WithCharset(Aws::String&& value) { SetCharset(std::move(value)); return *this;}

    /**
     *
The character set for the content. Because of the constraints of the SMTP
     * protocol, Amazon Pinpoint uses 7-bit ASCII by default. If the text includes
     * characters outside of the ASCII range, you have to specify a character set. For
     * example, you could specify UTF-8, ISO-8859-1, or
     * Shift_JIS.

     */
    inline Content& WithCharset(const char* value) { SetCharset(value); return *this;}

  private:

    Aws::String m_data;
    bool m_dataHasBeenSet;

    Aws::String m_charset;
    bool m_charsetHasBeenSet;
  };

} // namespace Model
} // namespace PinpointEmail
} // namespace Aws


text:
// +build linux

package util

import (
	"errors"
	"strings"
)

// FindMultipathDeviceForDevice given a device name like /dev/sdx, find the devicemapper parent
func (handler *deviceHandler) FindMultipathDeviceForDevice(device string) string {
	io := handler.get_io
	disk, err := findDeviceForPath(device, io)
	if err != nil {
		return ""
	}
	sysPath := "/sys/block/"
	if dirs, err := io.ReadDir(sysPath); err == nil {
		for _, f := range dirs {
			name := f.Name()
			if strings.HasPrefix(name, "dm-") {
				if _, err1 := io.Lstat(sysPath + name + "/slaves/" + disk); err1 == nil {
					return "/dev/" + name
				}
			}
		}
	}
	return ""
}

// findDeviceForPath Find the underlaying disk for a linked path such as /dev/disk/by-path/XXXX or /dev/mapper/XXXX
// will return sdX or hdX etc, if /dev/sdX is passed in then sdX will be returned
func findDeviceForPath(path string, io IoUtil) (string, error) {
	devicePath, err := io.EvalSymlinks(path)
	if err != nil {
		return "", err
	}
	// if path /dev/hdX split into "", "dev", "hdX" then we will
	// return just the last part
	parts := strings.Split(devicePath, "/")
	if len(parts) == 3 && strings.HasPrefix(parts[1], "dev") {
		return parts[2], nil
	}
	return "", errors.New("Illegal path for device " + devicePath)
}


text:
require 'rails_helper'

RSpec.describe 'bill_requests', type: :system do

  let!(:school)                { create(:school) }
  let!(:dcc_meter)             { create(:electricity_meter, school: school, dcc_meter: true, consent_granted: false) }

  let!(:admin)                 { create(:admin) }

  before(:each) do
    login_as admin
  end

  context 'with pending meter review' do

    it 'should provide navigation' do
      visit root_path
      click_on 'Admin'
      click_on 'Meter Reviews'
      expect(page).to have_link("Request bill", href: new_admin_school_bill_request_path(school) )
    end
  end

  context 'requesting a bill' do

    context 'with no users' do

      before(:each) do
        visit new_admin_school_bill_request_path(school)
      end

      it 'should say there are no users' do
        expect(page).to have_text("The school has no staff or admin users")
      end

      it 'should link to add a user' do
        expect(page).to have_link("Add user", href: school_users_path(school))
      end
    end

    context 'with users' do
      let!(:school_admin)          { create(:school_admin, school: school)}
      let!(:staff)                 { create(:staff, school: school)}

      before(:each) do
        visit new_admin_school_bill_request_path(school)
      end

      it 'should display user name and role' do
        expect(page).to have_text(staff.name)
        expect(page).to have_text(staff.staff_role.title)
        expect(page).to have_text(school_admin.name)
        expect(page).to have_text(school_admin.staff_role.title)
      end

      it 'should link to manage users' do
        expect(page).to have_link("Manage users", href: school_users_path(school))
      end

      context 'when invalid form is submitted' do
        it 'should display an error' do
          click_on 'Request bill'
          expect(page.has_text?("You must select at least one user")).to be true
          expect(ActionMailer::Base.deliveries.count).to be 0
        end
      end

      context 'when valid form is submitted' do
        before(:each) do
          find(:css, "#bill_request_user_ids_#{school_admin.id}").set(true)
          click_on 'Request bill'
        end

        it 'should confirm email has been sent' do
          expect(page.has_text?("Bill has been requested")).to be true
        end

        it 'should send the email' do
          expect(ActionMailer::Base.deliveries.count).to be 1
        end
      end

    end

  end
end


text:
from importlib import import_module

from django.core.exceptions import ImproperlyConfigured
from django.urls import (
    LocaleRegexURLResolver, RegexURLPattern, RegexURLResolver,
)
from django.views import defaults

__all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include', 'url']

handler400 = defaults.bad_request
handler403 = defaults.permission_denied
handler404 = defaults.page_not_found
handler500 = defaults.server_error

def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # callable returning a namespace hint
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    'Cannot override the namespace for a dynamic module that '
                    'provides a namespace.'
                )
            raise ImproperlyConfigured(
                'Passing a %d-tuple to django.conf.urls.include() is not supported. '
                'Pass a 2-tuple containing the list of patterns and app_name, '
                'and provide the namespace argument to include() instead.' % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace
        urlconf_module = arg

    if isinstance(urlconf_module, str):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
    app_name = getattr(urlconf_module, 'app_name', app_name)
    if namespace and not app_name:
        raise ImproperlyConfigured(
            'Specifying a namespace in django.conf.urls.include() without '
            'providing an app_name is not supported. Set the app_name attribute '
            'in the included module, or pass a 2-tuple containing the list of '
            'patterns and app_name instead.',
        )

    namespace = namespace or app_name

    # Make sure we can iterate through the patterns (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            # Test if the LocaleRegexURLResolver is used within the include;
            # this should throw an error since this is not allowed!
            if isinstance(url_pattern, LocaleRegexURLResolver):
                raise ImproperlyConfigured(
                    'Using i18n_patterns in an included URLconf is not allowed.')

    return (urlconf_module, app_name, namespace)

def url(regex, view, kwargs=None, name=None):
    if isinstance(view, (list, tuple)):
        # For include(...) processing.
        urlconf_module, app_name, namespace = view
        return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace)
    elif callable(view):
        return RegexURLPattern(regex, view, kwargs, name)
    else:
        raise TypeError('view must be a callable or a list/tuple in the case of include().')


text:
@interface UIView (Resizing)

- (void)resizeToFit;

@end


text:
__version__ = '2.0.0'

def get_account(using=None):
    from django.conf import settings
    accounts = settings.SMSGATEWAY_ACCOUNTS
    if using is not None:
        return accounts[using]
    else:
        return accounts[accounts['__default__']]

def send(to, msg, signature, using=None, reliable=False):
    """
    Send an SMS message immediately.

    *   'to' is a semicolon separated list of phone numbers with an international
        prefix (+32... etc).
    *   'msg' is the message itself as a unicode object (max 160 characters).
    *   'signature' is where the message comes from. Depends on the backend in use.
    *   'using' is an optional parameter where you can specify a specific account
        to send messages from.
    """
    # Don't send empty smses
    if not msg:
        return

    from smsgateway.backends import get_backend
    from smsgateway.sms import SMSRequest
    account_dict = get_account(using)
    backend = get_backend(account_dict['backend'])
    sms_request = SMSRequest(to, msg, signature, reliable=reliable)
    return backend.send(sms_request, account_dict)

def send_queued(to, msg, signature, using=None, reliable=False, priority=None):
    """
    Place SMS message in queue to be sent.
    """
    # Don't send empty smses
    if not msg:
        return

    from smsgateway.models import QueuedSMS
    queued_sms = QueuedSMS(
        to=to,
        content=msg,
        signature=signature,
        using=using if using is not None else '__none__',
        reliable=reliable
    )
    if priority is not None:
        queued_sms.priority = priority
    queued_sms.save()


text:
from __future__ import unicode_literals

from django.db import migrations
import sentry.db.models.fields.bounded

class Migration(migrations.Migration):
    # This flag is used to mark that a migration shouldn't be automatically run in
    # production. We set this to True for operations that we think are risky and want
    # someone from ops to run manually and monitor.
    # General advice is that if in doubt, mark your migration as `is_dangerous`.
    # Some things you should always mark as dangerous:
    # - Large data migrations. Typically we want these to be run manually by ops so that
    #   they can be monitored. Since data migrations will now hold a transaction open
    #   this is even more important.
    # - Adding columns to highly active tables, even ones that are NULL.
    is_dangerous = False

    # This flag is used to decide whether to run this migration in a transaction or not.
    # By default we prefer to run in a transaction, but for migrations where you want
    # to `CREATE INDEX CONCURRENTLY` this needs to be set to False. Typically you'll
    # want to create an index concurrently when adding one to an existing table.
    atomic = True

    dependencies = [("sentry", "0049_auto_20200304_0254")]

    operations = [
        migrations.AlterField(
            model_name="exporteddata",
            name="query_type",
            field=sentry.db.models.fields.bounded.BoundedPositiveIntegerField(
                choices=[(0, "Issues-by-Tag"), (1, "Discover")]
            ),
        )
    ]


text:
<?php
namespace Ratchet\Component\WebSocket\Version\RFC6455;
use Ratchet\Component\WebSocket\Version\FrameInterface;

class Frame implements FrameInterface {
    /**
     * The contents of the frame
     * @var string
     */
    protected $_data = '';

    /**
     * Number of bytes received from the frame
     * @var int
     */
    public $_bytes_rec = 0;

    /**
     * Number of bytes in the payload (as per framing protocol)
     * @var int
     */
    protected $_pay_len_def = -1;

    /**
     * Bit 9-15
     * @var int
     */
    protected $_pay_check = -1;

    public function isCoalesced() {
        try {
            $payload_length = $this->getPayloadLength();
            $payload_start  = $this->getPayloadStartingByte();
        } catch (\UnderflowException $e) {
            return false;
        }

        return $payload_length + $payload_start === $this->_bytes_rec;
    }

    public function addBuffer($buf) {
        $buf = (string)$buf;

        $this->_data      .= $buf;
        $this->_bytes_rec += strlen($buf);
    }

    public function isFinal() {
        if ($this->_bytes_rec < 1) {
            throw new \UnderflowException('Not enough bytes received to determine if this is the final frame in message');
        }

        $fbb = sprintf('%08b', ord($this->_data[0]));
        return (boolean)(int)$fbb[0];
    }

    public function isMasked() {
        if ($this->_bytes_rec < 2) {
            throw new \UnderflowException("Not enough bytes received ({$this->_bytes_rec}) to determine if mask is set");
        }

        return (boolean)bindec(substr(sprintf('%08b', ord($this->_data[1])), 0, 1));
    }

    public function getOpcode() {
        if ($this->_bytes_rec < 1) {
            throw new \UnderflowException('Not enough bytes received to determine opcode');
        }

        return bindec(substr(sprintf('%08b', ord($this->_data[0])), 4, 4));
    }

    /**
     * Gets the decimal value of bits 9 (10th) through 15 inclusive
     * @return int
     * @throws UnderflowException If the buffer doesn't have enough data to determine this
     */
    protected function getFirstPayloadVal() {
        if ($this->_bytes_rec < 2) {
            throw new \UnderflowException('Not enough bytes received');
        }

        return ord($this->_data[1]) & 127;
    }

    /**
     * @return int (7|23|71) Number of bits defined for the payload length in the fame
     * @throws UnderflowException
     */
    protected function getNumPayloadBits() {
        if ($this->_bytes_rec < 2) {
            throw new \UnderflowException('Not enough bytes received');
        }

        // By default 7 bits are used to describe the payload length
        // These are bits 9 (10th) through 15 inclusive
        $bits = 7;

        // Get the value of those bits
        $check = $this->getFirstPayloadVal();

        // If the value is 126 the 7 bits plus the next 16 are used to describe the payload length
        if ($check >= 126) {
            $bits += 16;
        }

        // If the value of the initial payload length are is 127 an additional 48 bits are used to describe length
        // Note: The documentation specifies the length is to be 63 bits, but I think that's a type and is 64 (16+48)
        if ($check === 127) {
            $bits += 48;
        }

        if (!in_array($bits, array(7, 23, 71))) {
            throw new \UnexpectedValueException("Malformed frame, invalid payload length provided");
        }

        return $bits;
    }

    /**
     * This just returns the number of bytes used in the frame to describe the payload length (as opposed to # of bits)
     * @see getNumPayloadBits
     */
    protected function getNumPayloadBytes() {
        return (1 + $this->getNumPayloadBits()) / 8;
    }

    public function getPayloadLength() {
        if ($this->_pay_len_def !== -1) {
            return $this->_pay_len_def;
        }

        $length_check = $this->getFirstPayloadVal();

        if ($length_check <= 125) {
            $this->_pay_len_def = $length_check;
            return $this->getPayloadLength();
        }

        $byte_length = $this->getNumPayloadBytes();
        if ($this->_bytes_rec < 1 + $byte_length) {
            throw new \UnderflowException('Not enough data buffered to determine payload length');
        }

        $strings = array();
        for ($i = 2; $i < $byte_length + 1; $i++) {
            $strings[] = ord($this->_data[$i]);
        }

        $this->_pay_len_def = bindec(vsprintf(str_repeat('%08b', $byte_length - 1), $strings));
        return $this->getPayloadLength();
    }

    public function getMaskingKey() {
        if (!$this->isMasked()) {
            return '';
        }

        $length = 4;
        $start  = 1 + $this->getNumPayloadBytes();

        if ($this->_bytes_rec < $start + $length) {
            throw new \UnderflowException('Not enough data buffered to calculate the masking key');
        }

        return substr($this->_data, $start, $length);
    }

    public function getPayloadStartingByte() {
        return 1 + $this->getNumPayloadBytes() + strlen($this->getMaskingKey());
    }

    public function getPayload() {
        if (!$this->isCoalesced()) {
            throw new \UnderflowException('Can not return partial message');
        }

        $payload = '';
        $length  = $this->getPayloadLength();

        if ($this->isMasked()) {
            $mask  = $this->getMaskingKey();
            $start = $this->getPayloadStartingByte();

            for ($i = 0; $i < $length; $i++) {
                $payload .= $this->_data[$i + $start] ^ $mask[$i % 4];
            }
        } else {
            $payload = substr($this->_data, $start, $this->getPayloadLength());
        }

        if (strlen($payload) !== $length) {
            // Is this possible?  isCoalesced() math _should_ ensure if there is mal-formed data, it would return false
            throw new \UnexpectedValueException('Payload length does not match expected length');
        }

        return $payload;
    }
}


text:
// cassandra-sharp - high performance .NET driver for Apache Cassandra
// Copyright (c) 2011-2013 Pierre Chalamet
//
// 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.

namespace CassandraSharp.Enlightenment
{
    using CassandraSharp.CQLPropertyBag;
    using CassandraSharp.Extensibility;

    internal sealed class PropertyBagDataMapperFactory : IDataMapperFactory
    {
        public IDataMapper Create<T>(object dataSource)
        {
            PropertyBag propertyBag = (PropertyBag) dataSource;
            return new DataMapper(propertyBag);
        }
    }
}


text:
#ifndef __included_grenade_h
#define __included_grenade_h

#include <crisscross/stopwatch.h>

#include "Game/player.h"
#include "Game/weapon.h"

class Grenade : public Weapon
{
protected:
    CrissCross::System::Stopwatch m_smokeTick;
    double m_dest;
    double m_dist;
    double m_speed;

public:
    Grenade ( Player *_player, int _lX, int _lY, int _cX, int _cY );
    virtual ~Grenade();

    virtual void Update();
    virtual void Render();
};

#endif


text:
var regex = require('glsl-version-regex')

module.exports = function glslExtractVersion (tokens) {
  for (var i = 0; i < tokens.length; i++) {
    var token = tokens[i]
    if (token.type === 'preprocessor') {
      var match = regex.exec(token.data)
      if (match) {
        return match[1].replace(/\s\s+/g, ' ')
      }
    }
  }
  return null
}


text:
@protocol JavaLangIterable;

#define ComGoogleCommonCollectOrdering_RESTRICT 1
#define ComGoogleCommonCollectOrdering_INCLUDE 1
#include "com/google/common/collect/Ordering.h"

#define JavaIoSerializable_RESTRICT 1
#define JavaIoSerializable_INCLUDE 1
#include "java/io/Serializable.h"

#define ComGoogleCommonCollectLexicographicalOrdering_serialVersionUID 0LL

@interface ComGoogleCommonCollectLexicographicalOrdering : ComGoogleCommonCollectOrdering < JavaIoSerializable > {
 @public
  ComGoogleCommonCollectOrdering *elementOrder_;
}

- (instancetype)initWithComGoogleCommonCollectOrdering:(ComGoogleCommonCollectOrdering *)elementOrder;

- (jint)compareWithId:(id<JavaLangIterable>)leftIterable
               withId:(id<JavaLangIterable>)rightIterable;

- (jboolean)isEqual:(id)object;

- (NSUInteger)hash;

- (NSString *)description;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonCollectLexicographicalOrdering)

J2OBJC_FIELD_SETTER(ComGoogleCommonCollectLexicographicalOrdering, elementOrder_, ComGoogleCommonCollectOrdering *)

CF_EXTERN_C_BEGIN

J2OBJC_STATIC_FIELD_GETTER(ComGoogleCommonCollectLexicographicalOrdering, serialVersionUID, jlong)
CF_EXTERN_C_END
#endif

J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonCollectLexicographicalOrdering)


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

<title>Results.Chunks (playframework)</title>
<meta name="date" content="2013-04-02">
<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 Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

play.mvc

Class Results.Chunks<A>

java.lang.Object

play.mvc.Results.Chunks<A>

Direct Known Subclasses:

Comet, Results.ByteChunks, Results.StringChunks

Enclosing class:

Results

public abstract static class Results.Chunks<A>
extends java.lang.Object

A Chunked result.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
Results.Chunks.Out<A>

A Chunked stream.

Constructor Summary

Constructors

Constructor and Description

Results.Chunks(<any> w)

Method Summary

Methods

Modifier and Type
Method and Description

abstract void
onReady(Results.Chunks.Out<A> out)

Called when the Chunked stream is ready.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Results.Chunks

public Results.Chunks(<any> w)

Method Detail

onReady

public abstract void onReady(Results.Chunks.Out<A> out)

Called when the Chunked stream is ready.

Parameters:

out - The out stream.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module Brewmaster
  class Coordinator
    attr_accessor :configuration

    def initialize(configuration)
      self.configuration = configuration
    end

    def run
      if configuration.bootstrap?
        Brewmaster.bootstrap!
      else
        Brewmaster.setup_load_paths
      end

      run_brews
      run_casks
      run_rubies
    end

    def run_brews
      c = BrewCollection.new(configuration.brews)
      c.install_missing
      c.install_updates
    end

    def run_casks
      c = CaskCollection.new(configuration.casks)
      c.install_missing
    end

    def run_rubies
      c = RubyCollection.new(configuration.rubies)
      c.install_missing
    end
  end
end


text:
package com.streamsets.pipeline.api;

/**
 * If the execution of a pipeline throws an exception, all stages in the pipeline implementing this interface will
 * be notified via the {@link #errorNotification(Throwable)} method.
 */
public interface ErrorListener {

  /**
   * Invoked when the execution of a pipeline throws an exception.
   *
   * @param throwable the exception thrown by the pipeline.
   */
  void errorNotification(Throwable throwable);

}


text:
import { actions, createKernelRef } from "@nteract/core";
import { DesktopCommand, ReqContent, ReqKernelSpec } from "../types";
import { currentDocumentDirectory } from "../utils/directories";

export const KillKernel: DesktopCommand<ReqContent> = {
  name: "KillKernel",
  props: {
    contentRef: "required",
  },
  makeAction: actions.killKernel.with({ restarting: false }),
};

export const InterruptKernel: DesktopCommand<ReqContent> = {
  name: "InterruptKernel",
  props: {
    contentRef: "required",
  },
  makeAction: actions.interruptKernel,
};

export const RestartKernel: DesktopCommand<ReqContent> = {
  name: "RestartKernel",
  props: {
    contentRef: "required",
  },
  makeAction: actions.restartKernel.with({ outputHandling: "None" }),
};

export const RestartAndClearAll: DesktopCommand<ReqContent> = {
  name: "RestartAndClearAll",
  props: {
    contentRef: "required",
  },
  makeAction: actions.restartKernel.with({ outputHandling: "Clear All" }),
};

export const RestartAndRunAll: DesktopCommand<ReqContent> = {
  name: "RestartAndRunAll",
  props: {
    contentRef: "required",
  },
  makeAction: actions.restartKernel.with({ outputHandling: "Run All" }),
};

export const NewKernel: DesktopCommand<ReqContent & ReqKernelSpec> = {
  name: "NewKernel",
  props: {
    contentRef: "required",
    kernelSpec: "required",
  },
  *makeActions(store, props) {
    yield actions.launchKernel({
      cwd: currentDocumentDirectory(store, props.contentRef),
      kernelRef: createKernelRef(),
      selectNextKernel: true,
      ...props,
    });
  },
};


text:
<?php

namespace Propel\Tests\Runtime\TypeTests;

class DummyObjectClass
{
    public $propPublic;

    protected $propProtected;

    private $propPrivate;

    /**
     * @param mixed $propPrivate
     *
     * @return void
     */
    public function setPropPrivate($propPrivate)
    {
        $this->propPrivate = $propPrivate;
    }

    /**
     * @return mixed
     */
    public function getPropPrivate()
    {
        return $this->propPrivate;
    }

    /**
     * @param mixed $propProtected
     *
     * @return void
     */
    public function setPropProtected($propProtected)
    {
        $this->propProtected = $propProtected;
    }

    /**
     * @return mixed
     */
    public function getPropProtected()
    {
        return $this->propProtected;
    }

    /**
     * @param mixed $propPublic
     *
     * @return void
     */
    public function setPropPublic($propPublic)
    {
        $this->propPublic = $propPublic;
    }

    /**
     * @return mixed
     */
    public function getPropPublic()
    {
        return $this->propPublic;
    }
}


text:
namespace map {

class EditorGridSystem : public engine::System
{
public:
    DEFINE_SYSTEM_BASE( EditorGridSystem )
    EditorGridSystem();
    ~EditorGridSystem();
    static Opt<EditorGridSystem> Get();
    IGrid& GetGrid();
protected:
    virtual void Init();
    virtual void Update( double DeltaTime );
private:
    Scene& mScene;
    GridRepo& mGridRepo;
    int32_t mGridId;
    boost::ptr_vector<ModelValue> mEditorModels;
    void GridChanged( std::string const& grid );
    AutoReg mOnWorldMouseMove;
    void OnWorldMouseMoveEvent( const WorldMouseMoveEvent& Event );
};

} // namespace map

#endif//INCLUDED_MAP_EDITOR_GRID_SYSTEM_H

//command:  "classgenerator.exe" -g "system" -c "editor_grid_system" -n "map"


text:
''' This package is for mass texting in wechat mp
 1. What can we send?
    - IMAGE, VOICE, VIDEO, TEXT, NEWS, CARD

 2. How to send them?
    - we use send_some / send_all method
        `send_some(targetIdList, msgType, mediaId, additionalDict)`
    - for msg like text and card, just pass content as msgId
    - for files like image, voice, video, we need to upload them first
        `upload(fileType, openedFile, additionalDict, permanent)`
    - for news, you need to form them first and upload to get msgId
        `create_news(newsDict, permanent)`
      for images used in news, you need to turn them into url first
        `get_image_url(openedFile)`
    - SPECIAL WARNING: video is a little bit **STRANGE**
      when uploading or sending, you need to pass additionalDict to method
        `{"title" :VIDEO_TITLE, "introduction" :INTRODUCTION}`

 3. I alse listed API list for you:
   - SENDING
     send_some
     send_all
     preview
   - MSG MANAGING
     delete
     get
   - TEMP MATERIAL MANAGING
     upload
     download
   - PERMENENT MATERIAL MANAGING
     get_material
     delete_material
     get_materialcount
     batchget_material
   - FORM NEWS
     create_news
     update_news
     get_image_url
'''
import logging, json, os, mimetypes, io, re

from ..requests import requests
from itchatmp.utils import retry, encode_send_dict
from itchatmp.config import SERVER_URL
from itchatmp.content import (
    IMAGE, VOICE, VIDEO, THUMB, TEXT, NEWS, CARD)
from itchatmp.returnvalues import ReturnValue

logger = logging.getLogger('itchatmp')

def send_some(msgType, mediaId, additionalDict={},
        targetIdList=[], partyIdList=[], tagIdList=[],
        agentId=None, accessToken=None):
    msgDict = __form_send_dict(msgType, mediaId, additionalDict)
    if not msgDict: return msgDict
    if not isinstance(targetIdList, list) or len(targetIdList) < 2:
        return ReturnValue({'errcode': 40130})
    msgDict['touser'] = targetIdList
    r = requests.post('%s/cgi-bin/message/mass/send?access_token=%s' %
        (SERVER_URL, accessToken), data=encode_send_dict(msgDict))
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def send_all(msgType, mediaId, additionalDict={},
        tagId=None, agentId=None, accessToken=None):
    msgDict = __form_send_dict(msgType, mediaId, additionalDict)
    if not msgDict: return msgDict
    if tagId is None:
        msgDict['filter'] = {'is_to_all': True, 'tag_id': 0}
    else:
        msgDict['filter'] = {'is_to_all': False, 'tag_id': tagId}
    r = requests.post('%s/cgi-bin/message/mass/sendall?access_token=%s' %
        (SERVER_URL, accessToken), data=encode_send_dict(msgDict))
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'media_id' in result: result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def preview(msgType, mediaId, additionalDict={},
        toUserId=None, toWxAccount=None, accessToken=None):
    msgDict = __form_send_dict(msgType, mediaId, additionalDict)
    if not msgDict: return msgDict
    if (toUserId or toWxAccount) is None:
        return ReturnValue({'errcode': -10003})
    else:
        if toUserId is not None: msgDict['touser'] = toUserId
        if toWxAccount is not None: msgDict['towxname'] = toWxAccount
    r = requests.post('%s/cgi-bin/message/mass/preview?access_token=%s' %
        (SERVER_URL, accessToken), data=encode_send_dict(msgDict))
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def form_video_id(mediaId, additionalDict, accessToken=None):
    ''' in theory video needs another method to get media_id for sending '''
    additionalDict['media_id'] = mediaId
    additionalDict['description'] = additionalDict['introduction']
    # requests.packages.urllib3.disable_warnings()
    url = 'https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo' \
        '?access_token=%s' % accessToken
    r = requests.post(url, data=encode_send_dict(additionalDict))
        # verify=False).json()
    # I don't know why this is a fake ssl
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'media_id' in result:
            result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def __form_send_dict(msgType, mediaId, additionalDict):
    if not msgType in (IMAGE, VOICE, VIDEO, TEXT, NEWS, CARD):
        return ReturnValue({'errcode': 40004,})
    elif msgType == VIDEO:
        mediaId = form_video_id(mediaId, additionalDict)['media_id']
        if not mediaId: return mediaId
    return {
        NEWS: {'mpnews':{'media_id': mediaId}, 'msgtype': 'mpnews'},
        TEXT: {'text': {'content': mediaId}, 'msgtype': 'text'},
        VOICE: {'voice': {'media_id': mediaId}, 'msgtype': 'voice'},
        IMAGE: {'image': {'media_id': mediaId}, 'msgtype': 'image'},
        VIDEO: {'mpvideo':{'media_id': mediaId,
            'title': additionalDict.get('title', ''),
            'description': additionalDict.get('introduction', '')},
            'msgtype': 'mpvideo'},
        CARD: {'wxcard': {'card_id': mediaId}, 'msgtype': 'wxcard'},
        }[msgType]

def delete(msgId, accessToken=None):
    r = requests.post('%s/cgi-bin/message/mass/delete?access_token=%s' %
        (SERVER_URL, accessToken), data={'msg_id': msgId})
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def get(msgId, accessToken=None):
    r = requests.post('%s/cgi-bin/message/mass/get?access_token=%s' %
        (SERVER_URL, accessToken), data={'msg_id': int(msgId)})
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def upload(fileType, fileDir, additionalDict={}, permanent=False, accessToken=None):
    if additionalDict: # format additionalDict
        for key in ('description',):
            if key in additionalDict and isinstance(additionalDict[key], dict):
                for k, v in additionalDict[key].items():
                    if k not in additionalDict:
                        additionalDict[k] = v
        additionalDict = {k.lower().replace('_', ''): v
            for k, v in additionalDict.items()}
        if 'introduction' in additionalDict:
            additionalDict['description'] = additionalDict['introduction']
    if not fileType in (IMAGE, VOICE, VIDEO, THUMB):
        return ReturnValue({'errcode': 40004,})
    elif fileType == VIDEO and permanent and not ('title' in additionalDict
            and 'description' in additionalDict):
        return ReturnValue({'errcode': -10003, 'errmsg':
            'additionalDict for type VIDEO should be: ' +
            "{'Title' : 'title', 'Description' :'des'}"})
    try:
        with open(fileDir, 'rb') as f:
            file_ = f.read()
    except:
        return ReturnValue({'errcode': -10004,})
    fileName = 'file' + os.path.splitext(fileDir)[1]
    if hasattr(fileName, 'decode'):
        fileName = fileName.decode('utf8', 'replace')
    fileMime = mimetypes.guess_type(fileName)[0] or 'application/octet-stream'
    if permanent:
        url = '%s/cgi-bin/material/add_material?access_token=%s&type=%s'
    else:
        url = '%s/cgi-bin/media/upload?access_token=%s&type=%s'
    files = {'media': (fileName, file_, fileMime), }
    if fileType == VIDEO and permanent:
        files['description'] = (None, encode_send_dict({
            'title': additionalDict['title'],
            'introduction': additionalDict['description'], }
            ), 'application/json')
    r = requests.post(url % (SERVER_URL, accessToken, fileType),
        files=files)
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'media_id' in result:
            result['errcode'] = 0
        else:
            for k in result:
                if 'media_id' in k:
                    result['media_id'] = result[k]
                    result['errcode'] = 0
                    break
        return result
    r._wrap_result = _wrap_result
    return r

def download(mediaId, accessToken=None):
    r = requests.get('%s/cgi-bin/media/get?access_token=%s&media_id=%s' %
        (SERVER_URL, accessToken, mediaId), stream=True)
    def _wrap_result(result):
        if 'text/plain' in result.headers['Content-Type']:
            j = result.json()
            if 'down_url' in j or 'news_item' in j:
                j['errcode'] = 0
            return ReturnValue(j)
        else:
            tempStorage = io.BytesIO()
            for block in result.iter_content(1024):
                tempStorage.write(block)
            basicDict = {'File': tempStorage, 'errcode': 0}
            if 'Content-disposition' in result.headers:
                match = re.search('filename="(.*?)"', result.headers['Content-disposition'])
                if match:
                    basicDict['FileName'] = match.group(1)
            if 'Content-Type' in result.headers:
                basicDict['ContentType'] = result.headers['Content-Type']
            if 'Content-Length' in result.headers:
                basicDict['ContentLength'] = result.headers['Content-Length']
            return ReturnValue(basicDict)
    r._wrap_result = _wrap_result
    return r

def get_material(mediaId, accessToken=None):
    data = {'media_id': mediaId}
    data = encode_send_dict(data)
    if data is None: return ReturnValue({'errcode': -10001})
    r = requests.post('%s/cgi-bin/material/get_material?access_token=%s' %
        (SERVER_URL, accessToken), data=data, stream=True)
    def _wrap_result(result):
        if 'text/plain' in result.headers['Content-Type']:
            j = result.json()
            if 'down_url' in j or 'news_item' in j:
                j['errcode'] = 0
            return ReturnValue(j)
        else:
            tempStorage = io.BytesIO()
            for block in result.iter_content(1024):
                tempStorage.write(block)
            basicDict = {'File': tempStorage, 'errcode': 0}
            if 'Content-disposition' in result.headers:
                match = re.search('filename="(.*?)"', result.headers['Content-disposition'])
                if match:
                    basicDict['FileName'] = match.group(1)
            if 'Content-Type' in result.headers:
                basicDict['ContentType'] = result.headers['Content-Type']
            if 'Content-Length' in result.headers:
                basicDict['ContentLength'] = result.headers['Content-Length']
            return ReturnValue(basicDict)
    r._wrap_result = _wrap_result
    return r

def delete_material(mediaId, accessToken=None):
    r = requests.post('%s/cgi-bin/material/del_material?access_token=%s' %
        (SERVER_URL, accessToken), data={'msg_id': mediaId})
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def get_material_count(accessToken=None):
    r = requests.get('%s/cgi-bin/material/get_materialcount?access_token=%s'
        % (SERVER_URL, accessToken))
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'voice_count' in result:
            result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def batchget_material(fileType, offset=0, count=20, accessToken=None):
    if not fileType in (IMAGE, VOICE, VIDEO, THUMB):
        return ReturnValue({'errcode': 40004,})
    if 20 < count: count = 20
    data = {'type': fileType,
        'offset': offset,
        'count': count, }
    data = encode_send_dict(data)
    if data is None: return ReturnValue({'errcode': -10001})
    r = requests.post('%s/cgi-bin/material/batchget_material?access_token=%s'
        % (SERVER_URL, accessToken), data=data)
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'total_count' in result: result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def create_news(newsDict, permanent=False, accessToken=None):
    if permanent:
        url = '%s/cgi-bin/material/add_news?access_token=%s'
    else:
        url = '%s/cgi-bin/media/uploadnews?access_token=%s'
    r = requests.post(url % (SERVER_URL, accessToken),
        data=encode_send_dict(newsDict))
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'media_id' in result: result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def update_news(mediaId, newsDict, index=0, accessToken=None):
    data = {
        'media_id': mediaId,
        'index': index,
        'articles': newsDict, }
    data = encode_send_dict(data)
    if data is None: return ReturnValue({'errcode': -10001})
    r = requests.post('%s/cgi-bin/material/update_news?access_token=%s' %
        (SERVER_URL, accessToken), data=data)
    def _wrap_result(result):
        return ReturnValue(result.json())
    r._wrap_result = _wrap_result
    return r

def get_image_url(openedFile, accessToken=None):
    r = requests.post('%s/cgi-bin/media/uploadimg?access_token=%s' %
        (SERVER_URL, accessToken), files={'file': openedFile})
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'url' in result: result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r

def get_autoreply(accessToken=None):
    r = requests.post('%s/cgi-bin/get_current_autoreply_info?access_token=%s' %
        (SERVER_URL, accessToken))
    def _wrap_result(result):
        result = ReturnValue(result.json())
        if 'is_autoreply_open' in result:
            result['errcode'] = 0
        return result
    r._wrap_result = _wrap_result
    return r


text:
var options = {
    manager: require("../../../src/managers/master/holiday-manager"),
    model: require("dl-models").master.Holiday,
    util: require("../../data-util/master/holiday-data-util"),
    validator: require("dl-models").validator.master.holiday,
    createDuplicate: false,
    keys: []
};

var basicTest = require("../../basic-test-factory");
basicTest(options);


text:
package za.org.grassroot.core.domain.notification;

import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.broadcast.Broadcast;
import za.org.grassroot.core.domain.campaign.CampaignLog;
import za.org.grassroot.core.enums.DeliveryRoute;
import za.org.grassroot.core.enums.NotificationDetailedType;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("CAMPAIGN_BROADCAST")
public class CampaignBroadcastNotification extends BroadcastNotification {

    protected CampaignBroadcastNotification() {
        // for JPA
    }

    public CampaignBroadcastNotification(User destination, String message, Broadcast broadcast, DeliveryRoute deliveryChannel,
                                         CampaignLog campaignLog) {
        super(destination, message, deliveryChannel, campaignLog, broadcast);
        // todo : think about / through priority
    }

    @Override
    public NotificationDetailedType getNotificationDetailedType() {
        return NotificationDetailedType.CAMPAIGN_BROADCAST;
    }

}