text:
"""Utility functions for pylinac."""
import os
import os.path as osp
import struct
from collections.abc import Iterable
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Union, Sequence, Type, BinaryIO

import numpy as np
import pydicom

from .. import __version__

def convert_to_enum(value: Union[str, Enum, None], enum: Type[Enum]) -> Enum:
    """Convert a value to an enum representation from an enum value if needed"""
    if isinstance(value, enum):
        return value
    else:
        return enum(value)

@dataclass
class ResultBase:
    pylinac_version: str = field(init=False)  #:
    date_of_analysis: datetime = field(init=False)  #:

    def __post_init__(self):
        self.pylinac_version = __version__
        self.date_of_analysis = datetime.today()

def clear_data_files():
    """Delete all demo files, image classifiers, etc from the demo folder"""
    demo_folder = osp.join(osp.dirname(osp.dirname(__file__)), "demo_files")
    if osp.isdir(demo_folder):
        for file in os.listdir(demo_folder):
            full_file = osp.join(demo_folder, file)
            if osp.isfile(full_file):
                os.remove(full_file)
    print("Pylinac data files cleared.")

def assign2machine(source_file: str, machine_file: str):
    """Assign a DICOM RT Plan file to a specific machine. The source file is overwritten to contain
    the machine of the machine file.

    Parameters
    ----------
    source_file : str
        Path to the DICOM RTPlan file that contains the fields/plan desired
        (e.g. a Winston Lutz set of fields or Varian's default PF files).
    machine_file : str
        Path to a DICOM RTPlan file that has the desired machine. This is easily obtained from pushing a plan from the TPS
        for that specific machine. The file must contain at least one valid field.
    """
    dcm_source = pydicom.dcmread(source_file)
    dcm_machine = pydicom.dcmread(machine_file)
    for beam in dcm_source.BeamSequence:
        beam.TreatmentMachineName = dcm_machine.BeamSequence[0].TreatmentMachineName
    dcm_source.save_as(source_file)

def is_close(
    val: float, target: Union[float, Sequence], delta: float = 1
):
    """Return whether the value is near the target value(s).

    Parameters
    ----------
    val : number
        The value being compared against.
    target : number, iterable
        If a number, the values are simply evaluated.
        If a sequence, each target is compared to ``val``.
        If any values of ``target`` are close, the comparison is considered True.

    Returns
    -------
    bool
    """
    try:
        targets = (value for value in target)
    except (AttributeError, TypeError):
        targets = [target]
    for target in targets:
        if target - delta < val < target + delta:
            return True
    return False

def simple_round(number: float, decimals: int = 0) -> float:
    """Round a number to the given number of decimals. Fixes small floating number errors."""
    num = int(round(number * 10**decimals))
    num /= 10**decimals
    return num

def is_iterable(object) -> bool:
    """Determine if an object is iterable."""
    return isinstance(object, Iterable)

class Structure:
    """A simple structure that assigns the arguments to the object."""

    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

    def update(self, **kwargs):
        self.__dict__.update(**kwargs)

def decode_binary(
    file: BinaryIO,
    dtype: Union[Type[int], Type[float], Type[str]],
    num_values: int = 1,
    cursor_shift: int = 0,
) -> Union[int, float, str, np.ndarray]:
    """Read in a raw binary file and convert it to given data types.

    Parameters
    ----------
    file
        The open file object.
    dtype
        The expected data type to return. If int or float and num_values > 1, will return numpy array.
    num_values
        The expected number of dtype to return

        .. note:: This is not the same as the number of bytes.

    cursor_shift : int
        The number of bytes to move the cursor forward after decoding. This is used if there is a
        reserved section after the read-in segment.
    """
    f = file

    if dtype == str:  # if string
        output = f.read(num_values)
        if type(f) is not str:  # in py3 fc will be bytes
            output = output.decode()
        # strip the padding ("\x00")
        output = output.strip("\x00")
    elif dtype == int:
        ssize = struct.calcsize("i") * num_values
        output = np.asarray(struct.unpack("i" * num_values, f.read(ssize)))
        if len(output) == 1:
            output = int(output)
    elif dtype == float:
        ssize = struct.calcsize("f") * num_values
        output = np.asarray(struct.unpack("f" * num_values, f.read(ssize)))
        if len(output) == 1:
            output = float(output)
    else:
        raise TypeError(f"datatype '{dtype}' was not valid")

    # shift cursor if need be (e.g. if a reserved section follows)
    if cursor_shift:
        f.seek(cursor_shift, 1)
    return output


text:
/** Define GDOME */
GDOME = {};

/** Our exception data type */
Extension.load("gdome/GdomeException.js");
GDOME.exception = new GdomeException();

/** Gdome DOM Implementation */
GDOME.createDOMImplementation = function() {
	GDOME.exception.msg = "gdome_di_mkref";
	var di_pointer = CGDOME.call.gdome_di_mkref();
	if (di_pointer == 0) { throw GDOME.exception; }
	Extension.load("gdome/GdomeDOMImplementation.js");
	return new GdomeDOMImplementation(di_pointer);
}

/* EOF */

redpajama_set_name: RedPajamaGithub


text:
yum-erlang_solutions Cookbook
============
[![Build Status](https://travis-ci.org/chef-cookbooks/yum-erlang_solutions.svg?branch=master)](http://travis-ci.org/chef-cookbooks/yum-erlang_solutions)
[![Cookbook Version](https://img.shields.io/cookbook/v/yum-erlang_solutions.svg)](https://supermarket.chef.io/cookbooks/yum-erlang_solutions)

The yum-erlang_solutions cookbook takes over management of the default
repositoryids used by erlang_solutions. It allows attribute manipulation of
`erlang_solutions`.

Requirements
------------
#### Platforms
* RHEL/CentOS and derivatives
* Fedora

#### Chef
* Chef 11+

#### Cookbooks
* yum version 3.2.0 or higher

Attributes
----------
The following attributes are set by default

``` ruby
default['yum']['erlang_solutions']['baseurl'] = 'http://packages.erlang-solutions.com/rpm/centos/$releasever/$basearch'
default['yum']['erlang_solutions']['description'] = 'Centos $releasever - $basearch - Erlang Solutions'
default['yum']['erlang_solutions']['gpgkey'] = 'http://packages.erlang-solutions.com/debian/erlang_solutions.asc'
default['yum']['erlang_solutions']['enabled'] = true
```

Recipes
-------
* default - Walks through node attributes and feeds a yum_resource
  parameters. The following is an example a resource generated by the
  recipe during compilation.

```ruby
  yum_repository 'erlang_solutions' do
    baseurl 'http://packages.erlang-solutions.com/rpm/centos/$releasever/$basearch'
    description 'Centos $releasever - $basearch - Erlang Solutions'
    enabled true
    gpgcheck true
    gpgkey 'http://packages.erlang-solutions.com/debian/erlang_solutions.asc'
  end
```

Usage Example
-------------
To disable the erlang_solutions repository through a Role or Environment definition

```
default_attributes(
  :yum => {
    :erlang_solutions => {
      :enabled => {
        false
       }
     }
   }
 )
```

To enable the erlang_solutions repository with a wrapper cookbook, place
the following in a recipe:

```
node.default['yum']['erlang_solutions']['enabled'] = true
include_recipe 'yum-erlang_solutions'
```

More Examples
-------------
Point the erlang_solutions repositories at an internally hosted server.

```
node.default['yum']['erlang_solutions']['enabled'] = true
node.default['yum']['erlang_solutions']['baseurl'] = 'https://internal.example.com/erlang_solutions'
node.default['yum']['erlang_solutions']['sslverify'] = false

include_recipe 'yum-erlang_solutions'
```

License & Authors
-----------------

**Author:** Cookbook Engineering Team (<cookbooks@chef.io>)

**Copyright:** 2011-2015, Chef Software, Inc.
```
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
package edu.ua.cs.teaser.text;

public class Word {

    private String text;

    public Word(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

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


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

import java.math.BigInteger;
import java.util.List;

import ghidra.app.plugin.core.debug.gui.colors.MultiSelectionBlendedLayoutBackgroundColorManager.ColoredFieldSelection;

public interface SelectionGenerator {
	void addSelections(BigInteger layoutIndex, SelectionTranslator translator,
			List<ColoredFieldSelection> selections);
}


text:
namespace base {
class TimeDelta;
}

namespace gfx {
class Image;
}

namespace message_center {

namespace test {
class NotificationListTest;
}

class Notification;
class NotificationDelegate;
struct NotifierId;

// Comparers used to auto-sort the lists of Notifications.
struct MESSAGE_CENTER_EXPORT ComparePriorityTimestampSerial {
  bool operator()(Notification* n1, Notification* n2) const;
};

struct MESSAGE_CENTER_EXPORT CompareTimestampSerial {
  bool operator()(Notification* n1, Notification* n2) const;
};

// An adapter to allow use of the comparers above with std::unique_ptr.
template <typename PlainCompare>
struct UniquePtrCompare {
  template <typename T>
  bool operator()(const std::unique_ptr<T>& n1,
                  const std::unique_ptr<T>& n2) const {
    return PlainCompare()(n1.get(), n2.get());
  }
};

// A helper class to manage the list of notifications.
class MESSAGE_CENTER_EXPORT NotificationList {
 public:
  struct NotificationState {
    bool operator!=(const NotificationState& other) const;

    bool shown_as_popup = false;
    bool is_read = false;
  };

  // Auto-sorted set. Matches the order in which Notifications are shown in
  // Notification Center.
  using Notifications = std::set<Notification*, ComparePriorityTimestampSerial>;
  using OwnedNotifications =
      std::map<std::unique_ptr<Notification>,
               NotificationState,
               UniquePtrCompare<ComparePriorityTimestampSerial>>;

  // Auto-sorted set used to return the Notifications to be shown as popup
  // toasts.
  using PopupNotifications = std::set<Notification*, CompareTimestampSerial>;

  explicit NotificationList(MessageCenter* message_center);

  NotificationList(const NotificationList&) = delete;
  NotificationList& operator=(const NotificationList&) = delete;

  virtual ~NotificationList();

  // Makes a message "read". Collects the set of ids whose state have changed
  // and set to |udpated_ids|. NULL if updated ids don't matter.
  void SetNotificationsShown(const NotificationBlockers& blockers,
                             std::set<std::string>* updated_ids);

  void AddNotification(std::unique_ptr<Notification> notification);

  void UpdateNotificationMessage(
      const std::string& old_id,
      std::unique_ptr<Notification> new_notification);

  void RemoveNotification(const std::string& id);

  // Returns all notifications in this list.
  Notifications GetNotifications() const;

  // Returns all notifications that have a matching |notifier_id|.
  Notifications GetNotificationsByNotifierId(
      const NotifierId& notifier_id) const;

  // Returns all notifications that have a matching |app_id|.
  Notifications GetNotificationsByAppId(const std::string& app_id) const;

  // Returns all notifications that have a matching `origin_url`.
  Notifications GetNotificationsByOriginUrl(const GURL& origin_url) const;

  // Returns true if the notification exists and was updated.
  bool SetNotificationIcon(const std::string& notification_id,
                           const gfx::Image& image);

  // Returns true if the notification exists and was updated.
  bool SetNotificationImage(const std::string& notification_id,
                            const gfx::Image& image);

  // Returns true if |id| matches a notification in the list and that
  // notification's type matches the given type.
  bool HasNotificationOfType(const std::string& id,
                             const NotificationType type) const;

  // Returns false if the first notification has been shown as a popup (which
  // means that all notifications have been shown).
  bool HasPopupNotifications(const NotificationBlockers& blockers) const;

  // Returns the recent notifications of the priority higher then LOW,
  // that have not been shown as a popup. kMaxVisiblePopupNotifications are
  // used to limit the number of notifications for the DEFAULT priority.
  // It also stores the list of notifications which are blocked by |blockers|
  // to |blocked|. |blocked| can be NULL if the caller doesn't care which
  // notifications are blocked.
  PopupNotifications GetPopupNotifications(const NotificationBlockers& blockers,
                                           std::list<std::string>* blocked);

  // Marks a specific popup item as shown. Set |mark_notification_as_read| to
  // true in case marking the notification as read too.
  void MarkSinglePopupAsShown(const std::string& id,
                              bool mark_notification_as_read);

  // Marks a specific popup item as displayed.
  void MarkSinglePopupAsDisplayed(const std::string& id);

  // Resets the state for a pop up so that it can be shown again. Used to
  // bring up a grouped notification when a new item is added to it.
  void ResetSinglePopup(const std::string& id);

  NotificationDelegate* GetNotificationDelegate(const std::string& id);

  bool quiet_mode() const { return quiet_mode_; }

  // Sets the current quiet mode status to |quiet_mode|.
  void SetQuietMode(bool quiet_mode);

  // Sets the current quiet mode to true. The quiet mode will expire in the
  // specified time-delta from now.
  void EnterQuietModeWithExpire(const base::TimeDelta& expires_in);

  // Returns the notification with the corresponding id. If not found, returns
  // NULL. Notification instance is owned by this list.
  Notification* GetNotificationById(const std::string& id);

  void PopupBlocked(const std::string& id);

  // Returns all visible notifications, in a (priority-timestamp) order.
  // Suitable for rendering notifications in a MessageCenter.
  Notifications GetVisibleNotifications(
      const NotificationBlockers& blockers) const;
  size_t NotificationCount(const NotificationBlockers& blockers) const;

 private:
  friend class NotificationListTest;
  FRIEND_TEST_ALL_PREFIXES(NotificationListTest,
                           TestPushingShownNotification);

  // Iterates through the list and returns the first notification matching |id|.
  OwnedNotifications::iterator GetNotification(const std::string& id);
  OwnedNotifications::const_iterator GetNotification(
      const std::string& id) const;

  void EraseNotification(OwnedNotifications::iterator iter);

  void PushNotification(std::unique_ptr<Notification> notification);

  raw_ptr<MessageCenter> message_center_;  // owner
  OwnedNotifications notifications_;
  bool quiet_mode_;
};

}  // namespace message_center

#endif // UI_MESSAGE_CENTER_NOTIFICATION_LIST_H_


text:
package consulo.msil.lang.psi.impl;

import javax.annotation.Nonnull;
import com.intellij.lang.ASTNode;
import com.intellij.psi.stubs.IStubElementType;
import consulo.dotnet.lang.psi.impl.DotNetPsiCountUtil;
import consulo.dotnet.psi.DotNetGenericParameterList;
import consulo.msil.lang.psi.MsilGenericParameter;
import consulo.msil.lang.psi.MsilStubElements;
import consulo.msil.lang.psi.impl.elementType.stub.MsilGenericParameterListStub;

/**
 * @author VISTALL
 * @since 23.05.14
 */
public class MsilGenericParameterListImpl extends MsilStubElementImpl<MsilGenericParameterListStub> implements DotNetGenericParameterList
{
	public MsilGenericParameterListImpl(@Nonnull ASTNode node)
	{
		super(node);
	}

	public MsilGenericParameterListImpl(@Nonnull MsilGenericParameterListStub stub, @Nonnull IStubElementType nodeType)
	{
		super(stub, nodeType);
	}

	@Override
	public void accept(MsilVisitor visitor)
	{

	}

	@Nonnull
	@Override
	public MsilGenericParameter[] getParameters()
	{
		return getStubOrPsiChildren(MsilStubElements.GENERIC_PARAMETER, MsilGenericParameter.ARRAY_FACTORY);
	}

	@Override
	public int getGenericParametersCount()
	{
		return DotNetPsiCountUtil.countChildrenOfType(this, MsilStubElements.GENERIC_PARAMETER);
	}
}


text:
using UnityEditor;
using UnityEngine;

namespace Common.IO
{
    [CustomPropertyDrawer(typeof(ResourceReference))]
    public class ResourceReferenceDrawer : PropertyDrawer
    {
        private Rect m_ContentArea;

        // Draw the property inside the given rect
        public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
        {
            m_ContentArea = pos;
            EditorGUI.BeginProperty(m_ContentArea, label, prop);
            m_ContentArea.height = EditorGUIExtensions.DEFAULT_GUI_HEIGHT;
            ResourcesDBItem tempResourceItem = null;
            SerializedProperty assetProp = prop.FindPropertyRelative("FilePath");
            if (assetProp != null)
            {
                string assetPath = assetProp.stringValue;
                Object asset = null;
                if (!string.IsNullOrEmpty(assetPath))
                {
                    System.Type type = typeof(Object);
                    string subName = prop.FindPropertyRelative("SubName").stringValue;
                    if (!string.IsNullOrEmpty(subName))
                    {
                        string typeName = prop.FindPropertyRelative("SubType").stringValue;
                        type = System.Type.GetType(typeName);
                    }
                    tempResourceItem = ResourcesDB.GetByResourcesPath(assetPath);
                    asset = tempResourceItem.Load(type, subName);
                }
                asset = EditorGUI.ObjectField(m_ContentArea, "Asset", asset, typeof(Object), false);
                string newAssetFilePath = string.Empty;
                if (asset != null)
                {
                    string foundAssetPath = AssetDatabase.GetAssetPath(asset);
                    string foundAssetName = System.IO.Path.GetFileNameWithoutExtension(foundAssetPath);
                    newAssetFilePath = System.IO.Path.ChangeExtension(foundAssetPath, null);
                    ResourcesDBItem info = ResourcesDB.GetByPath(newAssetFilePath);
                    //noverting path to resource path
                    newAssetFilePath = (info != null) ? info.ResourcesPath : string.Empty;

                    if (asset.name != foundAssetName)
                    {
                        prop.FindPropertyRelative("SubName").stringValue = asset.name;
                        prop.FindPropertyRelative("SubType").stringValue = asset.GetType().AssemblyQualifiedName;
                    }
                    else
                    {
                        prop.FindPropertyRelative("SubName").stringValue = string.Empty;
                        prop.FindPropertyRelative("SubType").stringValue = string.Empty;
                    }
                }
                assetProp.stringValue = newAssetFilePath;
                if (tempResourceItem != null)
                {
                    tempResourceItem.Unload();
                }
            }

            EditorGUI.EndProperty();
        }

        public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
        {
            return EditorGUIExtensions.DEFAULT_GUI_LINE_HEIGHT;
        }
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/geo_hyperplane_3.dir/geo_hyperplane.cpp.o"
  "geo_hyperplane_3.pdb"
  "geo_hyperplane_3"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/geo_hyperplane_3.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
/**
 * This package contains utility classes.
 */
package citizensnips.marshals.util;


text:
(function (window, bean, qwest, dom, minifier) {
    'use strict';

    bean.on(window, 'load', function () {
        var errorView  = minifier.errorView(dom, '#errorView'),
            outputView = minifier.outputView(dom, '#outputView', bean, window),
            formView   = minifier.formView(dom, '#formView', bean, qwest, errorView, outputView);

        formView.initialize();
    });
}(window, bean, qwest, URLMinifier.dom, URLMinifier.minifier));


text:
package com.voxeo.moho.sip;

import javax.media.mscontrol.MsControlException;
import javax.media.mscontrol.join.Joinable.Direction;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;

import com.voxeo.moho.Participant.JoinType;
import com.voxeo.moho.event.JoinCompleteEvent;
import com.voxeo.moho.sip.SIPCall.State;
import com.voxeo.moho.util.SDPUtils;

public class DirectNI2NIJoinDelegate extends JoinDelegate {

  protected Direction _direction;

  protected DirectNI2NIJoinDelegate(final SIPIncomingCall call1, final SIPIncomingCall call2,
      final Direction direction, SIPCallImpl peer) {
    _call1 = call1;
    _call2 = call2;
    _direction = direction;
    _peer = peer;
  }

  @Override
  public void doJoin() throws Exception {
    super.doJoin();
    // TODO call1 or call2 in PROCESSED state.
    final SipServletResponse res1 = _call1.getSipInitnalRequest().createResponse(SipServletResponse.SC_OK);
    if (_call2.getRemoteSdp() != null) {
      res1.setContent(SDPUtils.formulateSDP(_call1, _call2.getRemoteSdp()), "application/sdp");
    }
    res1.send();
    final SipServletResponse res2 = _call2.getSipInitnalRequest().createResponse(SipServletResponse.SC_OK);
    if (_call1.getRemoteSdp() != null) {
      res2.setContent(SDPUtils.formulateSDP(_call2, _call1.getRemoteSdp()), "application/sdp");
    }
    res2.send();
  }

  @Override
  protected void doAck(final SipServletRequest req, final SIPCallImpl call) throws MsControlException {
    call.setSIPCallState(State.ANSWERED);
    doDisengage(call, JoinType.DIRECT);
    if (_call1.equals(call)) {
      _call1.linkCall(_call2, JoinType.DIRECT, _direction);
      done(JoinCompleteEvent.Cause.JOINED, null);
    }
  }

}


text:
package org.ngseq.metagenomics;

import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.DFSClient;
import org.apache.hadoop.hdfs.DFSInputStream;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.broadcast.Broadcast;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;

/**Usage
 spark-submit --master local[${NUM_EXECUTORS}] --executor-memory 20g --class org.ngseq.metagenomics.Assemble metagenomics-0.9-jar-with-dependencies.jar -in ${OUTPUT_PATH}/${PROJECT_NAME}_groupped -out ${OUTPUT_PATH}/${PROJECT_NAME}_assembled -localdir ${LOCAL_TEMP_PATH} -merge -t ${ASSEMBLER_THREADS}

 spark-submit --master yarn --deploy-mode ${DEPLOY_MODE} --conf spark.dynamicAllocation.enabled=true --conf spark.dynamicAllocation.cachedExecutorIdleTimeout=100 --conf spark.shuffle.service.enabled=true --conf spark.scheduler.mode=${SCHEDULER_MODE} --conf spark.task.maxFailures=100 --conf spark.yarn.max.executor.failures=100 --executor-memory 20g --conf spark.yarn.executor.memoryOverhead=10000  --class org.ngseq.metagenomics.Assemble metagenomics-0.9-jar-with-dependencies.jar -in ${OUTPUT_PATH}/${PROJECT_NAME}_groupped -out ${OUTPUT_PATH}/${PROJECT_NAME}_assembled -localdir ${LOCAL_TEMP_PATH} -merge -t ${ASSEMBLER_THREADS}

 **/

public class Assemble {

  public static void main(String[] args) throws IOException {
    SparkConf conf = new SparkConf().setAppName("Assemble");
    JavaSparkContext sc = new JavaSparkContext(conf);

    Options options = new Options();

    Option splitOpt = new Option( "in", true, "" );
    Option cOpt = new Option( "t", true, "Threads" );
    Option kOpt = new Option( "m", true, "fraction of memory to be used per process" );
    Option ouOpt = new Option( "out", true, "" );

    options.addOption(new Option( "localdir", true, "Absolute path to local temp dir ( YARN must have write permissions if YARN used)"));
    options.addOption(new Option( "merge", "Merge output"));
    options.addOption(  new Option( "subdirs", "Read from subdirectories" ) );
    options.addOption(  new Option( "debug", "saves error log" ) );
    options.addOption(  new Option( "bin", true,"Path to megahit binary, defaults calls 'megahit'" ) );
    options.addOption(  new Option( "single", "Single reads option, default is interleaved paired-end" ) );
    options.addOption( splitOpt );
    options.addOption( cOpt );
    options.addOption( kOpt );
    options.addOption( ouOpt );

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp( "spark-submit <spark specific args>", options, true );

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse( options, args );
    }
    catch( ParseException exp ) {
      System.err.println( "Parsing failed.  Reason: " + exp.getMessage() );
      System.exit(1);
    }
    String inputPath = (cmd.hasOption("in")==true)? cmd.getOptionValue("in"):null;
    String outDir = (cmd.hasOption("out")==true)? cmd.getOptionValue("out"):null;
    String localdir = cmd.getOptionValue("localdir");
    boolean subdirs = cmd.hasOption("subdirs");
    boolean debug = cmd.hasOption("debug");
    String readstype = (cmd.hasOption("single")==true)? "-r":"--12";
    String bin = (cmd.hasOption("bin")==true)? cmd.getOptionValue("bin"):"megahit";

    int t = (cmd.hasOption("t")==true)? Integer.valueOf(cmd.getOptionValue("t")):1;
    double m = (cmd.hasOption("m")==true)? Double.valueOf(cmd.getOptionValue("m")):0.9;
    boolean mergeout = cmd.hasOption("merge");

    FileSystem fs = FileSystem.get(new Configuration());
    fs.mkdirs(fs,new Path(outDir),new FsPermission(FsAction.ALL,FsAction.ALL,FsAction.ALL));

    ArrayList<String> splitFileList = new ArrayList<>();
    if(subdirs){
      FileStatus[] dirs = fs.listStatus(new Path(inputPath));
      for (FileStatus dir : dirs){
        FileStatus[] st = fs.listStatus(dir.getPath());
        for (int i=0;i<st.length;i++){
          String fn = st[i].getPath().getName().toString();
          if(!fn.equalsIgnoreCase("_SUCCESS")){
            splitFileList.add(st[i].getPath().toUri().getRawPath().toString());
            System.out.println(st[i].getPath().toUri().getRawPath().toString());
          }
        }
      }
    }else{
      FileStatus[] st = fs.listStatus(new Path(inputPath));
      for (int i=0;i<st.length;i++){
        String fn = st[i].getPath().getName().toString();
        if(!fn.equalsIgnoreCase("_SUCCESS"))
          splitFileList.add(st[i].getPath().toUri().getRawPath().toString());
      }
    }

    JavaRDD<String> splitFilesRDD = sc.parallelize(splitFileList, splitFileList.size());
    Broadcast<String> bs = sc.broadcast(fs.getUri().toString());
    JavaRDD<String> outRDD = splitFilesRDD.mapPartitions(f -> {
      String path = f.next();
      System.out.println(path);
      String fname;
      if(path.lastIndexOf(".")<path.lastIndexOf("/"))
        fname = path.substring(path.lastIndexOf("/")+1);
      else fname = path.substring(path.lastIndexOf("/")+1, path.lastIndexOf("."));

      String tempName = String.valueOf((new Date()).getTime());

      DFSClient client = new DFSClient(URI.create(bs.getValue()), new Configuration());
      DFSInputStream hdfsstream = client.open(path);

      String ass_cmd = bin+" -t" + t + " -m" + m + " "+readstype+" /dev/stdin -o "+localdir+"/"+tempName; //YARN must have write permission to localdir
      System.out.println(ass_cmd);

      ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", ass_cmd);
      Process process = pb.start();

      BufferedReader hdfsinput = new BufferedReader(new InputStreamReader(hdfsstream));
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
      String line;
      while ((line = hdfsinput.readLine()) != null) {
	writer.write(line);
        writer.newLine();
      }
      writer.close();

      ArrayList<String> out = new ArrayList<String>();

      BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
      String e;
      while ((e = err.readLine()) != null) {
        System.out.println(e);
        out.add(e);
      }

      String copy_cmd = System.getenv("HADOOP_HOME")+"/bin/hdfs dfs -put "+localdir+"/"+tempName+" "+outDir+"/megahit_"+fname; //YARN should have write permissions to /tmp in HDFS
	ProcessBuilder pb2 = new ProcessBuilder("/bin/sh", "-c", copy_cmd);
      Process process2 = pb2.start();

      BufferedReader err2 = new BufferedReader(new InputStreamReader(process2.getErrorStream()));
      String e2;
      while ((e2 = err2.readLine()) != null) {
        System.out.println(e2);
        out.add(e2);
      }
      process2.waitFor();

      String delete_cmd = "rm -rf "+localdir+"/"+tempName;

      ProcessBuilder pb3 = new ProcessBuilder("/bin/sh", "-c", delete_cmd);
      Process process3 = pb3.start();
      BufferedReader err3 = new BufferedReader(new InputStreamReader(process3.getErrorStream()));
      String e3;
      while ((e3 = err3.readLine()) != null) {
        System.out.println(e3);
        out.add(e3);
      }
      process3.waitFor();

      out.add(ass_cmd);
      out.add(copy_cmd);
      out.add(delete_cmd);

      return out.iterator();
    });
    if(debug) outRDD.saveAsTextFile("pipe_errorlog/"+String.valueOf(new Date().getTime()));
    else outRDD.foreach(err -> System.out.println(err));

    if(mergeout){

      FileStatus[] dirs = fs.listStatus(new Path(outDir));
      for (FileStatus dir : dirs){
	if(dir.getPath().getName().toString().startsWith("megahit")){
       	 FileStatus[] st = fs.listStatus(dir.getPath());
        	for (int i=0;i<st.length;i++){
          		String fn = st[i].getPath().getName().toString();
          			if(fn.endsWith(".fasta") || fn.endsWith(".fa")){
            				String dst = outDir+"/"+dir.getPath().getName()+"_"+st[i].getPath().getName();
            				FileUtil.copy(fs, st[i].getPath(), fs, new Path(dst),true, new Configuration());
          			}
        	}
      		fs.delete(dir.getPath(), true);
	}
	}
    }

    sc.stop();

  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OwlAPI.Structure;
using OwlAlgos.ShortestPath;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace OwlAlgos.SSSP
{
    /// <summary>
    /// implements a parallel single source shortest path using concurrentqueue
    /// </summary>
    public class pSSSP : ABreadthFirstSearch
    {
        public static void Search(IGraph myGraph, IVertex mySource, Func<IVertex, bool> myMatchingFunc = null)
        {
            Search(myGraph, mySource, false, myMatchingFunc);
        }

        /// <summary>
        /// BFS for st-connectivity
        /// </summary>
        /// <param name="myGraph"></param>
        /// <param name="mySource"></param>
        /// <param name="myTarget"></param>
        /// <param name="myMatchingFunc"></param>
        /// <returns></returns>
        public static void Search(IGraph myGraph, IVertex mySource, bool myInitGraph, Func<IVertex, bool> myMatchingFunc = null)
        {
            #region Init

            if (myInitGraph)
            {
                InitGraph(myGraph);
            }
            mySource.IsVisited = true;
            mySource.Distance = 0;

            // bool if matching function has to be called
            var doMatching = myMatchingFunc != null;

            // use Concurrent Queue for parallel access
            var queue = new ConcurrentQueue<IVertex>();

            #endregion

            #region BFS

            // enqueue the source vertex
            queue.Enqueue(mySource);

            while (queue.Count > 0)
            {
                Parallel.ForEach(queue, u =>
                    {
                        if(queue.TryDequeue(out u))
                        {
                            // process neighbours in parallel
                            //Parallel.ForEach<IEdge>(u.OutgoingEdges, outEdge =>
                            foreach (var outEdge in u.OutgoingEdges)
                            {
                                // neighbour node
                                var v = outEdge.Target;

                                if (!v.IsVisited) // unexplorered node
                                {
                                    // set as visited (Color.RED)
                                    v.IsVisited = true;
                                    // set the predecessor
                                    v.Predecessor = u;
                                    //increment the distance
                                    v.Distance = u.Distance + 1;
                                    // and enqueue that node (if matching condition == true)
                                    if (doMatching)
                                    {
                                        // matches condition?
                                        if (myMatchingFunc(v))
                                        {
                                            // matches, enqueue
                                            queue.Enqueue(v);
                                        }
                                    }
                                    else
                                    {
                                        // no matching necessary
                                        queue.Enqueue(v);
                                    }
                                }
                            }
                        }
                    });
            }

            #endregion
        }
    }
}


text:
require 'stripe/customer_subscription_deleted'
require 'stripe/checkout_session_completed'

module Stripe
  API_KEY = ENV.fetch('STRIPE_API_KEY')
  PLAN_ID = ENV.fetch('STRIPE_PLAN_ID')
  PLAN_PRICE_IN_CENTS = ENV.fetch('STRIPE_PLAN_PRICE_IN_CENTS').to_i
  PUBLISHABLE_KEY = ENV.fetch('STRIPE_PUBLISHABLE_KEY')
  TRIAL_PERIOD_DAYS = ENV.fetch('STRIPE_TRIAL_PERIOD_DAYS')
  WEBHOOK_SIGNING_SECRET = ENV.fetch('STRIPE_WEBHOOK_SIGNING_SECRET')
end

Stripe.api_key = Stripe::API_KEY
StripeEvent.signing_secret = Stripe::WEBHOOK_SIGNING_SECRET

StripeEvent.configure do |events|
  events.subscribe 'checkout.session.completed',
    Stripe::CheckoutSessionCompleted.new
  events.subscribe 'customer.subscription.deleted',
    Stripe::CustomerSubscriptionDeleted.new
end


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="chantey.xsl"?>
<!DOCTYPE chantey SYSTEM "chantey.dtd">
<chantey>
    <title>On the Banks of Sacramento</title>
    <collection>1894BMORCOM</collection>
    <location>61</location>
    <author>
        <personid>Trad</personid>
    </author>
    <ID>R000319</ID>

<text>
As I was walking down the street,
    Hoodah, to my Hoodah;
A charming girl I chanced to meet,
    Hoodah, Hoodah day.

Blow ye wind heigho,
    For California, O;
There's plenty of gold
    So I've been told
On the banks of Sacramento.
</text>

</chantey>


text:
package redisearch

import (
	"time"
)

type resultChan chan interface{}

type workUnit struct {
	f   func(interface{}) interface{}
	v   interface{}
	out resultChan
}

type workQueue chan workUnit

func (wq workQueue) poolWorker() {

	for work := range wq {
		work.out <- work.f(work.v)
	}
}

// newWorkQueue creates a new workQueue with N workers
func newWorkQueue(numWorkers int) workQueue {
	wc := make(workQueue)
	for i := 0; i < numWorkers; i++ {
		go wc.poolWorker()

	}
	return wc
}

func (wq workQueue) NewTaskGroup() *taskGroup {
	return &taskGroup{
		wq:  wq,
		rc:  make(resultChan, 8),
		num: 0,
	}
}

type taskGroup struct {
	wq  workQueue
	rc  resultChan
	num int
}

func (t *taskGroup) Submit(f func(interface{}) interface{}, v interface{}) {
	t.wq <- workUnit{f, v, t.rc}
	t.num++
}
func (t *taskGroup) Wait(timeout time.Duration) ([]interface{}, error) {
	returns := 0
	//end := time.Now().Add(timeout)
	ret := make([]interface{}, 0, t.num)
	var err error

	for returns < t.num { // && time.Now().Before(end) {

		var res interface{}
		select {
		case res = <-t.rc:
			ret = append(ret, res)
			returns++
			//		case <-time.After(end.Sub(time.Now())):
			//			goto endit
		}

	}

	return ret, err
}


text:
package Test::VS::RuleEngine::Input;

use strict;
use warnings;

use Carp qw(croak);

use base qw(VS::RuleEngine::Input);

sub new {
    my ($pkg, %args) = @_;
    my $self = bless { %args }, $pkg;
    return $self;
}

1;
__END__

=head1 NAME

Test::VS::RuleEngine::Input - Test input class

=head1 INTERFACE

=head2 CLASS METHODS

=over 4

=item new

Creates a new instace.

=back

=cut


text:
@interface StylizeCSSParser : NSObject

- (NSDictionary *)parseText:(NSString *)cssText;

@end


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.apache.wicket.feedback (Wicket Parent 1.5.7 API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.wicket.feedback package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

org.apache.wicket.feedback

Interfaces

IFeedback

IFeedbackMessageFilter

Classes

ComponentFeedbackMessageFilter

ContainerFeedbackMessageFilter

ErrorLevelFeedbackMessageFilter

FeedbackMessage

FeedbackMessages

FeedbackMessagesModel


text:
<?php
/**
 * The template for displaying search forms.
 *
 * @file      searchform.php
 * @package   max-magazine
 * @author    Sami Ch.
 * @link 	  http://gazpo.com
 */
?>

<form method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
	<div>
		<input class="searchfield" type="text" value="<?php _e('Search', 'max-magazine');?>" name="s" id="s" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}" />
	</div>
</form>


text:
module Google
  module Ads
    module GoogleAds
      module V10
        module Services
          module AdGroupCriterionCustomizerService
            # Path helper methods for the AdGroupCriterionCustomizerService API.
            module Paths
              ##
              # Create a fully-qualified AdGroupCriterion resource string.
              #
              # The resource will be in the following format:
              #
              # `customers/{customer_id}/adGroupCriteria/{ad_group_id}~{criterion_id}`
              #
              # @param customer_id [String]
              # @param ad_group_id [String]
              # @param criterion_id [String]
              #
              # @return [::String]
              def ad_group_criterion_path customer_id:, ad_group_id:, criterion_id:
                raise ::ArgumentError, "customer_id cannot contain /" if customer_id.to_s.include? "/"
                raise ::ArgumentError, "ad_group_id cannot contain /" if ad_group_id.to_s.include? "/"

                "customers/#{customer_id}/adGroupCriteria/#{ad_group_id}~#{criterion_id}"
              end

              ##
              # Create a fully-qualified AdGroupCriterionCustomizer resource string.
              #
              # The resource will be in the following format:
              #
              # `customers/{customer_id}/adGroupCriterionCustomizers/{ad_group_id}~{criterion_id}~{customizer_attribute_id}`
              #
              # @param customer_id [String]
              # @param ad_group_id [String]
              # @param criterion_id [String]
              # @param customizer_attribute_id [String]
              #
              # @return [::String]
              def ad_group_criterion_customizer_path customer_id:, ad_group_id:, criterion_id:, customizer_attribute_id:
                raise ::ArgumentError, "customer_id cannot contain /" if customer_id.to_s.include? "/"
                raise ::ArgumentError, "ad_group_id cannot contain /" if ad_group_id.to_s.include? "/"
                raise ::ArgumentError, "criterion_id cannot contain /" if criterion_id.to_s.include? "/"

                "customers/#{customer_id}/adGroupCriterionCustomizers/#{ad_group_id}~#{criterion_id}~#{customizer_attribute_id}"
              end

              ##
              # Create a fully-qualified CustomizerAttribute resource string.
              #
              # The resource will be in the following format:
              #
              # `customers/{customer_id}/customizerAttributes/{customizer_attribute_id}`
              #
              # @param customer_id [String]
              # @param customizer_attribute_id [String]
              #
              # @return [::String]
              def customizer_attribute_path customer_id:, customizer_attribute_id:
                raise ::ArgumentError, "customer_id cannot contain /" if customer_id.to_s.include? "/"

                "customers/#{customer_id}/customizerAttributes/#{customizer_attribute_id}"
              end

              extend self
            end
          end
        end
      end
    end
  end
end


text:
//
//  Copyright 2012 Alin Dobra and Christopher Jermaine
//  Copyright 2013 Tera Insights
//
//  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.
//
#include "LT_GIST.h"
#include "AttributeManager.h"
#include "TwoWayList.h"

using namespace std;

bool LT_GIST :: GetConfig(WayPointConfigureData& where) {
    // Get the ID
    WayPointID myID = GetId();

    // Set up work functions.
    GISTPreProcessWorkFunc preprocess(NULL);
    GISTNewRoundWorkFunc newRound(NULL);
    GISTDoStepsWorkFunc doSteps(NULL);
    GISTMergeStatesWorkFunc mergeStates(NULL);
    GISTShouldIterateWorkFunc shouldIterate(NULL);
    GISTProduceResultsWorkFunc produceResults(NULL);
    GISTProduceStateWorkFunc produceState(NULL);

    WorkFuncContainer myWorkFuncs;

    myWorkFuncs.Insert(preprocess);
    myWorkFuncs.Insert(newRound);
    myWorkFuncs.Insert(doSteps);
    myWorkFuncs.Insert(mergeStates);
    myWorkFuncs.Insert(shouldIterate);
    myWorkFuncs.Insert(produceResults);
    myWorkFuncs.Insert(produceState);

    // Manage query exits
    QueryExitContainer myEndingQueryExits;
    QueryExitContainer myFlowThroughQueryExits;
    GetQueryExits (myFlowThroughQueryExits, myEndingQueryExits);

    // Managed required states
    QueryToReqStates myReqStates;
    QueryIDToBool myReturnStates;
    for( auto it : stateSources ) {
        QueryID curID = it.first;
        StateSourceVec& reqStates = it.second;

        ReqStateList stateList;

        for( StateSourceVec::iterator iter = reqStates.begin(); iter != reqStates.end(); ++iter) {
            WayPointID curSource = *iter;
            stateList.Append(curSource);
        }

        myReqStates.Insert( curID, stateList );
    }

    for( auto it : infoMap ) {
        QueryID qID = it.first;
        Json::Value & info = it.second;

        Swapify<bool> retState = info[J_STATE].asBool();
        myReturnStates.Insert(qID, retState);
    }

    // Create the configuration data.
    GISTConfigureData myConfig(myID, myWorkFuncs, myEndingQueryExits,
            myFlowThroughQueryExits, myReqStates, myReturnStates);

    where.swap(myConfig);

    return true;
}

void LT_GIST :: DeleteQuery(QueryID query) {
    DeleteQueryCommon(query);
    synthesized.erase(query);
    QueryID qID;
    SlotContainer slotCont;

    infoMap.erase(query);
}

void LT_GIST :: ClearAllDataStructure() {
    ClearAll();
    synthesized.clear();
    infoMap.clear();
}

bool LT_GIST :: AddGIST( QueryID query,
			 SlotContainer& resultAtts,
             StateSourceVec & sVec,
			 Json::Value& info) {
    infoMap[query] = info;
    stateSources[query] = sVec;

    SlotSet rAtts;
    SlotContainerToSet(resultAtts, rAtts);

    queriesCovered.Union(query);
    CheckQueryAndUpdate(query, rAtts, synthesized);

    return true;
}

bool LT_GIST::ReturnAsState( QueryID query ) {
    Json::Value &info = infoMap[query];

    info[J_STATE] = true;
    return true;
}

// atts coming from top is dropped as it will not be propagated down
// that also means, all attributes coming from top are synthesized ones
// 1. result is blank, as this waypoint uses no attributes
// 2. Correctness : Atts coming from top is subset of synthesized
bool LT_GIST :: PropagateDown(QueryID query, const SlotSet& atts, SlotSet& result, QueryExit qe) {
    // atts coming from top should be subset of synthesized
    if( !IsSubSet(atts, synthesized[query]) ) {
        cerr << "GISTWP : Aggregate error: attributes coming from top are not subset of synthesized ones" << endl;
        cerr << "PropgateDown for Waypoint " << GetWPName() << endl;
        cerr << "Query: " << query.ToString() << endl;
        /* FIXME: GetAllAttrAsString got removed somehow
        cerr << "a0tts: " << GetAllAttrAsString(atts) << endl;
        cerr << "synthesized[query]: " << GetAllAttrAsString(synthesized[query]) << endl;
        */
        return false;
    }

    result.clear();
    queryExit.Insert(qe);
    return true;
}

bool LT_GIST :: PropagateDownTerminating(QueryID query, const SlotSet& atts, SlotSet& result, QueryExit qe ) {
    // atts coming from top should be subset of synthesized
    if( !IsSubSet(atts, synthesized[query]) ) {
        cerr << "GISTWP : Aggregate error: attributes coming from top are not subset of synthesized ones" << endl;
        cerr << "PropgateDownTerminating for Waypoint " << GetWPName() << endl;
        cerr << "Query: " << query.ToString() << endl;
        /* FIXME: GetAllAttrAsString got removed somehow
        cerr << "atts: " << GetAllAttrAsString(atts) << endl;
        cerr << "synthesized[query]: " << GetAllAttrAsString(synthesized[query]) << endl;
        */
        return false;
    }

    queryExitTerminating.Insert(qe);
    return true;
}

// GIST uses no attributes, so just say that our result is the attributes we're producing.
bool LT_GIST :: PropagateUp(QueryToSlotSet& result) {
    result.clear();
    result = synthesized;

    return true;
}

Json::Value LT_GIST::GetJson(){
  Json::Value out(Json::objectValue);// overall object to be return

  IDInfo info;
  GetId().getInfo(info);
  out[J_NAME] = info.getName();
  out[J_TYPE] = JN_GIST_WP;

  out[J_PAYLOAD] = MapToJson(infoMap);

  SlotToQuerySet reverse;
  AttributesToQuerySet(used, reverse);
  out[J_ATT_MAP] = JsonAttToQuerySets(reverse);

  return out;
}


text:
$(document).ready( function() {

    $("#search").addEventListener("keyup", function(event) {
        var value = $(this).val();
        $.ajax({
            url: "http://search.xignite.com/Search/Suggest?parameter=XigniteFinancials.GetCompanyBalanceSheet.Identifier&term=" + value + "&tags=XNYS,XNAS",
            success: function(responses) {
                console.log(responses);
                $("#searchresults").empty();
                for (var i = 0; i < responses.Results.length; i++) {
                    //console.log(responses.Results[i].Value);
                    $("<option/>").html(responses.Results[i].Value).appendTo("#searchresults");
                }
                $(this).focus();
            }

        });
    }, false);

} );


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   timer.h
 * Author: admin
 *
 * Created on 2017年3月7日, 下午1:26
 */

#ifndef TIMER_H
#define TIMER_H
#include "svr_define.h"
namespace easynet{
class Timer
    {
        //epoll_wait 是毫秒级别的timeout
        public:
            Timer();
            ~Timer();
        public:
            //创建timer, 返回timerID
            //tick 超时时间, 单位毫秒, handler 处理的函数
            uint64_t CreateTimer(uint64_t tick, const _OnTimerHandler& handler);
            uint64_t CreateTimer(uint64_t tick, _OnTimerHandler &&handler);
            //删除定时器
            bool CancelTimer(uint64_t id);
            //检查定时器
            void CheckTimer();
            uint32_t GetNextExpireTime();
        private:
            //毫秒为单位
            uint64_t GetSysTick();

        private:
            int64_t MakeTimerID();
            std::map<uint64_t, _OnTimerHandler*> timer_map_;
            const uint64_t start_sys_time_ = GetSysTick();

    };
}

#endif /* TIMER_H */


text:
//
//  Language.m
//  Checker Mobile
//
//  Created by Puganda_Mac on 4/7/15.
//  Copyright (c) 2015 Puganda_Mac. All rights reserved.
//

#import "Language.h"

@implementation Language
static NSBundle *bundle = nil;
static NSString *currentLanguage;
+(void)initialize {
    //   NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    //    NSArray* languages = [defs objectForKey:@"AppleLanguages"]; anhnt6 comment
    //    NSString *current =@"vi";// [[languages objectAtIndex:0] retain];
    //    [self setLanguage:current];
    [self setLanguage:@"vi"];
}

+(void)setLanguage:(NSString *)l {
    currentLanguage=l;
    bundle = [NSBundle bundleWithPath:[[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ]];
}

+(NSString *)currentLanguage{
    return currentLanguage;
}
/*+(NSString *)fullLanguage{
 if ([currentLanguage isEqualToString:@"vi"]) {
 return @"vietnamese";
 } else if ([currentLanguage isEqualToString:@"en"]) {
 return @"english";
 }
 return @"english";
 }*/ //anhnt6 comment
+(NSString *)get:(NSString *)key alter:(NSString *)alternate {
    return [bundle localizedStringForKey:key value:alternate table:nil];
}
+(NSString *)get:(NSString *)key{
    return [bundle localizedStringForKey:key value:@"" table:nil];
}
+(int)getCodeTimeout{
    return -1;
}
@end


text:
layout: docs.hbs
title: Streams Cookbook
---

#Introduction

This is a collection of patterns to demonstrate various usage of the Akka Streams API by solving small targeted
problems in the format of "recipes". The purpose of this page is to give inspiration and ideas how to approach
various small tasks involving streams. The recipes in this page can be used directly as-is, but they are most powerful as
starting points: customization of the code snippets is warmly encouraged.

This part also serves as supplementary material for the main body of documentation. It is a good idea to have this page
open while reading the manual and look for examples demonstrating various streaming concepts
as they appear in the main body of documentation.

If you need a quick reference of the available processing stages used in the recipes see
[Overview of built-in stages and their semantics](builtinstages)

#Working with Flows

In this collection we show simple recipes that involve linear flows. The recipes in this section are rather
general, more targeted recipes are available as separate sections ( [Buffers and working with rate](buffersandworkingwithrate), [Working with streaming IO](workingwithstreamingio)).

####Logging elements of a stream

**Situation:** During development it is sometimes helpful to see what happens in a particular section of a stream.

The simplest solution is to simply use a ``Select`` operation and use ``WriteLine`` to print the elements received to the console.
While this recipe is rather simplistic, it is often suitable for a quick debug session.

```csharp
var mySource = Source.Empty<string>();

var loggedSource = mySource.Select(element =>
{
  Console.WriteLine(element);
  return element;
});
```

Another approach to logging is to use ``Log()`` operation which allows configuring logging for elements flowing through
the stream as well as completion and erroring.

```csharp
// customise log levels
mySource.Log("before-select")
    .WithAttributes(Attributes.CreateLogLevels(onElement: LogLevel.WarningLevel))
    .Select(Analyse);

// or provide custom logging adapter
mySource.Log("custom", null, Logging.GetLogger(sys, "customLogger"));
```

####Flattening a stream of sequences

**Situation:** A stream is given as a stream of sequence of elements, but a stream of elements needed instead, streaming
all the nested elements inside the sequences separately.

The ``SelectMany`` operation can be used to implement a one-to-many transformation of elements using a mapper function
in the form of ``In => IEnumerable<Out>``. In this case we want to map a ``Enumerable`` of elements to the elements in the
collection itself, so we can just call ``SelectMany(x => x)``.

```csharp
Source<List<Message>,NotUsed > myData = someDataSource;
Source<Message, NotUsed> flattened = myData.SelectMany(x => x);
```

####Draining a stream to a strict collection

**Situation:** A possibly unbounded sequence of elements is given as a stream, which needs to be collected into a collection while ensuring boundedness

A common situation when working with streams is one where we need to collect incoming elements into a collection.
This operation is supported via ``Sink.Seq`` which materializes into a ``Task<IEnumerable<T>>``.

The function ``Limit`` or ``Take`` should always be used in conjunction in order to guarantee stream boundedness, thus preventing the program from running out of memory.

For example, this is best avoided:

```csharp
// Dangerous: might produce a collection with 2 billion elements!
var f = mySource.RunWith(Sink.Seq<string>(), materializer);
```

Rather, use ``Limit`` or ``Take`` to ensure that the resulting ``Enumerable`` will contain only up to ``max`` elements:

```csharp
var MAX_ALLOWED_SIZE = 100;

// OK. Task will fail with a `StreamLimitReachedException`
// if the number of incoming elements is larger than max
var limited = mySource.Limit(MAX_ALLOWED_SIZE).RunWith(Sink.Seq<string>(), materializer);

// OK. Collect up until max-th elements only, then cancel upstream
var ignoreOverflow = mySource.Take(MAX_ALLOWED_SIZE).RunWith(Sink.Seq<string>(), materializer);
```

####Calculating the digest of a ByteString stream

**Situation:** A stream of bytes is given as a stream of ``ByteStrings`` and we want to calculate the cryptographic digest
of the stream.

This recipe uses a `GraphStage` to host a `HashAlgorithm` class (part of the .Net Cryptography
API). When the stream starts, the ``onPull`` handler of the stage is called, which just bubbles up the ``pull`` event to its upstream.
As a response to this pull, a ByteString chunk will arrive (``onPush``) which we store, then it will pull for the next chunk.

Eventually the stream of ``ByteStrings`` depletes and we get a notification about this event via ``onUpstreamFinish``.
At this point we want to emit the digest value, but we cannot do it with ``push`` in this handler directly since there may
be no downstream demand. Instead we call ``emit`` which will temporarily replace the handlers, emit the provided value when
demand comes in and then reset the stage state. It will then complete the stage.

```csharp
public class DigestCalculator : GraphStage<FlowShape<ByteString, ByteString>>
{
    private readonly string _algorithm;

    private sealed class Logic : GraphStageLogic
    {
        private readonly HashAlgorithm _digest;
        private ByteString _bytes;

        public Logic(DigestCalculator calculator) : base(calculator.Shape)
        {
            _digest = HashAlgorithm.Create(calculator._algorithm);
            _bytes = ByteString.Empty;

            SetHandler(calculator.Out, onPull: () => { Pull(calculator.In); });

            SetHandler(calculator.In, onPush: () =>
            {
                _bytes += Grab(calculator.In);
                Pull(calculator.In);
            }, onUpstreamFinish: () =>
            {
                Emit(calculator.Out, ByteString.Create(_digest.ComputeHash(_bytes.ToArray())));
                CompleteStage();
            });
        }
    }

    public DigestCalculator(string algorithm)
    {
        _algorithm = algorithm;
        Shape = new FlowShape<ByteString, ByteString>(In, Out);
    }

    public Inlet<ByteString> In { get; } = new Inlet<ByteString>("DigestCalculator.in");

    public Outlet<ByteString> Out { get; } = new Outlet<ByteString>("DigestCalculator.out");

    public override FlowShape<ByteString, ByteString> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}

var data = Source.Empty<ByteString>();
var digest = data.Via(new DigestCalculator("SHA-256"));
```

####Parsing lines from a stream of ByteStrings

**Situation:** A stream of bytes is given as a stream of ``ByteStrings`` containing lines terminated by line ending
characters (or, alternatively, containing binary frames delimited by a special delimiter byte sequence) which
needs to be parsed.

The `Framing` helper object contains a convenience method to parse messages from a stream of ``ByteStrings``:

```csharp
var rawData = Source.Empty<ByteString>();
var linesStream = rawData
    .Via(Framing.Delimiter(delimiter: ByteString.FromString("\r\n"), maximumFrameLength: 10, allowTruncation: true))
    .Select(b => b.DecodeString());
```

####Implementing reduce-by-key

**Situation:** Given a stream of elements, we want to calculate some aggregated value on different subgroups of the
elements.

The "hello world" of reduce-by-key style operations is *wordcount* which we demonstrate below. Given a stream of words
we first create a new stream that groups the words according to the ``identity`` function, i.e. now
we have a stream of streams, where every substream will serve identical words.

To count the words, we need to process the stream of streams (the actual groups
containing identical words). ``GroupBy`` returns a `SubFlow`, which
means that we transform the resulting substreams directly. In this case we use
the ``Reduce`` combinator to aggregate the word itself and the number of its
occurrences within a tuple `(String, Integer)`. Each substream will then
emit one final value—precisely such a pair—when the overall input completes. As
a last step we merge back these values from the substreams into one single
output stream.

One noteworthy detail pertains to the ``MaximumDistinctWords`` parameter: this
defines the breadth of the groupBy and merge operations. Akka Streams is
focused on bounded resource consumption and the number of concurrently open
inputs to the merge operator describes the amount of resources needed by the
merge itself.  Therefore only a finite number of substreams can be active at
any given time. If the ``GroupBy`` operator encounters more keys than this
number then the stream cannot continue without violating its resource bound, in
this case ``GroupBy`` will terminate with a failure.

```csharp
var words = Source.Empty<string>();
var counts = words
    // split the words into separate streams first
    .GroupBy(MaximumDistinctWords, x => x)
    //transform each element to pair with number of words in it
    .Select(x => Tuple.Create(x, 1))
    // add counting logic to the streams
    .Sum((l, r) => Tuple.Create(l.Item1, l.Item2 + r.Item2))
    // get a stream of word counts
    .MergeSubstreams();
```

By extracting the parts specific to *wordcount* into

* a ``GroupKey`` function that defines the groups
* a ``Select`` map each element to value that is used by the reduce on the substream
* a ``Reduce`` function that does the actual reduction

we get a generalized version below:

```csharp
public Flow<TIn, Tuple<TKey, TOut>, NotUsed> ReduceByKey<TIn, TKey, TOut>(int maximumGroupSize,
    Func<TIn, TKey> groupKey,
    Func<TIn, TOut> map,
    Func<TOut, TOut, TOut> reduce)
{
    return (Flow<TIn, Tuple<TKey, TOut>, NotUsed>)
        Flow.Create<TIn>()
            .GroupBy(maximumGroupSize, groupKey)
            .Select(e => Tuple.Create(groupKey(e), map(e)))
            .Sum((l, r) => Tuple.Create(l.Item1, reduce(l.Item2, r.Item2)))
            .MergeSubstreams();
}

var counts = words.Via(ReduceByKey(MaximumDistinctWords,
    groupKey: (string word) => word,
    map: word => 1,
    reduce: (l, r) => l + r));
```

>**Note**<br/>
Please note that the reduce-by-key version we discussed above is sequential in reading the overall input stream,
in other words it is **NOT** a parallelization pattern like MapReduce and similar frameworks.

####Sorting elements to multiple groups with groupBy

**Situation:** The ``GroupBy`` operation strictly partitions incoming elements, each element belongs to exactly one group.
Sometimes we want to map elements into multiple groups simultaneously.

To achieve the desired result, we attack the problem in two steps:

* first, using a function ``TopicMapper`` that gives a list of topics (groups) a message belongs to, we transform our
  stream of ``Message`` to a stream of ``(Message, Topic)`` where for each topic the message belongs to a separate pair
  will be emitted. This is achieved by using ``SelectMany``
* Then we take this new stream of message topic pairs (containing a separate pair for each topic a given message
  belongs to) and feed it into GroupBy, using the topic as the group key.

```csharp
Func<Message, ImmutableHashSet<Topic>> topicMapper = ExtractTopics;
var elements = Source.Empty<Message>();
var messageAndTopic = elements.SelectMany(msg =>
{
    var topicsForMessage = topicMapper(msg);
    // Create a (Msg, Topic) pair for each of the topics
    // the message belongs to
    return topicsForMessage.Select(t => Tuple.Create(msg, t));
});

var multiGroups = messageAndTopic.GroupBy(2, tuple => tuple.Item2).Select(tuple =>
{
    var msg = tuple.Item1;
    var topic = tuple.Item2;

    // do what needs to be done
});
```

#Working with Graphs

In this collection we show recipes that use stream graph elements to achieve various goals.

####Triggering the flow of elements programmatically

**Situation:** Given a stream of elements we want to control the emission of those elements according to a trigger signal.
In other words, even if the stream would be able to flow (not being backpressured) we want to hold back elements until a
trigger signal arrives.

This recipe solves the problem by simply zipping the stream of ``Message`` elements with the stream of ``Trigger``
signals. Since ``Zip`` produces pairs, we simply map the output stream selecting the first element of the pair.

```csharp
var elements = Source.Empty<Message>();
var triggerSource = Source.Empty<Trigger>();
var sink = Sink.Ignore<Message>().MapMaterializedValue(_ => NotUsed.Instance);

var graph = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
    var zip = b.Add(new Zip<Message, Trigger>());

    b.From(elements).To(zip.In0);
    b.From(triggerSource).To(zip.In1);
    b.From(zip.Out).Via(Flow.Create<Tuple<Message, Trigger>>().Select(t => t.Item1)).To(sink);

    return ClosedShape.Instance;
}));
```

Alternatively, instead of using a ``Zip``, and then using ``Select`` to get the first element of the pairs, we can avoid
creating the pairs in the first place by using ``ZipWith`` which takes a two argument function to produce the output
element. If this function would return a pair of the two argument it would be exactly the behavior of ``Zip`` so
``ZipWith`` is a generalization of zipping.

```csharp
var graph = RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
    var zip = b.Add(ZipWith.Apply((Message msg, Trigger trigger) => msg));

    b.From(elements).To(zip.In0);
    b.From(triggerSource).To(zip.In1);
    b.From(zip.Out).To(sink);

    return ClosedShape.Instance;
}));
```

####Balancing jobs to a fixed pool of workers

**Situation:** Given a stream of jobs and a worker process expressed as a `Flow` create a pool of workers
that automatically balances incoming jobs to available workers, then merges the results.

We will express our solution as a function that takes a worker flow and the number of workers to be allocated and gives
a flow that internally contains a pool of these workers. To achieve the desired result we will create a `Flow`
from a graph.

The graph consists of a ``Balance`` node which is a special fan-out operation that tries to route elements to available
downstream consumers. In a ``for`` loop we wire all of our desired workers as outputs of this balancer element, then
we wire the outputs of these workers to a ``Merge`` element that will collect the results from the workers.

To make the worker stages run in parallel we mark them as asynchronous with `Async`.

```csharp
public Flow<TIn, TOut, NotUsed> Balancer<TIn, TOut>(Flow<TIn, TOut, NotUsed> worker, int workerCount)
{
    return Flow.FromGraph(GraphDsl.Create(b =>
    {
        var balancer = b.Add(new Balance<TIn>(workerCount, waitForAllDownstreams: true));
        var merge = b.Add(new Merge<TOut>(workerCount));

        for (var i = 0; i < workerCount; i++)
            b.From(balancer).Via(worker.Async()).To(merge);

        return new FlowShape<TIn, TOut>(balancer.In, merge.Out);
    }));
}

var myJobs = Source.Empty<Job>();
var worker = Flow.Create<Job>().Select(j => new Done(j));
var processedJobs = myJobs.Via(Balancer(worker, 3));
```

#Working with rate

This collection of recipes demonstrate various patterns where rate differences between upstream and downstream
needs to be handled by other strategies than simple backpressure.

####Dropping elements

**Situation:** Given a fast producer and a slow consumer, we want to drop elements if necessary to not slow down
the producer too much.

This can be solved by using a versatile rate-transforming operation, ``Conflate``. Conflate can be thought as
a special ``Sum`` operation that collapses multiple upstream elements into one aggregate element if needed to keep
the speed of the upstream unaffected by the downstream.

When the upstream is faster, the sum process of the ``Conflate`` starts. Our reducer function simply takes
the freshest element. This cin a simple dropping operation.

```csharp
var droppyStream = Flow.Create<Message>().Conflate((lastMessage, newMessage) => newMessage);
```

There is a more general version of ``Conflate`` named ``ConflateWithSeed`` that allows to express more complex aggregations, more
similar to a ``Aggregate``.

####Dropping broadcast

**Situation:** The default ``Broadcast`` graph element is properly backpressured, but that means that a slow downstream
consumer can hold back the other downstream consumers resulting in lowered throughput. In other words the rate of
``Broadcast`` is the rate of its slowest downstream consumer. In certain cases it is desirable to allow faster consumers
to progress independently of their slower siblings by dropping elements if necessary.

One solution to this problem is to append a ``Buffer`` element in front of all of the downstream consumers
defining a dropping strategy instead of the default ``Backpressure``. This allows small temporary rate differences
between the different consumers (the buffer smooths out small rate variances), but also allows faster consumers to
progress by dropping from the buffer of the slow consumers if necessary.

```csharp
var mysink1 = Sink.Ignore<int>();
var mysink2 = Sink.Ignore<int>();
var mysink3 = Sink.Ignore<int>();

var graph = RunnableGraph.FromGraph(GraphDsl.Create(mysink1, mysink2, mysink3, Tuple.Create,
    (builder, sink1, sink2, sink3) =>
    {
        var broadcast = builder.Add(new Broadcast<int>(3));

        builder.From(broadcast).Via(Flow.Create<int>().Buffer(10, OverflowStrategy.DropHead)).To(sink1);
        builder.From(broadcast).Via(Flow.Create<int>().Buffer(10, OverflowStrategy.DropHead)).To(sink2);
        builder.From(broadcast).Via(Flow.Create<int>().Buffer(10, OverflowStrategy.DropHead)).To(sink3);

        return ClosedShape.Instance;
    }));
```

####Collecting missed ticks

**Situation:** Given a regular (stream) source of ticks, instead of trying to backpressure the producer of the ticks
we want to keep a counter of the missed ticks instead and pass it down when possible.

We will use ``ConflateWithSeed`` to solve the problem. The seed version of conflate takes two functions:

* A seed function that produces the zero element for the folding process that happens when the upstream is faster than
  the downstream. In our case the seed function is a constant function that returns 0 since there were no missed ticks
  at that point.
* A fold function that is invoked when multiple upstream messages needs to be collapsed to an aggregate value due
  to the insufficient processing rate of the downstream. Our folding function simply increments the currently stored
  count of the missed ticks so far.

As a result, we have a flow of ``Int`` where the number represents the missed ticks. A number 0 means that we were
able to consume the tick fast enough (i.e. zero means: 1 non-missed tick + 0 missed ticks)

```csharp
var missed = Flow.Create<Tick>()
  .ConflateWithSeed(seed: _ => 0, aggregate: (missedTicks, tick) => missedTicks + 1);
```

####Create a stream processor that repeats the last element seen

**Situation:** Given a producer and consumer, where the rate of neither is known in advance, we want to ensure that none
of them is slowing down the other by dropping earlier unconsumed elements from the upstream if necessary, and repeating
the last value for the downstream if necessary.

We have two options to implement this feature. In both cases we will use `GraphStage` to build our custom
element. In the first version we will use a provided initial value ``initial`` that will be used
to feed the downstream if no upstream element is ready yet. In the ``onPush()`` handler we just overwrite the
``currentValue`` variable and immediately relieve the upstream by calling ``pull()``. The downstream ``onPull`` handler
is very similar, we immediately relieve the downstream by emitting ``currentValue``.

```csharp
public sealed class HoldWithInitial<T> : GraphStage<FlowShape<T, T>>
{
    private sealed class Logic : GraphStageLogic
    {
        private readonly HoldWithInitial<T> _holder;
        private T _currentValue;

        public Logic(HoldWithInitial<T> holder) : base(holder.Shape)
        {
            _holder = holder;
            _currentValue = holder._initial;

            SetHandler(holder.In, onPush: () =>
            {
                _currentValue = Grab(holder.In);
                Pull(holder.In);
            });

            SetHandler(holder.Out, onPull: () => Push(holder.Out, _currentValue));
        }

        public override void PreStart() => Pull(_holder.In);
    }

    private readonly T _initial;

    public HoldWithInitial(T initial)
    {
        _initial = initial;
        Shape = new FlowShape<T, T>(In, Out);
    }

    public Inlet<T> In { get; } = new Inlet<T>("HoldWithInitial.in");

    public Outlet<T> Out { get; } = new Outlet<T>("HoldWithInitial.out");

    public override FlowShape<T, T> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
```

While it is relatively simple, the drawback of the first version is that it needs an arbitrary initial element which is not
always possible to provide. Hence, we create a second version where the downstream might need to wait in one single
case: if the very first element is not yet available.

We introduce a boolean variable ``waitingFirstValue`` to denote whether the first element has been provided or not
(alternatively an `Option` can be used for ``currentValue`` or if the element type is a value type
a null can be used with the same purpose). In the downstream ``onPull()`` handler the difference from the previous
version is that we check if we have received the first value and only emit if we have. This leads to that when the
first element comes in we must check if there possibly already was demand from downstream so that we in that case can
push the element directly.

```csharp
public sealed class HoldWithWait<T> : GraphStage<FlowShape<T, T>>
{
    private sealed class Logic : GraphStageLogic
    {
        private readonly HoldWithWait<T> _holder;
        private T _currentValue;
        private bool _waitingFirstValue = true;

        public Logic(HoldWithWait<T> holder) : base(holder.Shape)
        {
            _holder = holder;

            SetHandler(holder.In, onPush: () =>
            {
                _currentValue = Grab(holder.In);
                if (_waitingFirstValue)
                {
                    _waitingFirstValue = false;
                    if(IsAvailable(holder.Out))
                        Push(holder.Out, _currentValue);
                }
                Pull(holder.In);
            });

            SetHandler(holder.Out, onPull: () =>
            {
                if(!_waitingFirstValue)
                    Push(holder.Out, _currentValue);
            });
        }

        public override void PreStart() => Pull(_holder.In);
    }

    public HoldWithWait()
    {
        Shape = new FlowShape<T, T>(In, Out);
    }

    public Inlet<T> In { get; } = new Inlet<T>("HoldWithWait.in");

    public Outlet<T> Out { get; } = new Outlet<T>("HoldWithWait.out");

    public override FlowShape<T, T> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}
```

####Globally limiting the rate of a set of streams

**Situation:** Given a set of independent streams that we cannot merge, we want to globally limit the aggregate
throughput of the set of streams.

One possible solution uses a shared actor as the global limiter combined with `SelectAsync` to create a reusable `Flow` that can be plugged into a stream to limit its rate.

As the first step we define an actor that will do the accounting for the global rate limit. The actor maintains
a timer, a counter for pending permit tokens and a queue for possibly waiting participants. The actor has
an ``open`` and ``closed`` state. The actor is in the ``open`` state while it has still pending permits. Whenever a
request for permit arrives as a ``WantToPass`` message to the actor the number of available permits is decremented
and we notify the sender that it can pass by answering with a ``MayPass`` message. If the amount of permits reaches
zero, the actor transitions to the ``closed`` state. In this state requests are not immediately answered, instead the reference
of the sender is added to a queue. Once the timer for replenishing the pending permits fires by sending a ``ReplenishTokens``
message, we increment the pending permits counter and send a reply to each of the waiting senders. If there are more
waiting senders than permits available we will stay in the ``closed`` state.

```csharp
public sealed class WantToPass
{
    public static readonly WantToPass Instance = new WantToPass();

    private WantToPass() { }
}

public sealed class MayPass
{
    public static readonly MayPass Instance = new MayPass();

    private MayPass() { }
}

public sealed class ReplenishTokens
{
    public static readonly ReplenishTokens Instance = new ReplenishTokens();

    private ReplenishTokens() { }
}

public class Limiter : ReceiveActor
{
    public static Props Props(int maxAvailableTokens, TimeSpan tokenRefreshPeriod, int tokenRefreshAmount)
        => Akka.Actor.Props.Create(() => new Limiter(maxAvailableTokens, tokenRefreshPeriod, tokenRefreshAmount));

    private readonly int _maxAvailableTokens;
    private readonly int _tokenRefreshAmount;
    private ImmutableList<IActorRef> _waitQueue;
    private int _permitTokens;
    private readonly ICancelable _replenishTimer;

    public Limiter(int maxAvailableTokens, TimeSpan tokenRefreshPeriod, int tokenRefreshAmount)
    {
        _maxAvailableTokens = maxAvailableTokens;
        _tokenRefreshAmount = tokenRefreshAmount;

        _waitQueue = ImmutableList.Create<IActorRef>();
        _permitTokens = maxAvailableTokens;
        _replenishTimer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(initialDelay: tokenRefreshPeriod,
            interval: tokenRefreshPeriod, receiver: Self, message: ReplenishTokens.Instance, sender: Nobody.Instance);

        Become(Open);
    }

    private void Open(object message)
    {
        message.Match()
            .With<ReplenishTokens>(() =>
            {
                _permitTokens = Math.Min(_permitTokens + _tokenRefreshAmount, _maxAvailableTokens);
            })
            .With<WantToPass>(() =>
            {
                _permitTokens--;
                Sender.Tell(MayPass.Instance);
                if(_permitTokens == 0)
                    Become(Closed);
            });
    }

    private void Closed(object message)
    {
        message.Match()
            .With<ReplenishTokens>(() =>
            {
                _permitTokens = Math.Min(_permitTokens + _tokenRefreshAmount, _maxAvailableTokens);
                ReleaseWaiting();
            })
            .With<WantToPass>(() =>
            {
                _waitQueue = _waitQueue.Add(Sender);
            });
    }

    private void ReleaseWaiting()
    {
        var toBeReleased = _waitQueue.GetRange(0, _permitTokens);
        _waitQueue = _waitQueue.RemoveRange(0, _permitTokens);
        _permitTokens -= toBeReleased.Count;
        toBeReleased.ForEach(s => s.Tell(MayPass.Instance));
        if(_permitTokens > 0)
            Become(Open);
    }

    protected override void PostStop()
    {
        _replenishTimer.Cancel();
        _waitQueue.ForEach(s => s.Tell(new Status.Failure(new IllegalStateException("Limiter stopped"))));
    }
}
```

To create a Flow that uses this global limiter actor we use the ``SelectAsync`` function with the combination of the ``Ask``
pattern. We also define a timeout, so if a reply is not received during the configured maximum wait period the returned
task from ``Ask`` will fail, which will fail the corresponding stream as well.

```csharp
public Flow<T, T, NotUsed> LimitGlobal<T>(IActorRef limiter, TimeSpan maxAllowedWait)
  => Flow.Create<T>().SelectAsync(4, element =>
  {
      var limiterTriggerTask = limiter.Ask<T>(WantToPass.Instance, maxAllowedWait);
      return limiterTriggerTask.ContinueWith(t => element);
  });
```

>**Note**<br/>
  The global actor used for limiting introduces a global bottleneck. You might want to assign a dedicated dispatcher
  for this actor.

#Working with IO

####Chunking up a stream of ByteStrings into limited size ByteStrings

**Situation:** Given a stream of ByteStrings we want to produce a stream of ByteStrings containing the same bytes in
the same sequence, but capping the size of ByteStrings. In other words we want to slice up ByteStrings into smaller
chunks if they exceed a size threshold.

This can be achieved with a single `GraphStage`. The main logic of our stage is in ``emitChunk()`` which implements the following logic:

* if the buffer is empty, and upstream is not closed we pull for more bytes, if it is closed we complete
* if the buffer is nonEmpty, we split it according to the ``chunkSize``. This will give a next chunk that we will emit,
  and an empty or non-empty remaining buffer.

Both ``onPush()`` and ``onPull()`` calls ``emitChunk()`` the only difference is that the push handler also stores
the incoming chunk by appending to the end of the buffer.

```csharp
public class Chunker : GraphStage<FlowShape<ByteString, ByteString>>
{
    private sealed class Logic : GraphStageLogic
    {
        private readonly Chunker _chunker;
        private ByteString _buffer = ByteString.Empty;

        public Logic(Chunker chunker) : base(chunker.Shape)
        {
            _chunker = chunker;

            SetHandler(chunker.Out, onPull: () =>
            {
                if (IsClosed(chunker.In))
                    EmitChunk();
                else
                    Pull(chunker.In);
            });

            SetHandler(chunker.In, onPush: () =>
            {
                var element = Grab(chunker.In);
                _buffer += element;
                EmitChunk();
            }, onUpstreamFinish: () =>
            {
                if(_buffer.IsEmpty)
                    CompleteStage();
                // elements left in buffer, keep accepting downstream pulls
                // and push from buffer until buffer is emitted
            });
        }

        private void EmitChunk()
        {
            if (_buffer.IsEmpty)
            {
                if (IsClosed(_chunker.In))
                    CompleteStage();
                else
                    Pull(_chunker.In);
            }
            else
            {
                var t = _buffer.SplitAt(_chunker._chunkSize);
                var chunk = t.Item1;
                var nextBuffer = t.Item2;

                _buffer = nextBuffer;
                Push(_chunker.Out, chunk);
            }
        }
    }

    private readonly int _chunkSize;

    public Chunker(int chunkSize)
    {
        _chunkSize = chunkSize;
        Shape = new FlowShape<ByteString, ByteString>(In, Out);
    }

    public Inlet<ByteString> In { get; }= new Inlet<ByteString>("Chunker.in");

    public Outlet<ByteString> Out { get; } = new Outlet<ByteString>("Chunker.out");

    public override FlowShape<ByteString, ByteString> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}

var rawBytes = Source.Empty<ByteString>();
var chunkStream = rawBytes.Via(new Chunker(ChunkLimit));
```

####Limit the number of bytes passing through a stream of ByteStrings

**Situation:** Given a stream of ByteStrings we want to fail the stream if more than a given maximum of bytes has been
consumed.

This recipe uses a `GraphStage` to implement the desired feature. In the only handler we override,
``onPush()`` we just update a counter and see if it gets larger than ``maximumBytes``. If a violation happens
we signal failure, otherwise we forward the chunk we have received.

```csharp
public class ByteLimiter : GraphStage<FlowShape<ByteString, ByteString>>
{
    private sealed class Logic : GraphStageLogic
    {
        private long _count;

        public Logic(ByteLimiter limiter) : base(limiter.Shape)
        {
            SetHandler(limiter.In, onPush: () =>
            {
                var chunk = Grab(limiter.In);
                _count += chunk.Count;
                if (_count > limiter._maximumBytes)
                    FailStage(new IllegalStateException("Too much bytes"));
                else
                    Push(limiter.Out, chunk);
            });

            SetHandler(limiter.Out, onPull: () => Pull(limiter.In));
        }
    }

    private readonly long _maximumBytes;

    public ByteLimiter(long maximumBytes)
    {
        _maximumBytes = maximumBytes;
        Shape = new FlowShape<ByteString, ByteString>(In, Out);
    }

    public Inlet<ByteString> In { get; } = new Inlet<ByteString>("ByteLimiter.in");

    public Outlet<ByteString> Out { get; } = new Outlet<ByteString>("ByteLimiter.out");

    public override FlowShape<ByteString, ByteString> Shape { get; }

    protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this);
}

var limiter = Flow.Create<ByteString>().Via(new ByteLimiter(SizeLimit));
```

####Compact ByteStrings in a stream of ByteStrings

**Situation:** After a long stream of transformations, due to their immutable, structural sharing nature ByteStrings may
refer to multiple original ByteString instances unnecessarily retaining memory. As the final step of a transformation
chain we want to have clean copies that are no longer referencing the original ByteStrings.

The recipe is a simple use of Select, calling the ``Compact()`` method of the `ByteString` elements. This does
copying of the underlying arrays, so this should be the last element of a long chain if used.

```csharp
var data = Source.Empty<ByteString>();
var compacted = data.Select(b => b.Compact());
```

####Injecting keep-alive messages into a stream of ByteStrings

**Situation:** Given a communication channel expressed as a stream of ByteStrings we want to inject keep-alive messages
but only if this does not interfere with normal traffic.

There is a built-in operation that allows to do this directly:

```csharp
var injectKeepAlive = Flow.Create<ByteString>().KeepAlive(TimeSpan.FromSeconds(1), () => keepAliveMessage);
```


text:
class T6476118c {
    static class A<T> {
        public void foo(T t) { }
    }

    static class B<T extends Number> extends A<T> {
        public void foo(T t) { }
    }

    static class C extends B<Integer> {
        public void foo(Object o) { }
        public void foo(Number o) { }
    }

    static class D extends C {} //check that no spurious diags generated here!
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Exoascus cerasi-microcarpae Kuschke

### Remarks
null


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (4 ways to jumpstart productivity at work)
[#]: via: (https://opensource.com/article/19/3/guide-being-more-productive)
[#]: author: (Sarah Wall https://opensource.com/users/sarahwall)

4 ways to jumpstart productivity at work
======

This article includes six open source productivity tools.

![][1]

Time poverty—the idea that there's not enough time to do all the work we need to do—is it a perception or a reality?

The truth is you'll never get more than 24 hours out of any day. Working longer hours doesn't help. Your productivity actually decreases the longer you work in a given day. Your perception, or intuitive understanding of your time, is what matters. One key to managing productivity is how you use the time you've got.

You have lots of time that you can use more efficiently, including time lost to ineffective meetings, distractions, and context switching between tasks. By spending your time more wisely, you can get more done and achieve higher overall job performance. You will also have a higher level of job satisfaction and feel lower levels of stress.

### Jumpstart your productivity

#### 1\. Eliminate distractions

When you have too many things vying for your attention, it slows you down and decreases your productivity. Do your best to remove every distraction that pulls you off tasks.

Cellphones, email, and messaging apps are the most common drains on productivity. Set the ringer on your phone to vibrate, set specific times for checking email, and close irrelevant browser tabs. With this approach, your work will be interrupted less throughout the day.

#### 2\. Make your to-do list _verb-oriented_

To-do lists are a great way to help you focus on exactly what you need to accomplish each day. Some people do best with a physical list, like a notebook, and others do better with digital tools. Check out these suggestions for [open source productivity tools][2] to help you manage your workflow. Or check these six open source tools to stay organized:

  * [Joplin, a note-taking app][3]
  * [Wekan, an open source kanban board][4]
  * [TaskBoard, a lightweight kanban board][5]
  * [Go For It, a flexible to-do list application][6]
  * [Org mode without Emacs][7]
  * [Freeplane, an open source mind-mapping application][8]

Your list can be as sophisticated or as simple as you like, but just making a list is not enough. What goes on your list makes all the difference. Every item that goes on your list should be actionable. The trick is to make sure there's a verb. For example, "Smith project" is not actionable enough. "Outline key deliverables on Smith project" gives you a more concrete task to complete.

#### 3\. Stick to the 10-minute rule

Overwhelmed by an unclear or unwieldy task? Break it into 10-minute mini-tasks instead. This can be a great way to take something unmanageable and turn it into something achievable.

The beauty of 10-minute tasks is they can be fit into many parts of your day. When you get into the office in the morning and are feeling fresh, kick off your day with a burst of productivity with a few 10-minute tasks. Losing momentum in the afternoon? A 10-minute job can help you regain speed.

Ten-minute tasks are also a good way to identify tasks that can be delegated to others. The ability to delegate work is often one of the most effective management techniques. By finding a simple task that can be accomplished by another member of your team, you can make short work of a big job.

#### 4\. Take a break

Another drain on productivity is the urge to keep pressing ahead on a task to complete it without taking a break. Suddenly you feel really fatigued or hungry, and you realize you haven't gone to the bathroom in hours! Your concentration is affected, and therefore your productivity decreases.

Set benchmarks for taking breaks and stick to them. For example, commit to once per hour to get up and move around for five minutes. If you're pressed for time, stand up and stretch for two minutes. Changing your body position and focusing on the present moment will help relieve any mental tension that has built up.

Hydrate your mind with a glass of water. When your body is not properly hydrated, it can put increased stress on your brain. As little as a one to three percent decrease in hydration can negatively affect your memory, concentration, and decision-making.

### Don't fall into the time-poverty trap

Time is limited and time poverty is just an idea. How you choose to spend the time you have each day is what's important. When you develop new, healthy habits, you can increase your productivity and direct your time in the ways that give the most value.

* * *

_This article was adapted from "[The Keys to Productivity][9]" on ImageX's blog._

_Sarah Wall will present_ [_Mindless multitasking: a dummy's guide to productivity_][10], _at_ [_DrupalCon_][11] _in Seattle, April 8-12, 2019._

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

via: https://opensource.com/article/19/3/guide-being-more-productive

作者:[Sarah Wall][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://opensource.com/users/sarahwall
[b]: https://github.com/lujun9972
[1]: https://opensource.com/sites/default/files/styles/image-full-size/public/lead-images/rh_commun_4604_02_mech_connections_rhcz0.5x.png?itok=YPPU4dMj
[2]: https://opensource.com/article/16/11/open-source-productivity-hacks
[3]: https://opensource.com/article/19/1/productivity-tool-joplin
[4]: https://opensource.com/article/19/1/productivity-tool-wekan
[5]: https://opensource.com/article/19/1/productivity-tool-taskboard
[6]: https://opensource.com/article/19/1/productivity-tool-go-for-it
[7]: https://opensource.com/article/19/1/productivity-tool-org-mode
[8]: https://opensource.com/article/19/1/productivity-tool-freeplane
[9]: https://imagexmedia.com/managing-productivity
[10]: https://events.drupal.org/seattle2019/sessions/mindless-multitasking-dummy%E2%80%99s-guide-productivity
[11]: https://events.drupal.org/seattle2019