text:
/*  WinUSBNet library
 *  (C) 2010 Thomas Bleeker (www.madwizard.org)
 *
 *  Licensed under the MIT license, see license.txt or:
 *  http://www.opensource.org/licenses/mit-license.php
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace MadWizard.WinUSBNet
{
    /// <summary>
    /// UsbPipe represents a single pipe on a WinUSB device. A pipe is connected
    /// to a certain endpoint on the device and has a fixed direction (IN or OUT)
    /// </summary>
    public class USBPipe
    {
        private API.WINUSB_PIPE_INFORMATION _pipeInfo;
        private USBInterface _interface = null;
        private USBDevice _device;
        private USBPipePolicy _policy;

        /// <summary>
        /// Endpoint address including the direction in the most significant bit
        /// </summary>
        public byte Address
        {
            get
            {
                return _pipeInfo.PipeId;
            }
        }

        /// <summary>
        /// The USBDevice this pipe is associated with
        /// </summary>
        public USBDevice Device
        {
            get
            {
                return _device;
            }
        }

        /// <summary>
        /// Maximum packet size for transfers on this endpoint
        /// </summary>
        public int MaximumPacketSize
        {
            get
            {
                return _pipeInfo.MaximumPacketSize;
            }
        }

        /// <summary>
        /// The interface associated with this pipe
        /// </summary>
        public USBInterface Interface
        {
            get
            {
                return _interface;
            }
        }

        /// <summary>
        /// The pipe policy settings for this pipe
        /// </summary>
        public USBPipePolicy Policy
        {
            get
            {
                return _policy;
            }
        }

        /// <summary>
        /// True if the pipe has direction OUT (host to device), false otherwise.
        /// </summary>
        public bool IsOut
        {
            get
            {
                return (_pipeInfo.PipeId & 0x80) == 0;
            }
        }

        /// <summary>
        /// True if the pipe has direction IN (device to host), false otherwise.
        /// </summary>
        public bool IsIn
        {
            get
            {
                return (_pipeInfo.PipeId & 0x80) != 0;
            }
        }

        /// <summary>
        /// Reads data from the pipe into a buffer.
        /// </summary>
        /// <param name="buffer">The buffer to read data into. The maximum number of bytes that will be read is specified by the length of the buffer.</param>
        /// <returns>The number of bytes read from the pipe.</returns>
        public int Read(byte[] buffer)
        {
            return Read(buffer, 0, buffer.Length);
        }

        /// <summary>
        /// Reads data from the pipe into a buffer.
        /// </summary>
        /// <param name="buffer">The buffer to read data into.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer"/> from which to begin writing data read from the pipe.</param>
        /// <param name="length">The maximum number of bytes to read, starting at offset</param>
        /// <returns>The number of bytes read from the pipe.</returns>
        public int Read(byte[] buffer, int offset, int length)
        {
            CheckReadParams(buffer, offset, length);

            try
            {
                uint bytesRead;

                _device.InternalDevice.ReadPipe(Interface.InterfaceIndex, _pipeInfo.PipeId, buffer, offset, length, out bytesRead);

                return (int)bytesRead;
            }
            catch (API.APIException e)
            {
                throw new USBException("Failed to read from pipe.", e);
            }
        }

        private void CheckReadParams(byte[] buffer, int offset, int length)
        {
            if (!IsIn)
                throw new NotSupportedException("Cannot read from a pipe with OUT direction.");

            int bufferLength = buffer.Length;
            if (offset < 0 || offset >= bufferLength)
                throw new ArgumentOutOfRangeException("Offset of data to read is outside the buffer boundaries.");
            if (length < 0 || (offset + length) > bufferLength)
                throw new ArgumentOutOfRangeException("Length of data to read is outside the buffer boundaries.");
        }
        private void CheckWriteParams(byte[] buffer, int offset, int length)
        {
            if (!IsOut)
                throw new NotSupportedException("Cannot write to a pipe with IN direction.");

            int bufferLength = buffer.Length;
            if (offset < 0 || offset >= bufferLength)
                throw new ArgumentOutOfRangeException("Offset of data to write is outside the buffer boundaries.");
            if (length < 0 || (offset + length) > bufferLength)
                throw new ArgumentOutOfRangeException("Length of data to write is outside the buffer boundaries.");

        }

        /// <summary>Initiates an asynchronous read operation on the pipe. </summary>
        /// <param name="buffer">Buffer that will receive the data read from the pipe.</param>
        /// <param name="offset">Byte offset within the buffer at which to begin writing the data received.</param>
        /// <param name="length">Length of the data to transfer.</param>
        /// <param name="userCallback">An optional asynchronous callback, to be called when the operation is complete. Can be null if no callback is required.</param>
        /// <param name="stateObject">A user-provided object that distinguishes this particular asynchronous operation. Can be null if not required.</param>
        /// <returns>An <see cref="IAsyncResult"/> object repesenting the asynchronous operation, which could still be pending.</returns>
        /// <remarks>This method always completes immediately even if the operation is still pending. The <see cref="IAsyncResult"/> object returned represents the operation
        /// and must be passed to <see cref="EndRead"/> to retrieve the result of the operation. For every call to this method a matching call to
        /// <see cref="EndRead"/> must be made. When <paramref name="userCallback"/> specifies a callback function, this function will be called when the operation is completed. The optional
        /// <paramref name="stateObject"/> parameter can be used to pass user-defined information to this callback or the <see cref="IAsyncResult"/>. The <see cref="IAsyncResult"/>
        /// also provides an event handle (<see cref="IAsyncResult.AsyncWaitHandle" />) that will be triggered when the operation is complete as well.
        /// </remarks>
        public IAsyncResult BeginRead(byte[] buffer, int offset, int length, AsyncCallback userCallback, object stateObject)
        {
            CheckReadParams(buffer, offset, length);

            USBAsyncResult result = new USBAsyncResult(userCallback, stateObject);
            try
            {
                _device.InternalDevice.ReadPipeOverlapped(Interface.InterfaceIndex, _pipeInfo.PipeId, buffer, offset, length, result);
            }
            catch (API.APIException e)
            {
                if (result != null)
                    result.Dispose();
                throw new USBException("Failed to read from pipe.", e);
            }
            catch (Exception)
            {
                if (result != null)
                    result.Dispose();
                throw;
            }
            return result;
        }

        /// <summary>
        /// Waits for a pending asynchronous read operation to complete.
        /// </summary>
        /// <param name="asyncResult">The <see cref="IAsyncResult"/> object representing the asynchonous operation,
        /// as returned by <see cref="BeginRead"/>.</param>
        /// <returns>The number of bytes transfered during the operation.</returns>
        /// <remarks>Every call to <see cref="BeginRead"/> must have a matching call to <see cref="EndRead"/> to dispose
        /// of any resources used and to retrieve the result of the operation. When the operation was successful the method returns the number
        /// of bytes that were transfered. If an error occurred during the operation this method will throw the exceptions that would
        /// otherwise have ocurred during the operation. If the operation is not yet finished EndWrite will wait for the
        /// operation to finish before returning.</remarks>
        public int EndRead(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
                throw new NullReferenceException("asyncResult cannot be null");
            if (!(asyncResult is USBAsyncResult))
                throw new ArgumentException("AsyncResult object was not created by calling BeginRead on this class.");

            // todo: check duplicate end reads?
            USBAsyncResult result = (USBAsyncResult)asyncResult;
            try
            {
                if (!result.IsCompleted)
                    result.AsyncWaitHandle.WaitOne();

                if (result.Error != null)
                    throw new USBException("Asynchronous read from pipe has failed.", result.Error);

                return result.BytesTransfered;
            }
            finally
            {
                result.Dispose();
            }

        }

        /// <summary>
        /// Writes data from a buffer to the pipe.
        /// </summary>
        /// <param name="buffer">The buffer to write data from. The complete buffer will be written to the device.</param>
        public void Write(byte[] buffer)
        {
            Write(buffer, 0, buffer.Length);
        }

        /// <summary>
        /// Writes data from a buffer to the pipe.
        /// </summary>
        /// <param name="buffer">The buffer to write data from.</param>
        /// <param name="offset">The byte offset in <paramref name="buffer"/> from which to begin writing.</param>
        /// <param name="length">The number of bytes to write, starting at offset</param>
        public void Write(byte[] buffer, int offset, int length)
        {
            CheckWriteParams(buffer, offset, length);

            try
            {
                _device.InternalDevice.WritePipe(Interface.InterfaceIndex, _pipeInfo.PipeId, buffer, offset, length);
            }
            catch (API.APIException e)
            {
                throw new USBException("Failed to write to pipe.", e);
            }
        }

        /// <summary>Initiates an asynchronous write operation on the pipe. </summary>
        /// <param name="buffer">Buffer that contains the data to write to the pipe.</param>
        /// <param name="offset">Byte offset within the buffer from which to begin writing.</param>
        /// <param name="length">Length of the data to transfer.</param>
        /// <param name="userCallback">An optional asynchronous callback, to be called when the operation is complete. Can be null if no callback is required.</param>
        /// <param name="stateObject">A user-provided object that distinguishes this particular asynchronous operation. Can be null if not required.</param>
        /// <returns>An <see cref="IAsyncResult"/> object repesenting the asynchronous operation, which could still be pending.</returns>
        /// <remarks>This method always completes immediately even if the operation is still pending. The <see cref="IAsyncResult"/> object returned represents the operation
        /// and must be passed to <see cref="EndWrite"/> to retrieve the result of the operation. For every call to this method a matching call to
        /// <see cref="EndWrite"/> must be made. When <paramref name="userCallback"/> specifies a callback function, this function will be called when the operation is completed. The optional
        /// <paramref name="stateObject"/> parameter can be used to pass user-defined information to this callback or the <see cref="IAsyncResult"/>. The <see cref="IAsyncResult"/>
        /// also provides an event handle (<see cref="IAsyncResult.AsyncWaitHandle" />) that will be triggered when the operation is complete as well.
        /// </remarks>
        public IAsyncResult BeginWrite(byte[] buffer, int offset, int length, AsyncCallback userCallback, object stateObject)
        {
            CheckWriteParams(buffer, offset, length);

            USBAsyncResult result = new USBAsyncResult(userCallback, stateObject);
            try
            {
                _device.InternalDevice.WriteOverlapped(Interface.InterfaceIndex, _pipeInfo.PipeId, buffer, offset, length, result);
            }
            catch (API.APIException e)
            {
                if (result != null)
                    result.Dispose();
                throw new USBException("Failed to write to pipe.", e);
            }
            catch (Exception)
            {
                if (result != null)
                    result.Dispose();
                throw;
            }
            return result;
        }

        /// <summary>
        /// Waits for a pending asynchronous write operation to complete.
        /// </summary>
        /// <param name="asyncResult">The <see cref="IAsyncResult"/> object representing the asynchonous operation,
        /// as returned by <see cref="BeginWrite"/>.</param>
        /// <returns>The number of bytes transfered during the operation.</returns>
        /// <remarks>Every call to <see cref="BeginWrite"/> must have a matching call to <see cref="EndWrite"/> to dispose
        /// of any resources used and to retrieve the result of the operation. When the operation was successful the method returns the number
        /// of bytes that were transfered. If an error occurred during the operation this method will throw the exceptions that would
        /// otherwise have ocurred during the operation. If the operation is not yet finished EndWrite will wait for the
        /// operation to finish before returning.</remarks>
        public void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
                throw new NullReferenceException("asyncResult cannot be null");
            if (!(asyncResult is USBAsyncResult))
                throw new ArgumentException("AsyncResult object was not created by calling BeginWrite on this class.");

            USBAsyncResult result = (USBAsyncResult)asyncResult;
            try
            {
                // todo: check duplicate end writes?

                if (!result.IsCompleted)
                    result.AsyncWaitHandle.WaitOne();

                if (result.Error != null)
                    throw new USBException("Asynchronous write to pipe has failed.", result.Error);
            }
            finally
            {
                result.Dispose();
            }
        }

        /// <summary>
        /// Aborts all pending transfers for this pipe.
        /// </summary>
        public void Abort()
        {
            try
            {
                _device.InternalDevice.AbortPipe(Interface.InterfaceIndex, _pipeInfo.PipeId);
            }
            catch (API.APIException e)
            {
                throw new USBException("Failed to abort pipe.", e);
            }
        }

        /// <summary>
        /// Flushes the pipe, discarding any data that is cached. Only available on IN direction pipes.
        /// </summary>
        public void Flush()
        {
            if (!IsIn)
                throw new NotSupportedException("Flush is only supported on IN direction pipes");
            try
            {
                _device.InternalDevice.FlushPipe(Interface.InterfaceIndex, _pipeInfo.PipeId);
            }
            catch (API.APIException e)
            {
                throw new USBException("Failed to flush pipe.", e);
            }
        }

        internal USBPipe(USBDevice device, API.WINUSB_PIPE_INFORMATION pipeInfo)
        {
            _pipeInfo = pipeInfo;
            _device = device;

            // Policy is not set until interface is attached
            _policy = null;
        }

        internal void AttachInterface(USBInterface usbInterface)
        {
            _interface = usbInterface;

            // Initialize policy now that interface is set (policy requires interface)
            _policy = new USBPipePolicy(_device, _interface.InterfaceIndex, _pipeInfo.PipeId);
        }

    }

}


text:
package com.kalestenika.backend.data;

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.kalestenika.backend.Constants.Rank;
import lombok.Data;

import java.util.Date;

/**
 * Entity representing a (completed) session of a particular workout
 */
@Entity
@Data
public class Session {

    @Id Long id;
    /**
     * The user that did the workout
     */
    @Index String userId;
    /**
     * Workout completed in the session.
     */
    @Index Long workoutId;
    /**
     * Date and time when the workout was done.
     */
    Date when = new Date();
    /**
     * Store the ID of the place where the workout was done.
     */
    Long where;
    /**
     * Vote given by the user on her session performances.
     */
    Rank vote;
    /**
     * Duration of session
     */
    Integer duration;
    /**
     * Percentage of completion
     */
    Integer completion;

}

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <string name="app_name">android-ddp</string>
</resources>


text:
.class final Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$Aborter;
.super Ljava/lang/Object;
.source "HdmiCecStandbyModeHandler.java"

# interfaces
.implements Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$CecMessageHandler;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "Aborter"
.end annotation

# instance fields
.field private final mReason:I

.field final synthetic this$0:Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;

# direct methods
.method public constructor <init>(Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;I)V
    .locals 0
    .param p2, "reason"    # I

    .prologue
    .line 46
    iput-object p1, p0, Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$Aborter;->this$0:Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;

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

    .line 47
    iput p2, p0, Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$Aborter;->mReason:I

    .line 48
    return-void
.end method

# virtual methods
.method public handle(Lcom/android/server/hdmi/HdmiCecMessage;)Z
    .locals 2
    .param p1, "message"    # Lcom/android/server/hdmi/HdmiCecMessage;

    .prologue
    .line 51
    iget-object v0, p0, Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$Aborter;->this$0:Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;

    # getter for: Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;->mService:Lcom/android/server/hdmi/HdmiControlService;
    invoke-static {v0}, Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;->access$000(Lcom/android/server/hdmi/HdmiCecStandbyModeHandler;)Lcom/android/server/hdmi/HdmiControlService;

    move-result-object v0

    iget v1, p0, Lcom/android/server/hdmi/HdmiCecStandbyModeHandler$Aborter;->mReason:I

    invoke-virtual {v0, p1, v1}, Lcom/android/server/hdmi/HdmiControlService;->maySendFeatureAbortCommand(Lcom/android/server/hdmi/HdmiCecMessage;I)V

    .line 52
    const/4 v0, 0x1

    return v0
.end method


text:
import os
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

from terml.nodes import Term, coerceToTerm, termMaker as t

HERE = os.path.dirname(__file__)

def writeBytecode(expr):
    print("Gonna compile %s" % (expr,))
    from ometa.grammar import TreeTransformerGrammar
    from ometa.runtime import TreeTransformerBase
    path = os.path.join(HERE, 'vm.parsley')
    Compiler = TreeTransformerGrammar.makeGrammar(open(path).read(),
            "Compiler").createParserClass(TreeTransformerBase, {"t": t})
    return Compiler.transform(expr)[0]

def bytecodeToPython(expr):
    print("Gonna emit %s" % (expr,))
    from ometa.grammar import TreeTransformerGrammar
    from ometa.runtime import TreeTransformerBase
    Emitter = TreeTransformerGrammar.makeGrammar(open("ometa/vm_emit.parsley").read(),
            "Emitter").createParserClass(TreeTransformerBase, {"t": t})
    return Emitter.transform(expr)[0]

def writeBytecodeRule(expr):
    e = GrammarEmitter()
    p = PythonWriter(expr)
    p.output(e)
    return list(e.rules.items())[0]

def writeBytecodeGrammar(expr):
    e = GrammarEmitter()
    p = PythonWriter(expr)
    p.output(e)
    return e.rules

class GrammarEmitter(object):
    def __init__(self):
        self.rules = {}
        self.tree = False

    def emitterForRule(self, name):
        e = Emitter()
        self.rules[name] = e.instrs
        return e

class Emitter(object):

    def __init__(self):
        self.instrs = []

    def emit(self, i, label=None):
        self.instrs.append(i)
        if label is not None:
            self.backpatch(label, len(self.instrs) - 1)
        return len(self.instrs) - 1

    def backpatch(self, fromIdx, toIdx):
        old = self.instrs[fromIdx]
        self.instrs[fromIdx] = Term(old.tag, None, [coerceToTerm(toIdx)])

    def patchNext(self, target):
        self.backpatch(target, len(self.instrs))

class PythonWriter(object):
    """
    Converts an OMeta syntax tree into Python source.
    """
    def __init__(self, tree):
        self.tree = tree

    def output(self, out):
        self._generateNode(out, self.tree)

    def _generateNode(self, out, node, debugname=None):
        name = node.tag.name
        args = node.args
        if node.data is not None:
            out.emit(t.Literal(node.data))
            return
        if name == 'null':
            out.emit(t.Python("None"))
        return getattr(self, "generate_"+name)(out, *args, debugname=debugname)

    def generate_Rule(self, out, name, expr, debugname=None):
        e = out.emitterForRule(name.data)
        self._generateNode(e, expr, name.data)

    def generate_Grammar(self, out, name, takesTreeInput, rules,
                         debugname=None):
        for rule in rules.args:
            self._generateNode(out, rule, debugname)
        out.tree = takesTreeInput

    def generate_Apply(self, out, ruleName, codeName, rawArgs, debugname=None):
        for arg in rawArgs.args:
            self._generateNode(out, arg, debugname)
            out.emit(t.Push())
        if ruleName.data == "super":
            out.emit(t.SuperCall(codeName))
        else:
            out.emit(t.Call(ruleName))

    def generate_ForeignApply(self, out, grammarName, ruleName, codeName,
                              rawArgs, debugname=None):
        for arg in rawArgs.args:
            self._generateNode(out, arg, debugname)
            out.emit(t.Push())
        out.emit(t.ForeignCall(grammarName, ruleName))

    def generate_Exactly(self, out, literal, debugname=None):
        out.emit(t.Match(literal.data))

    def generate_Token(self, out, literal, debugname=None):
        self.generate_Exactly(out, literal)

    def generate_Many(self, out, expr, debugname=None):
        L = out.emit(t.Choice())
        self._generateNode(out, expr, debugname)
        L2 = out.emit(t.Commit())
        out.patchNext(L)
        out.backpatch(L2, L)

    def generate_Many1(self, out, expr, debugname=None):
        self._generateNode(out, expr, debugname)
        self.generate_Many(out, expr, debugname)

    def generate_Repeat(self, out, min, max, expr, debugname=None):
        out.emit(t.Python(str(min.data)))
        out.emit(t.Push())
        out.emit(t.Python(str(max.data)))
        out.emit(t.Push())
        L = out.emit(t.RepeatChoice())
        self._generateNode(out, expr, debugname)
        L2 = out.emit(t.Commit())
        out.patchNext(L)
        out.backpatch(L2, L)

    def generate_Optional(self, out, expr, debugname=None):
        """
        Try to parse an expr and continue if it fails.
        """
        L = out.emit(t.Choice())
        self._generateNode(out, expr, debugname)
        L2 = out.emit(t.Commit())
        out.emit(t.Python("None"), label=L)
        out.patchNext(L2)

    def generate_Or(self, out, exprs, debugname=None):
        if len(exprs.args) == 1:
            self._generateNode(out, exprs.args[0])
            return
        L = None
        lcs = []
        for ex in exprs.args[:-1]:
            L = out.emit(t.Choice(), label=L)
            self._generateNode(out, ex)
            lcs.append(out.emit(t.Commit()))
        out.patchNext(L)
        self._generateNode(out, exprs.args[-1])
        for LC in lcs:
            out.patchNext(LC)

    def generate_Not(self, out, expr, debugname=None):
        L1 = out.emit(t.Choice())
        self._generateNode(out, expr)
        L2 = out.emit(t.Commit())
        out.emit(t.Fail(), label=L1)
        out.patchNext(L2)

    def generate_Lookahead(self, out, expr, debugname=None):
        L1 = out.emit(t.Choice())
        L2 = out.emit(t.Choice())
        self._generateNode(out, expr)
        L3 = out.emit(t.Commit(), label=L2)
        out.emit(t.Fail(), label=L3)
        out.patchNext(L1)

    def generate_And(self, out, exprs, debugname=None):
        for ex in exprs.args:
            self._generateNode(out, ex)

    def generate_Bind(self, out, name, expr, debugname=None):
        self._generateNode(out, expr)
        out.emit(t.Bind(name))

    def generate_Predicate(self, out, expr, debugname=None):
        self._generateNode(out, expr)
        out.emit(t.Predicate())

    def generate_Action(self, out, expr, debugname=None):
        out.emit(t.Python(expr.data))

    def generate_Python(self, out, expr, debugname=None):
        out.emit(t.Python(expr.data))

    def generate_List(self, out, expr, debugname=None):
        out.emit(t.Descend())
        self._generateNode(out, expr)
        out.emit(t.Ascend())

    def generate_TermPattern(self, out, name, expr, debugname=None):
        raise NotImplementedError()

    def generate_StringTemplate(self, out, template, debugname=None):
        raise NotImplementedError()

    def generate_ConsumedBy(self, out, expr, debugname=None):
        out.emit(t.StartSlice())
        self._generateNode(out, expr, debugname)
        out.emit(t.EndSlice())


text:
package com.njnu.kai.practice.recycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * @author kai
 * @since 17/1/15
 */
public abstract class OnLoadMoreScrollListener extends RecyclerView.OnScrollListener {

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int visibleItemCount = layoutManager.getChildCount();

        boolean triggerCondition = visibleItemCount > 0
                && newState == RecyclerView.SCROLL_STATE_IDLE
                && canTriggerLoadMore(recyclerView);

        if (triggerCondition) {
            onLoadMore(recyclerView);
        }
    }

    public boolean canTriggerLoadMore(RecyclerView recyclerView) {
        View lastChild = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
        int position = recyclerView.getChildLayoutPosition(lastChild);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int totalItemCount = layoutManager.getItemCount();
        return totalItemCount - 1 == position;
    }

    public abstract void onLoadMore(RecyclerView recyclerView);
}


text:
from collections import defaultdict

from django_db_sanitizer.updaters.base import BaseUpdater
from django_db_sanitizer.utils import pg_bulk_update

class BatchMultiValuePostgresUpdater(BaseUpdater):
    """Use this updater if you use Postgres and have a very large update where
    all rows of all fields may receive different values.
    """

    update_batch_size = 10000

    def update(self):
        """Iterates through the queryset and updates all fields found in
        `fields_to_sanitize` in different batches of a size configurable with
        `update_batch_size`. There will be one update database query for
        each field from `fields_to_sanitize` per batch.
        """
        update_dict = defaultdict(dict)
        for i, values_row in enumerate(self.item_list.iterator(), 1):
            for field_name in self.fields_to_sanitize:
                field_value = values_row[field_name]
                sanitized_value = self.sanitizer.execute(
                    values_row, field_name, field_value)

                pk_value = values_row[self.model_pk_field]
                update_dict[field_name][pk_value] = sanitized_value

            if i % self.update_batch_size == 0:
                for field_name in self.fields_to_sanitize:
                    filter_data = list(update_dict[field_name].keys())
                    update_data = list(update_dict[field_name].values())

                    # One query per field per batch
                    pg_bulk_update(self.model_class, self.model_pk_field,
                                   field_name, filter_data, update_data)
                # New batch
                update_dict = defaultdict(dict)

        # Leftovers
        if update_dict:
            for field_name in self.fields_to_sanitize:
                filter_data = list(update_dict[field_name].keys())
                update_data = list(update_dict[field_name].values())

                pg_bulk_update(self.model_class, self.model_pk_field,
                               field_name, filter_data, update_data)


text:
use crate::{
    counters,
    logging::NetworkSchema,
    peer_manager::{self, conn_notifs_channel, ConnectionRequestSender, PeerManagerError},
    transport::ConnectionMetadata,
};
use diem_config::{
    config::{Peer, PeerRole, PeerSet},
    network_id::NetworkContext,
};
use diem_crypto::x25519;
use diem_infallible::RwLock;
use diem_logger::prelude::*;
use diem_time_service::{TimeService, TimeServiceTrait};
use diem_types::{network_address::NetworkAddress, PeerId};
use futures::{
    channel::oneshot,
    future::{BoxFuture, FutureExt},
    stream::{FuturesUnordered, StreamExt},
};
use netcore::transport::ConnectionOrigin;
use num_variants::NumVariants;
use rand::{
    prelude::{SeedableRng, SmallRng},
    seq::SliceRandom,
};
use serde::Serialize;
use short_hex_str::AsShortHexStr;
use std::{
    cmp::min,
    collections::{hash_map::Entry, HashMap, HashSet},
    fmt, mem,
    sync::Arc,
    time::Duration,
};
use tokio_retry::strategy::jitter;

pub mod builder;
#[cfg(test)]
mod test;

/// In addition to the backoff strategy, we also add some small random jitter to
/// the delay before each dial. This jitter helps reduce the probability of
/// simultaneous dials, especially in non-production environments where most nodes
/// are spun up around the same time. Similarly, it smears the dials out in time
/// to avoid spiky load / thundering herd issues where all dial requests happen
/// around the same time at startup.
const MAX_CONNECTION_DELAY_JITTER: Duration = Duration::from_millis(100);

/// The ConnectivityManager actor.
pub struct ConnectivityManager<TBackoff> {
    network_context: NetworkContext,
    /// A handle to a time service for easily mocking time-related operations.
    time_service: TimeService,
    /// Nodes which are eligible to join the network.
    eligible: Arc<RwLock<PeerSet>>,
    /// PeerId and address of remote peers to which this peer is connected.
    connected: HashMap<PeerId, ConnectionMetadata>,
    /// All information about peers from discovery sources.
    discovered_peers: DiscoveredPeerSet,
    /// Channel to send connection requests to PeerManager.
    connection_reqs_tx: ConnectionRequestSender,
    /// Channel to receive notifications from PeerManager.
    connection_notifs_rx: conn_notifs_channel::Receiver,
    /// Channel over which we receive requests from other actors.
    requests_rx: channel::Receiver<ConnectivityRequest>,
    /// Peers queued to be dialed, potentially with some delay. The dial can be canceled by
    /// sending over (or dropping) the associated oneshot sender.
    dial_queue: HashMap<PeerId, oneshot::Sender<()>>,
    /// The state of any currently executing dials. Used to keep track of what
    /// the next dial delay and dial address should be for a given peer.
    dial_states: HashMap<PeerId, DialState<TBackoff>>,
    /// Trigger connectivity checks every interval.
    connectivity_check_interval: Duration,
    /// Backoff strategy.
    backoff_strategy: TBackoff,
    /// Maximum delay b/w 2 consecutive attempts to connect with a disconnected peer.
    max_delay: Duration,
    /// A local counter incremented on receiving an incoming message. Printing this in debugging
    /// allows for easy debugging.
    event_id: u32,
    /// A way to limit the number of connected peers by outgoing dials.
    outbound_connection_limit: Option<usize>,
    /// Random for shuffling which peers will be dialed
    rng: SmallRng,
    /// Whether we are using mutual authentication or not
    mutual_authentication: bool,
}

/// Different sources for peer addresses, ordered by priority (Onchain=highest,
/// Config=lowest).
#[repr(u8)]
#[derive(Copy, Clone, Eq, Hash, PartialEq, Ord, PartialOrd, NumVariants, Serialize)]
pub enum DiscoverySource {
    OnChainValidatorSet,
    File,
    Config,
}

impl fmt::Debug for DiscoverySource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl fmt::Display for DiscoverySource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                DiscoverySource::OnChainValidatorSet => "OnChainValidatorSet",
                DiscoverySource::File => "File",
                DiscoverySource::Config => "Config",
            }
        )
    }
}

/// Requests received by the [`ConnectivityManager`] manager actor from upstream modules.
#[derive(Debug, Serialize)]
pub enum ConnectivityRequest {
    /// Update set of discovered peers and associated info
    UpdateDiscoveredPeers(DiscoverySource, PeerSet),
    /// Gets current size of connected peers. This is useful in tests.
    #[serde(skip)]
    GetConnectedSize(oneshot::Sender<usize>),
    /// Gets current size of dial queue. This is useful in tests.
    #[serde(skip)]
    GetDialQueueSize(oneshot::Sender<usize>),
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
struct DiscoveredPeerSet(HashMap<PeerId, DiscoveredPeer>);

impl DiscoveredPeerSet {
    fn try_remove_empty(&mut self, peer_id: &PeerId) -> bool {
        match self.0.entry(*peer_id) {
            Entry::Occupied(entry) => {
                let peer = entry.get();
                if peer.addrs.is_empty() && peer.keys.is_empty() {
                    entry.remove();
                    true
                } else {
                    false
                }
            }
            Entry::Vacant(_) => true,
        }
    }

    /// Converts `DiscoveredPeerSet` into a `PeerSet`, however disregards the source of discovery
    /// TODO: Provide smarter merging based on discovery source
    pub fn to_eligible_peers(&self) -> PeerSet {
        self.0
            .iter()
            .filter(|(_, peer)| peer.is_eligible())
            .map(|(peer_id, peer)| (*peer_id, peer.into()))
            .collect()
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
struct DiscoveredPeer {
    role: PeerRole,
    addrs: Addresses,
    keys: PublicKeys,
}

impl DiscoveredPeer {
    /// Peers without keys are not able to be mutually authenticated to
    pub fn is_eligible(&self) -> bool {
        !self.keys.is_empty()
    }

    /// Peers without addresses can't be dialed to
    pub fn is_eligible_to_be_dialed(&self) -> bool {
        self.is_eligible() && !self.addrs.is_empty()
    }
}

impl From<&DiscoveredPeer> for Peer {
    fn from(peer: &DiscoveredPeer) -> Self {
        Peer::new(peer.addrs.union(), peer.keys.union(), peer.role)
    }
}

/// A set of `NetworkAddress`'s for a single peer, bucketed by DiscoverySource in
/// priority order.
#[derive(Clone, Default, PartialEq, Serialize)]
struct Addresses([Vec<NetworkAddress>; DiscoverySource::NUM_VARIANTS]);

/// Sets of `x25519::PublicKey`s for a single peer, bucketed by DiscoverySource
/// in priority order.
#[derive(Clone, Default, PartialEq, Serialize)]
struct PublicKeys([HashSet<x25519::PublicKey>; DiscoverySource::NUM_VARIANTS]);

#[derive(Debug)]
enum DialResult {
    Success,
    Cancelled,
    Failed(PeerManagerError),
}

/// The state needed to compute the next dial delay and dial addr for a given
/// peer.
#[derive(Debug, Clone)]
struct DialState<TBackoff> {
    /// The current state of this peer's backoff delay.
    backoff: TBackoff,
    /// The index of the next address to dial. Index of an address in the `DiscoveredPeer`'s
    /// `addrs` entry.
    addr_idx: usize,
}

/////////////////////////
// ConnectivityManager //
/////////////////////////

impl<TBackoff> ConnectivityManager<TBackoff>
where
    TBackoff: Iterator<Item = Duration> + Clone,
{
    /// Creates a new instance of the [`ConnectivityManager`] actor.
    pub fn new(
        network_context: NetworkContext,
        time_service: TimeService,
        eligible: Arc<RwLock<PeerSet>>,
        seeds: PeerSet,
        connection_reqs_tx: ConnectionRequestSender,
        connection_notifs_rx: conn_notifs_channel::Receiver,
        requests_rx: channel::Receiver<ConnectivityRequest>,
        connectivity_check_interval: Duration,
        backoff_strategy: TBackoff,
        max_delay: Duration,
        outbound_connection_limit: Option<usize>,
        mutual_authentication: bool,
    ) -> Self {
        assert!(
            eligible.read().is_empty(),
            "Eligible peers must be initially empty. eligible: {:?}",
            eligible
        );

        info!(
            NetworkSchema::new(&network_context),
            "{} Initialized connectivity manager", network_context
        );

        let mut connmgr = Self {
            network_context,
            time_service,
            eligible,
            connected: HashMap::new(),
            discovered_peers: DiscoveredPeerSet::default(),
            connection_reqs_tx,
            connection_notifs_rx,
            requests_rx,
            dial_queue: HashMap::new(),
            dial_states: HashMap::new(),
            connectivity_check_interval,
            backoff_strategy,
            max_delay,
            event_id: 0,
            outbound_connection_limit,
            rng: SmallRng::from_entropy(),
            mutual_authentication,
        };

        // set the initial config addresses and pubkeys
        connmgr.handle_update_discovered_peers(DiscoverySource::Config, seeds);
        connmgr
    }

    /// Starts the [`ConnectivityManager`] actor.
    pub async fn start(mut self) {
        // The ConnectivityManager actor is interested in 3 kinds of events:
        // 1. Ticks to trigger connecitvity check. These are implemented using a clock based
        //    trigger in production.
        // 2. Incoming requests to connect or disconnect with a peer.
        // 3. Notifications from PeerManager when we establish a new connection or lose an existing
        //    connection with a peer.
        let mut pending_dials = FuturesUnordered::new();

        let ticker = self.time_service.interval(self.connectivity_check_interval);
        tokio::pin!(ticker);

        info!(
            NetworkSchema::new(&self.network_context),
            "{} Starting ConnectivityManager actor", self.network_context
        );

        loop {
            self.event_id = self.event_id.wrapping_add(1);
            futures::select! {
                _ = ticker.select_next_some() => {
                    self.check_connectivity(&mut pending_dials).await;
                },
                req = self.requests_rx.select_next_some() => {
                    self.handle_request(req);
                },
                maybe_notif = self.connection_notifs_rx.next() => {
                    // Shutdown the connectivity manager when the PeerManager
                    // shuts down.
                    match maybe_notif {
                        Some(notif) => self.handle_control_notification(notif),
                        None => break,
                    }
                },
                peer_id = pending_dials.select_next_some() => {
                    trace!(
                        NetworkSchema::new(&self.network_context)
                            .remote_peer(&peer_id),
                        "{} Dial complete to {}",
                        self.network_context,
                        peer_id.short_str(),
                    );
                    self.dial_queue.remove(&peer_id);
                },
            }
        }

        warn!(
            NetworkSchema::new(&self.network_context),
            "{} ConnectivityManager actor terminated", self.network_context
        );
    }

    /// Disconnect from all peers that are no longer eligible.
    ///
    /// For instance, a validator might leave the validator set after a
    /// reconfiguration. If we are currently connected to this validator, calling
    /// this function will close our connection to it.
    async fn close_stale_connections(&mut self) {
        let eligible = self.eligible.read().clone();
        let stale_connections: Vec<_> = self
            .connected
            .iter()
            .filter(|(peer_id, _)| !eligible.contains_key(peer_id))
            .filter_map(|(peer_id, metadata)| {
                // If we're using server only auth, we need to not evict unknown peers
                // TODO: We should prevent `Unknown` from discovery sources
                if !self.mutual_authentication
                    && metadata.origin == ConnectionOrigin::Inbound
                    && metadata.role == PeerRole::Unknown
                {
                    None
                } else {
                    Some(*peer_id)
                }
            })
            .collect();
        for p in stale_connections.into_iter() {
            info!(
                NetworkSchema::new(&self.network_context).remote_peer(&p),
                "{} Closing stale connection to peer {}",
                self.network_context,
                p.short_str()
            );

            // Close existing connection.
            if let Err(e) = self.connection_reqs_tx.disconnect_peer(p).await {
                info!(
                    NetworkSchema::new(&self.network_context)
                        .remote_peer(&p),
                    error = %e,
                    "{} Failed to close stale connection to peer {} : {}",
                    self.network_context,
                    p.short_str(),
                    e
                );
            }
        }
    }

    /// Cancel all pending dials to peers that are no longer eligible.
    ///
    /// For instance, a validator might leave the validator set after a
    /// reconfiguration. If there is a pending dial to this validator, calling
    /// this function will remove it from the dial queue.
    async fn cancel_stale_dials(&mut self) {
        let eligible = self.eligible.read().clone();
        let stale_dials: Vec<_> = self
            .dial_queue
            .keys()
            .filter(|peer_id| !eligible.contains_key(peer_id))
            .cloned()
            .collect();

        for p in stale_dials.into_iter() {
            debug!(
                NetworkSchema::new(&self.network_context).remote_peer(&p),
                "{} Cancelling stale dial {}",
                self.network_context,
                p.short_str()
            );
            self.dial_queue.remove(&p);
        }
    }

    fn dial_eligible_peers<'a>(
        &'a mut self,
        pending_dials: &'a mut FuturesUnordered<BoxFuture<'static, PeerId>>,
    ) {
        let to_connect = self.choose_peers_to_dial();
        for (peer_id, peer) in to_connect {
            self.queue_dial_peer(peer_id, peer, pending_dials);
        }
    }

    fn choose_peers_to_dial(&mut self) -> Vec<(PeerId, DiscoveredPeer)> {
        let network_id = self.network_context.network_id();
        let role = self.network_context.role();
        let roles_to_dial = network_id.upstream_roles(&role);
        let mut eligible: Vec<_> = self
            .discovered_peers
            .0
            .iter()
            .filter(|(peer_id, peer)| {
                peer.is_eligible_to_be_dialed() // The node is eligible to dial
                && !self.connected.contains_key(peer_id) // The node is not already connected.
                && !self.dial_queue.contains_key(peer_id) // There is no pending dial to this node.
                && roles_to_dial.contains(&peer.role) // We can dial this role
            })
            .collect();

        // Prioritize by PeerRole
        // Shuffle so we don't get stuck on certain peers
        eligible.shuffle(&mut self.rng);
        eligible.sort_by(|(_, peer), (_, other)| peer.role.cmp(&other.role));

        let num_eligible = eligible.len();

        // Limit the number of dialed connections from a Full Node
        // This does not limit the number of incoming connections
        // It enforces that a full node cannot have more outgoing connections than `connection_limit`
        // including in flight dials.
        let to_connect = if let Some(conn_limit) = self.outbound_connection_limit {
            let outbound_connections = self
                .connected
                .iter()
                .filter(|(_, metadata)| metadata.origin == ConnectionOrigin::Outbound)
                .count();
            min(
                conn_limit
                    .saturating_sub(outbound_connections.saturating_add(self.dial_queue.len())),
                num_eligible,
            )
        } else {
            num_eligible
        };

        eligible
            .iter()
            .take(to_connect)
            .map(|(peer_id, peer)| (**peer_id, (*peer).clone()))
            .collect()
    }

    fn queue_dial_peer<'a>(
        &'a mut self,
        peer_id: PeerId,
        peer: DiscoveredPeer,
        pending_dials: &'a mut FuturesUnordered<BoxFuture<'static, PeerId>>,
    ) {
        // If we're attempting to dial a Peer we must not be connected to it. This ensures that
        // newly eligible, but not connected to peers, have their counter initialized properly.
        counters::peer_connected(&self.network_context, &peer_id, 0);

        let connection_reqs_tx = self.connection_reqs_tx.clone();
        // The initial dial state; it has zero dial delay and uses the first
        // address.
        let init_dial_state = DialState::new(self.backoff_strategy.clone());
        let dial_state = self
            .dial_states
            .entry(peer_id)
            .or_insert_with(|| init_dial_state);

        // Choose the next addr to dial for this peer. Currently, we just
        // round-robin the selection, i.e., try the sequence:
        // addr[0], .., addr[len-1], addr[0], ..
        let addr = dial_state.next_addr(&peer.addrs).clone();

        // Using the DialState's backoff strategy, compute the delay until
        // the next dial attempt for this peer.
        let dial_delay = dial_state.next_backoff_delay(self.max_delay);
        let f_delay = self.time_service.sleep(dial_delay);

        let (cancel_tx, cancel_rx) = oneshot::channel();

        info!(
            NetworkSchema::new(&self.network_context)
                .remote_peer(&peer_id)
                .network_address(&addr),
            delay = dial_delay,
            "{} Create dial future to {} at {} after {:?}",
            self.network_context,
            peer_id.short_str(),
            addr,
            dial_delay
        );

        let network_context = self.network_context;
        // Create future which completes by either dialing after calculated
        // delay or on cancellation.
        let f = async move {
            // We dial after a delay. The dial can be canceled by sending to or dropping
            // `cancel_rx`.
            let dial_result = futures::select! {
                _ = f_delay.fuse() => {
                    info!(
                        NetworkSchema::new(&network_context)
                            .remote_peer(&peer_id)
                            .network_address(&addr),
                        "{} Dialing peer {} at {}",
                        network_context,
                        peer_id.short_str(),
                        addr
                    );
                    match connection_reqs_tx.dial_peer(peer_id, addr.clone()).await {
                        Ok(_) => DialResult::Success,
                        Err(e) => DialResult::Failed(e),
                    }
                },
                _ = cancel_rx.fuse() => DialResult::Cancelled,
            };
            log_dial_result(network_context, peer_id, addr, dial_result);
            // Send peer_id as future result so it can be removed from dial queue.
            peer_id
        };
        pending_dials.push(f.boxed());
        self.dial_queue.insert(peer_id, cancel_tx);
    }

    // Note: We do not check that the connections to older incarnations of a node are broken, and
    // instead rely on the node moving to a new epoch to break connections made from older
    // incarnations.
    async fn check_connectivity<'a>(
        &'a mut self,
        pending_dials: &'a mut FuturesUnordered<BoxFuture<'static, PeerId>>,
    ) {
        trace!(
            NetworkSchema::new(&self.network_context),
            "{} Checking connectivity",
            self.network_context
        );

        // Log the eligible peers with addresses from discovery
        sample!(SampleRate::Duration(Duration::from_secs(60)), {
            info!(
                NetworkSchema::new(&self.network_context),
                discovered_peers = ?self.discovered_peers,
                "Current eligible peers"
            )
        });

        // Cancel dials to peers that are no longer eligible.
        self.cancel_stale_dials().await;
        // Disconnect from connected peers that are no longer eligible.
        self.close_stale_connections().await;
        // Dial peers which are eligible but are neither connected nor queued for dialing in the
        // future.
        self.dial_eligible_peers(pending_dials);
    }

    fn reset_dial_state(&mut self, peer_id: &PeerId) {
        if let Some(dial_state) = self.dial_states.get_mut(peer_id) {
            *dial_state = DialState::new(self.backoff_strategy.clone());
        }
    }

    fn handle_request(&mut self, req: ConnectivityRequest) {
        trace!(
            NetworkSchema::new(&self.network_context),
            connectivity_request = req,
            "{} Handling ConnectivityRequest",
            self.network_context
        );

        match req {
            ConnectivityRequest::UpdateDiscoveredPeers(src, discovered_peers) => {
                trace!(
                    NetworkSchema::new(&self.network_context),
                    "{} Received updated list of discovered peers: src: {:?}",
                    self.network_context,
                    src,
                );
                self.handle_update_discovered_peers(src, discovered_peers);
            }
            ConnectivityRequest::GetDialQueueSize(sender) => {
                sender.send(self.dial_queue.len()).unwrap();
            }
            ConnectivityRequest::GetConnectedSize(sender) => {
                sender.send(self.connected.len()).unwrap();
            }
        }
    }

    fn handle_update_discovered_peers(
        &mut self,
        src: DiscoverySource,
        new_discovered_peers: PeerSet,
    ) {
        let self_peer_id = self.network_context.peer_id();
        let mut keys_updated = false;

        let mut peers_to_check_remove = Vec::new();

        // Remove peer info that no longer have information to use them
        for (peer_id, peer) in self.discovered_peers.0.iter_mut() {
            let new_peer = new_discovered_peers.get(peer_id);
            let check_remove = if let Some(new_peer) = new_peer {
                if new_peer.keys.is_empty() {
                    keys_updated |= peer.keys.clear_src(src);
                }
                if new_peer.addresses.is_empty() {
                    peer.addrs.clear_src(src);
                }
                new_peer.addresses.is_empty() && new_peer.keys.is_empty()
            } else {
                keys_updated |= peer.keys.clear_src(src);
                peer.addrs.clear_src(src);
                true
            };
            if check_remove {
                peers_to_check_remove.push(*peer_id);
            }
        }

        // Remove peers that no longer have state
        for peer_id in peers_to_check_remove {
            self.discovered_peers.try_remove_empty(&peer_id);
        }

        // Make updates to the peers accordingly
        for (peer_id, discovered_peer) in new_discovered_peers {
            // Don't include ourselves, because we don't need to dial ourselves
            if peer_id == self_peer_id {
                continue;
            }

            // Create the new `DiscoveredPeer`, role is set when a `Peer` is first discovered
            let peer = self
                .discovered_peers
                .0
                .entry(peer_id)
                .or_insert(DiscoveredPeer {
                    role: discovered_peer.role,
                    addrs: Addresses::default(),
                    keys: PublicKeys::default(),
                });
            let mut peer_updated = false;
            // Update peer's pubkeys
            if peer.keys.update(src, discovered_peer.keys) {
                info!(
                    NetworkSchema::new(&self.network_context)
                        .remote_peer(&peer_id)
                        .discovery_source(&src),
                    "{} pubkey sets updated for peer: {}, pubkeys: {}",
                    self.network_context,
                    peer_id.short_str(),
                    peer.keys
                );
                keys_updated = true;
                peer_updated = true;
            }

            // Update peer's addresses
            if peer.addrs.update(src, discovered_peer.addresses) {
                info!(
                    NetworkSchema::new(&self.network_context).remote_peer(&peer_id),
                    network_addresses = &peer.addrs,
                    "{} addresses updated for peer: {}, update src: {:?}, addrs: {}",
                    self.network_context,
                    peer_id.short_str(),
                    src,
                    &peer.addrs,
                );
                peer_updated = true;
            }

            // If we're currently trying to dial this peer, we reset their
            // dial state. As a result, we will begin our next dial attempt
            // from the first address (which might have changed) and from a
            // fresh backoff (since the current backoff delay might be maxed
            // out if we can't reach any of their previous addresses).
            if peer_updated {
                self.reset_dial_state(&peer_id)
            }
        }

        // update eligible peers accordingly
        if keys_updated {
            // For each peer, union all of the pubkeys from each discovery source
            // to generate the new eligible peers set.
            let new_eligible = self.discovered_peers.to_eligible_peers();

            // Swap in the new eligible peers set. Drop the old set after releasing
            // the write lock.
            let _old_eligible = {
                let mut eligible = self.eligible.write();
                mem::replace(&mut *eligible, new_eligible)
            };
        }
    }

    fn handle_control_notification(&mut self, notif: peer_manager::ConnectionNotification) {
        trace!(
            NetworkSchema::new(&self.network_context),
            connection_notification = notif,
            "Connection notification"
        );
        match notif {
            peer_manager::ConnectionNotification::NewPeer(metadata, _context) => {
                let peer_id = metadata.remote_peer_id;
                counters::peer_connected(&self.network_context, &peer_id, 1);
                self.connected.insert(peer_id, metadata);

                // Cancel possible queued dial to this peer.
                self.dial_states.remove(&peer_id);
                self.dial_queue.remove(&peer_id);
            }
            peer_manager::ConnectionNotification::LostPeer(metadata, _context, _reason) => {
                let peer_id = metadata.remote_peer_id;
                if let Some(stored_metadata) = self.connected.get(&peer_id) {
                    // Remove node from connected peers list.

                    counters::peer_connected(&self.network_context, &peer_id, 0);

                    info!(
                        NetworkSchema::new(&self.network_context)
                            .remote_peer(&peer_id)
                            .connection_metadata(&metadata),
                        stored_metadata = stored_metadata,
                        "{} Removing peer '{}' metadata: {}, vs event metadata: {}",
                        self.network_context,
                        peer_id.short_str(),
                        stored_metadata,
                        metadata
                    );
                    self.connected.remove(&peer_id);
                } else {
                    info!(
                        NetworkSchema::new(&self.network_context)
                            .remote_peer(&peer_id)
                            .connection_metadata(&metadata),
                        "{} Ignoring stale lost peer event for peer: {}, addr: {}",
                        self.network_context,
                        peer_id.short_str(),
                        metadata.addr
                    );
                }
            }
        }
    }
}

fn log_dial_result(
    network_context: NetworkContext,
    peer_id: PeerId,
    addr: NetworkAddress,
    dial_result: DialResult,
) {
    match dial_result {
        DialResult::Success => {
            info!(
                NetworkSchema::new(&network_context)
                    .remote_peer(&peer_id)
                    .network_address(&addr),
                "{} Successfully connected to peer: {} at address: {}",
                network_context,
                peer_id.short_str(),
                addr
            );
        }
        DialResult::Cancelled => {
            info!(
                NetworkSchema::new(&network_context).remote_peer(&peer_id),
                "{} Cancelled pending dial to peer: {}",
                network_context,
                peer_id.short_str()
            );
        }
        DialResult::Failed(err) => match err {
            PeerManagerError::AlreadyConnected(a) => {
                info!(
                    NetworkSchema::new(&network_context)
                        .remote_peer(&peer_id)
                        .network_address(&a),
                    "{} Already connected to peer: {} at address: {}",
                    network_context,
                    peer_id.short_str(),
                    a
                );
            }
            e => {
                info!(
                    NetworkSchema::new(&network_context)
                        .remote_peer(&peer_id)
                        .network_address(&addr),
                    error = %e,
                    "{} Failed to connect to peer: {} at address: {}; error: {}",
                    network_context,
                    peer_id.short_str(),
                    addr,
                    e
                );
            }
        },
    }
}

/////////////////////
// DiscoverySource //
/////////////////////

impl DiscoverySource {
    fn as_usize(self) -> usize {
        self as u8 as usize
    }
}

///////////////
// Addresses //
///////////////

impl Addresses {
    fn len(&self) -> usize {
        self.0.iter().map(Vec::len).sum()
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Update the addresses for the `DiscoverySource` bucket. Return `true` if
    /// the addresses have actually changed.
    fn update(&mut self, src: DiscoverySource, addrs: Vec<NetworkAddress>) -> bool {
        let src_idx = src.as_usize();
        if self.0[src_idx] != addrs {
            self.0[src_idx] = addrs;
            true
        } else {
            false
        }
    }

    fn clear_src(&mut self, src: DiscoverySource) -> bool {
        self.update(src, Vec::new())
    }

    fn get(&self, idx: usize) -> Option<&NetworkAddress> {
        self.0.iter().flatten().nth(idx)
    }

    /// The Union isn't stable, and order is completely disregarded
    fn union(&self) -> Vec<NetworkAddress> {
        let set: HashSet<_> = self.0.iter().flatten().cloned().collect();
        set.into_iter().collect()
    }
}

impl fmt::Display for Addresses {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Write without the typical "Addresses(..)" around the output to reduce
        // debug noise.
        write!(f, "{:?}", self.0)
    }
}

impl fmt::Debug for Addresses {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

////////////////
// PublicKeys //
////////////////

impl PublicKeys {
    fn len(&self) -> usize {
        self.0.iter().map(HashSet::len).sum()
    }

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn update(&mut self, src: DiscoverySource, pubkeys: HashSet<x25519::PublicKey>) -> bool {
        let src_idx = src.as_usize();
        if self.0[src_idx] != pubkeys {
            self.0[src_idx] = pubkeys;
            true
        } else {
            false
        }
    }

    fn clear_src(&mut self, src: DiscoverySource) -> bool {
        self.update(src, HashSet::new())
    }

    fn union(&self) -> HashSet<x25519::PublicKey> {
        self.0.iter().flatten().copied().collect()
    }
}

impl fmt::Display for PublicKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Write without the typical "PublicKeys(..)" around the output to reduce
        // debug noise.
        write!(f, "{:?}", self.0)
    }
}

impl fmt::Debug for PublicKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

///////////////
// DialState //
///////////////

impl<TBackoff> DialState<TBackoff>
where
    TBackoff: Iterator<Item = Duration> + Clone,
{
    fn new(backoff: TBackoff) -> Self {
        Self {
            backoff,
            addr_idx: 0,
        }
    }

    fn next_addr<'a>(&mut self, addrs: &'a Addresses) -> &'a NetworkAddress {
        assert!(!addrs.is_empty());

        let addr_idx = self.addr_idx;
        self.addr_idx = self.addr_idx.wrapping_add(1);

        addrs.get(addr_idx % addrs.len()).unwrap()
    }

    fn next_backoff_delay(&mut self, max_delay: Duration) -> Duration {
        let jitter = jitter(MAX_CONNECTION_DELAY_JITTER);

        min(max_delay, self.backoff.next().unwrap_or(max_delay)) + jitter
    }
}


text:
read -p "What would you like the folder that contains the files to be called?" folderName < /dev/tty
unzip -d "$folderName" submissions.zip
rm submissions.zip
#Get rid of everything after the first underscore in each filename
cd "$folderName"
mmv "*_*.zip" "#1.zip"
for zipfile in *.zip; do
	#get the name of the file without the .zip extension
	exdir="${zipfile%.zip}"
	unzip the file and remove the .zip archive
    unzip -d "$exdir" "$zipfile" && rm "$zipfile"
done


text:
package org.jivesoftware.smackx.mam;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser;

import org.jivesoftware.smackx.mam.element.MamFinIQ;
import org.jivesoftware.smackx.mam.provider.MamFinIQProvider;
import org.jivesoftware.smackx.rsm.packet.RSMSet;

import org.junit.jupiter.api.Test;

public class MamFinProviderTest extends MamTest {

    static final String exmapleMamFinXml = "<fin xmlns='urn:xmpp:mam:2' stable='true'>"
            + "<set xmlns='http://jabber.org/protocol/rsm'>" + "<max>10</max>" + "<after>09af3-cc343-b409f</after>"
            + "</set>" + "</fin>";

    @Test
    public void checkMamFinProvider() throws Exception {
        XmlPullParser parser = PacketParserUtils.getParserFor(exmapleMamFinXml);
        MamFinIQ mamFinIQ = new MamFinIQProvider().parse(parser, null);

        assertFalse(mamFinIQ.isComplete());
        assertTrue(mamFinIQ.isStable());
        assertNull(mamFinIQ.getQueryId());

        RSMSet rsmSet = mamFinIQ.getRSMSet();
        assertEquals(rsmSet.getAfter(), "09af3-cc343-b409f");
        assertEquals(rsmSet.getMax(), 10);
    }

    @Test
    public void checkQueryLimitedResults() throws Exception {
        // @formatter:off
        final String IQ_LIMITED_RESULTS_EXAMPLE = "<iq type='result' id='u29303'>"
                        + "<fin xmlns='urn:xmpp:mam:2' complete='true'>"
                        + "<set xmlns='http://jabber.org/protocol/rsm'>"
                        + "<first index='0'>23452-4534-1</first>"
                        + "<last>390-2342-22</last>" + "<count>16</count>"
                        + "</set>"
                        + "</fin>"
                        + "</iq>";
        // @formatter:on

        IQ iq = PacketParserUtils.parseStanza(IQ_LIMITED_RESULTS_EXAMPLE);

        MamFinIQ mamFinIQ = (MamFinIQ) iq;
        assertEquals(mamFinIQ.getType(), IQ.Type.result);

        assertTrue(mamFinIQ.isComplete());
        assertEquals(mamFinIQ.getRSMSet().getCount(), 16);
        assertEquals(mamFinIQ.getRSMSet().getFirst(), "23452-4534-1");
        assertEquals(mamFinIQ.getRSMSet().getFirstIndex(), 0);
        assertEquals(mamFinIQ.getRSMSet().getLast(), "390-2342-22");
    }

}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ApplicationCounter
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            EnrollUser();

            var path = Server.MapPath("Images/blank.jpg");
            var visitorsCount = GetCounter();

            using (var bitmap = new Bitmap(path))
            {
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    var brush = new SolidBrush(Color.BlueViolet);
                    graphics.FillRectangle(brush, 0, 0, 5000, 150);
                    graphics.DrawString(
                        "Current visitors count: " + visitorsCount.ToString(),
                        new Font("Segoe UI", 15),
                        new SolidBrush(Color.BlanchedAlmond),
                        new PointF(25, 40));
                    Response.ContentType = "image/jpeg";
                    bitmap.Save(Response.OutputStream, ImageFormat.Png);
                }
            }
        }

        private object GetCounter()
        {
            var visitorsCount = Application["Visitors"];
            return visitorsCount;
        }

        private void EnrollUser()
        {
            Application.Lock();
            if (Application["Visitors"] == null)
            {
                Application["Visitors"] = 1;
            }
            else
            {
                Application["Visitors"] = (int)Application["Visitors"] + 1;
            }

            Application.UnLock();
        }
    }
}


text:
package org.apache.axis2.transport.testkit.tests.misc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.xml.namespace.QName;

import org.apache.axiom.mime.ContentType;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.InOnlyAxisOperation;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.axis2.transport.testkit.axis2.client.AxisAsyncTestClient;
import org.apache.axis2.transport.testkit.axis2.client.AxisTestClientContext;
import org.apache.axis2.transport.testkit.axis2.endpoint.AxisTestEndpoint;
import org.apache.axis2.transport.testkit.axis2.endpoint.AxisTestEndpointContext;
import org.apache.axis2.transport.testkit.channel.AsyncChannel;
import org.apache.axis2.transport.testkit.client.ClientOptions;
import org.apache.axis2.transport.testkit.message.AxisMessage;
import org.apache.axis2.transport.testkit.name.Name;
import org.apache.axis2.transport.testkit.tests.TestResourceSet;
import org.apache.axis2.transport.testkit.tests.ManagedTestCase;

/**
 * Generic test case to check whether a transport listener processes messages with the expected
 * level of concurrency. This test case is used to verify that the listener is able to
 * process messages simultaneously.
 * <p>
 * The test case deploys a given number of services and sends a configurable number of messages
 * to each of these services. The services are configured with a custom message receiver that
 * blocks until the expected level of concurrency (given by the number of endpoints times the
 * number of messages) is reached. If after some timeout the concurrency level is not reached,
 * the test fails.
 */
@Name("MinConcurrency")
public class MinConcurrencyTest extends ManagedTestCase {
    private final AsyncChannel[] channels;
    private final int messages;
    private final boolean preloadMessages;

    public MinConcurrencyTest(AsyncChannel[] channels, int messages,
            boolean preloadMessages, Object... resources) {
        super(resources);
        addResource(AxisTestClientContext.INSTANCE);
        addResource(AxisTestEndpointContext.INSTANCE);
        this.channels = channels;
        this.messages = messages;
        this.preloadMessages = preloadMessages;
    }

    private int concurrencyReached;
    private final Object concurrencyReachedLock = new Object();
    private final Object shutdownAwaitLock = new Object();

    @Override
    protected void runTest() throws Throwable {
        int endpointCount = channels.length;
        int expectedConcurrency = endpointCount * messages;

        final MessageReceiver messageReceiver = new MessageReceiver() {
            public void receive(MessageContext msgContext) throws AxisFault {
                synchronized (concurrencyReachedLock) {
                    concurrencyReached++;
                    concurrencyReachedLock.notifyAll();
                }
                try {
                    shutdownAwaitLock.wait();
                } catch (InterruptedException ex) {
                }
            }
        };

        TestResourceSet[] clientResourceSets = new TestResourceSet[endpointCount];
        TestResourceSet[] endpointResourceSets = new TestResourceSet[endpointCount];
        try {
            for (int i=0; i<endpointCount; i++) {
                TestResourceSet clientResourceSet = new TestResourceSet(getResourceSet());
                AsyncChannel channel = channels[i];
                clientResourceSet.addResource(channel);
                AxisAsyncTestClient client = new AxisAsyncTestClient(false);
                clientResourceSet.addResource(client);
                clientResourceSet.setUp();
                clientResourceSets[i] = clientResourceSet;

                TestResourceSet endpointResourceSet = new TestResourceSet(clientResourceSet);
                endpointResourceSet.addResource(new AxisTestEndpoint() {
                    @Override
                    protected AxisOperation createOperation() {
                        AxisOperation operation = new InOnlyAxisOperation(new QName("in"));
                        operation.setMessageReceiver(messageReceiver);
                        return operation;
                    }

                    @Override
                    protected void onTransportError(Throwable ex) {
                        // TODO Auto-generated method stub
                    }
                });

                if (!preloadMessages) {
                    endpointResourceSet.setUp();
                    endpointResourceSets[i] = endpointResourceSet;
                }
                for (int j=0; j<messages; j++) {
                    ClientOptions options = new ClientOptions(client, new ContentType(SOAP11Constants.SOAP_11_CONTENT_TYPE), "UTF-8");
                    AxisMessage message = new AxisMessage();
                    message.setMessageType(SOAP11Constants.SOAP_11_CONTENT_TYPE);
                    SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
                    SOAPEnvelope envelope = factory.getDefaultEnvelope();
                    message.setEnvelope(envelope);
                    client.sendMessage(options, new ContentType(message.getMessageType()), message);
                }
                if (preloadMessages) {
                    endpointResourceSet.setUp();
                    endpointResourceSets[i] = endpointResourceSet;
                }
            }

            long startTime = System.currentTimeMillis();
            while (concurrencyReached < expectedConcurrency
                && System.currentTimeMillis() < (startTime + 5000)) {
                synchronized(concurrencyReachedLock) {
                    concurrencyReachedLock.wait(5000);
                }
            }

            synchronized(shutdownAwaitLock) {
                shutdownAwaitLock.notifyAll();
            }

            if (concurrencyReached < expectedConcurrency) {
                fail("Concurrency reached is " + concurrencyReached + ", but expected " +
                    expectedConcurrency);
            }

        } finally {
            for (int i=0; i<endpointCount; i++) {
                if (endpointResourceSets[i] != null) {
                    endpointResourceSets[i].tearDown();
                }
                if (clientResourceSets[i] != null) {
                    clientResourceSets[i].tearDown();
                }
            }
        }
    }
}


text:
@interface TPPSImageView : UIView

@property (nonatomic) UIImage *image;

@end


text:
require_relative "../../test_helper"
require_relative "flow_test_helper"
require 'gds_api/test_helpers/worldwide'

require "smart_answer_flows/report-a-lost-or-stolen-passport"

class ReportALostOrStolenPassportTest < ActiveSupport::TestCase
  include FlowTestHelper
  include GdsApi::TestHelpers::Worldwide

  setup do
    @location_slugs = %w(azerbaijan canada)
    worldwide_api_has_locations(@location_slugs)
    @location_slugs.each do |location|
      json = read_fixture_file("worldwide/#{location}_organisations.json")
      worldwide_api_has_organisations_for_location(location, json)
    end
    setup_for_testing_flow SmartAnswer::ReportALostOrStolenPassportFlow
  end

  should "ask where the passport was lost or stolen" do
    assert_current_node :where_was_the_passport_lost_or_stolen?
  end

  context "in the UK " do
    setup do
      add_response :in_the_uk
    end

    should "tell you to fill out the LS01 form" do
      assert_current_node :complete_LS01_form
    end
  end

  context "abroad" do
    setup do
      add_response :abroad
    end

    should "ask in which country has been lost/stolen" do
      assert_current_node :which_country?
    end

    context "in Azerbaijan" do
      setup do
        add_response "azerbaijan"
      end

      should "tell you to report it to the embassy" do
        assert_current_node :contact_the_embassy
        assert_match /British Embassy Baku/, outcome_body
      end
    end
  end

  context "abroad" do
    setup do
      add_response :abroad
    end

    should "ask in which country has been lost/stolen" do
      assert_current_node :which_country?
    end

    context "in Canada" do
      setup do
        add_response "canada"
      end

      should "tell you to fill in a form and visit the embassy" do
        assert_current_node :contact_the_embassy_canada
        assert_match /Fill in form LS01 and post it to your nearest British embassy, high commission or consulate./, outcome_body
      end
    end
  end
end


text:
<!DOCTYPE html>

  <title>Lithium</title>
  <meta about="Search Lithium content."/>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="format-detection" content="telephone=no">

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

Tabs

    <input type="text" class="CoveoQueryBox" autocapitalize="off" autocorrect="off"/>

Done

        Relevance
        Date


text:
$(document).ready(function() {
	$('#opadTabHeaderList > li').click(function(){
		if (!$(this).hasClass('opadTabActive')) {
			$('#opadTabHeaderList > li').removeClass('opadTabActive');
			$('#opadTabHeaderList > li').addClass('opadTabInactive');

			$(this).removeClass('opadTabInactive');
			$(this).addClass('opadTabActive');

			$('.opadTabBodyContent').hide();

			$('.opadTabBodyContent:eq(' + $('#opadTabHeaderList > li').index(this) + ')').show();
	    }
		if (!$(this).hasClass('opadTabtemplate')) {
			$('.opadSlider').hide();
	    } else {
	    	$('.opadSlider').show();
	    }
	});
});


text:
/*global console*/
/*global module*/
/*global require*/
var ArtistModel = require('./mongoose/mongoose-models.js')().Artist,
    Spotify = require('./Spotify/Spotify.js'),
    SpotifyAuth = require('./Spotify/SpotifyAuth.js'),
    Q = require("q");

var Artist = function () {'use strict'; };

Artist.refresh = function (user, callback) {
    'use strict';
    var exist = false,
        list = [],
        final = [],
        i = 0;
    SpotifyAuth.isSet(function (isSet) {
        if (isSet) {
            Artist.get(user, function (err, existing) {
                if (err) {
                    console.log(err);
                    callback(err);
                } else {
                    Spotify.getMyArtists(function (err, artists) {
                        if (err) {
                            console.log(err);
                            callback(err);
                        } else {
                            artists.forEach(function (artist) {
                                exist = false;
                                existing.forEach(function (e) {
                                    if (artist.name === e.name) {
                                        exist = true;
                                    }
                                });
                                if (!exist) {
                                    list.push({name: artist.name, spotifyId: artist.id});
                                }
                            });
                            if (list.length === 0) {
                                callback(null, {});
                            } else {
                                list.forEach(function (artist) {
                                    i += 1;
                                    Artist.insert(user, artist, function (err, saved) {
                                        if (err) {
                                            console.log(err);
                                        } else {
                                            final.push(saved);
                                        }
                                        i -= 1;
                                        if (i === 0) {
                                            callback(null, final);
                                        }
                                    });
                                });
                            }
                        }
                    });
                }
            });
        } else {
            console.log("not set...");
            callback("token expired");
        }
    });
};

Artist.get = function (user, callback) {
    var deferred = Q.defer(),
        artistDB = new ArtistModel();
    artistDB.find({}, function (err, list) {
        callback(err, list);
        if(!err) {
            deferred.resolve(list);
        } else {
            deferred.reject(err);
        }
    });
    return deferred.promise;
};
Artist.insert = function (user, artist, callback) {
    'use strict';
    var alarmDB = new ArtistModel();
    alarmDB.userId = user._id;
    alarmDB.name = artist.name;
    alarmDB.spotifyId = artist.spotifyId;
    alarmDB.musicgraphId = null;
    alarmDB.useItAsAlarm = true;
    alarmDB.save(function (err, saved) {
        callback(err, saved);
    });
};
Artist.get = function (user, callback) {
    'use strict';
    ArtistModel.find({userId: user._id}, function (err, artists) {
        callback(err, artists);
    });
};

module.exports = Artist;


text:
{% extends "accounts/base.html" %}
{% load static from staticfiles %}
{% block title %} Register{% endblock title %}
{% block about %} class="active" {% endblock about %}
{% block content %}

 Our Mission

	We do things together by aligning our energy towards a common goal, breaking the effort into parts, then marching towards the goal as one. But too often, the friction of coordination, of communicating the right amount of information, to the right people, at the right time, in the right place, gets in the way. This friction lowers our collective productivity - which worsens with the complexity of projects we undertake.

	Teamflowy's mission is to help humanity thrive by enabling all teams to work together effortlessly. We've re-imagined how work gets done through a fast and versatile web application that connects everyone with what's going on, their shared priorities, and who owns each part of the effort.

	To take the next step in human productivity, we need a fresh start. We created Asana to help take that step; to improve the productivity of individuals and groups, to increase the potential output of every team's effort.

Our Team

{% endblock content %}


text:
using content::BrowserThread;

namespace mate {

template <>
struct Converter<URLPattern> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     URLPattern* out) {
    std::string pattern;
    if (!ConvertFromV8(isolate, val, &pattern))
      return false;
    *out = URLPattern(URLPattern::SCHEME_ALL);
    return out->Parse(pattern) == URLPattern::ParseResult::kSuccess;
  }
};

}  // namespace mate

namespace electron {

namespace api {

namespace {

template <typename Method, typename Event, typename Listener>
void CallNetworkDelegateMethod(
    URLRequestContextGetter* url_request_context_getter,
    Method method,
    Event type,
    URLPatterns patterns,
    Listener listener) {
  // Force creating network delegate.
  url_request_context_getter->GetURLRequestContext();
  // Then call the method.
  auto* network_delegate = url_request_context_getter->network_delegate();
  (network_delegate->*method)(type, std::move(patterns), std::move(listener));
}

}  // namespace

WebRequest::WebRequest(v8::Isolate* isolate,
                       AtomBrowserContext* browser_context)
    : browser_context_(browser_context) {
  Init(isolate);
}

WebRequest::~WebRequest() {}

template <AtomNetworkDelegate::SimpleEvent type>
void WebRequest::SetSimpleListener(mate::Arguments* args) {
  SetListener<AtomNetworkDelegate::SimpleListener>(
      &AtomNetworkDelegate::SetSimpleListenerInIO, type, args);
}

template <AtomNetworkDelegate::ResponseEvent type>
void WebRequest::SetResponseListener(mate::Arguments* args) {
  SetListener<AtomNetworkDelegate::ResponseListener>(
      &AtomNetworkDelegate::SetResponseListenerInIO, type, args);
}

template <typename Listener, typename Method, typename Event>
void WebRequest::SetListener(Method method, Event type, mate::Arguments* args) {
  // { urls }.
  URLPatterns patterns;
  mate::Dictionary dict;
  args->GetNext(&dict) && dict.Get("urls", &patterns);

  // Function or null.
  v8::Local<v8::Value> value;
  Listener listener;
  if (!args->GetNext(&listener) &&
      !(args->GetNext(&value) && value->IsNull())) {
    args->ThrowError("Must pass null or a Function");
    return;
  }

  auto* url_request_context_getter = static_cast<URLRequestContextGetter*>(
      browser_context_->GetRequestContext());
  if (!url_request_context_getter)
    return;
  base::PostTaskWithTraits(
      FROM_HERE, {BrowserThread::IO},
      base::BindOnce(&CallNetworkDelegateMethod<Method, Event, Listener>,
                     base::RetainedRef(url_request_context_getter), method,
                     type, std::move(patterns), std::move(listener)));
}

// static
mate::Handle<WebRequest> WebRequest::Create(
    v8::Isolate* isolate,
    AtomBrowserContext* browser_context) {
  return mate::CreateHandle(isolate, new WebRequest(isolate, browser_context));
}

// static
void WebRequest::BuildPrototype(v8::Isolate* isolate,
                                v8::Local<v8::FunctionTemplate> prototype) {
  prototype->SetClassName(mate::StringToV8(isolate, "WebRequest"));
  mate::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate())
      .SetMethod("onBeforeRequest", &WebRequest::SetResponseListener<
                                        AtomNetworkDelegate::kOnBeforeRequest>)
      .SetMethod("onBeforeSendHeaders",
                 &WebRequest::SetResponseListener<
                     AtomNetworkDelegate::kOnBeforeSendHeaders>)
      .SetMethod("onHeadersReceived",
                 &WebRequest::SetResponseListener<
                     AtomNetworkDelegate::kOnHeadersReceived>)
      .SetMethod(
          "onSendHeaders",
          &WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnSendHeaders>)
      .SetMethod("onBeforeRedirect",
                 &WebRequest::SetSimpleListener<
                     AtomNetworkDelegate::kOnBeforeRedirect>)
      .SetMethod("onResponseStarted",
                 &WebRequest::SetSimpleListener<
                     AtomNetworkDelegate::kOnResponseStarted>)
      .SetMethod(
          "onCompleted",
          &WebRequest::SetSimpleListener<AtomNetworkDelegate::kOnCompleted>)
      .SetMethod("onErrorOccurred", &WebRequest::SetSimpleListener<
                                        AtomNetworkDelegate::kOnErrorOccurred>);
}

}  // namespace api

}  // namespace electron


text:
layout: post
title: "ODTU DevToWin Etkinlik Nisan 2015"
date: 2015-04-16 14:00
author: engin.polat
comments: true
category: [Etkinlik]
tags: [azure, etkinliklerim, microsoft, seminer, signalr, unity3d, universal app, windows phone, windows phone emulator, windows10, windowsphone, wp8]
---
**Microsoft Türkiye Ofisi** ile birlikte *13 Nisan 2015*, *14 Nisan 2015* ve *15 Nisan 2015* tarihlerinde **Ankara ODTU Üniversitesi ATOM** (*Animasyon Teknolojileri ve Oyun Geliştirme Merkezi*) içerisinde **DevToWin** etkinliği organize ettik.

![](/assets/uploads/2015/04/ODTUDevToWinEtkinlik.png)

Bu etkinlik kapsamında 3 gün boyunca Unity3D ile oyun geliştiren şirketlerin oyunlarını *Windows* platformuna uyarlayabilmeleri ve **Microsoft Azure**'un servislerinden faydalanabilmelerini sağlamaya çalıştım.

Özellikle **Unity3D ile oyun geliştirme inceliklerini**, **Windows 10 ile birlikte gelecek Universal App yeniliklerini**, oyun geliştiriciler için önemli olan **Microsoft Azure** hizmetlerini ve real-time servis geliştirmek için tercih edilebilecek **SignalR** framework'unu uygulamalı olarak anlattım.

Etkinliği birlikte organize ettiğimiz *Microsoft Türkiye Ofisi* çalışanı arkadaşlarıma ve etkinliğe katılanlara **teşekkür ederim**.


text:
using namespace std;

SendRawDialog::SendRawDialog(const QString &txID, const QString &txHEX, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SendRawDialog)
{
    ui->setupUi(this);

    if (txID.isEmpty() && txHEX.isEmpty())
    	 	return;

    if (txHEX.isEmpty())
    {
			    //1. txID
			    QString txIDdesc = txID.left(64);

			    //2. hex code of transaction(getrawtransaction)
			    uint256 hash;
			    hash.SetHex(txID.toStdString().c_str());

			    CTransaction tx;
			    uint256 hashBlock = 0;
			    if (!GetTransaction(hash, tx, hashBlock))
			    {
							QMessageBox::warning(this, windowTitle(), tr("No information available about transaction"), QMessageBox::Ok, QMessageBox::Ok);
					}

			    CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
			    ssTx << tx;
			    string strHex = HexStr(ssTx.begin(), ssTx.end());

			    QString txHexCode = QString::fromStdString(strHex);
			    ui->detailText->setText(txHexCode);
		} else  {
					ui->detailText->setText(txHEX);
		}
}

SendRawDialog::~SendRawDialog()
{
    delete ui;
}

void SendRawDialog::setModel(WalletModel *model)
{
    this->model = model;
}

void SendRawDialog::on_exitButton_clicked()
{
    close();
}

void SendRawDialog::on_sendButton_clicked()
{
    //3. send (sendrawtransaction)

    string strHex = ui->detailText->toPlainText().toStdString();

    // deserialize binary data stream
    CTransaction tx;
    try {
		    vector<unsigned char> txData(ParseHex(strHex.c_str()));
		    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
        ssData >> tx;
    }
    catch (std::exception &e) {
        QMessageBox::warning(this, windowTitle(), tr("TX decode failed"), QMessageBox::Ok, QMessageBox::Ok);
        return;
    }
    uint256 hashTx = tx.GetHash();

    // See if the transaction is already in a block
    // or in the memory pool:
    CTransaction existingTx;
    uint256 hashBlock = 0;
    if (GetTransaction(hashTx, existingTx, hashBlock))
    {
        if (hashBlock != 0)
        {
            QMessageBox::warning(this, windowTitle(), tr("transaction already in block %1").arg(QString::fromStdString(hashBlock.GetHex())), QMessageBox::Ok, QMessageBox::Ok);
						return;
         }
        // Not in block, but already in the memory pool; will drop through to re-relay it.
    }
    else
    {
        // push to local node
        if (!AcceptToMemoryPool(mempool, tx, true, NULL))
        {
            QMessageBox::warning(this, windowTitle(), tr("TX rejected"), QMessageBox::Ok, QMessageBox::Ok);
        		return;
      	}
    }
    RelayTransaction(tx, hashTx);
		return;
}


text:
<?php
/**
 * User: Peter J. Kambey
 * Date: 14-07-2016
 * Time: 00:22
 */
namespace common\components;

use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;

/**
 * Class SqlToTimestampBehavior
 * @package common\behaviors
 */
class IndoDateTimeBehavior extends Behavior
{
    /**
     * Attribute names that should be converted
     * @var array
     */
    public $attributes = [];

    /**
     * The format to convert to and from
     * @var string
     */
    public $indoFormatDate = 'php:d-m-Y';
    public $indoFormatDateTime = 'php:d-m-Y H:i';

    /**
     * @return array
     */
    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
            //ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeSave',

            //ActiveRecord::EVENT_AFTER_VALIDATE => 'afterFind',
            //ActiveRecord::EVENT_AFTER_INSERT => 'afterFind',
            //ActiveRecord::EVENT_AFTER_UPDATE => 'afterFind',
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
        ];
    }

    /**
     * @param $event
     */
    public function beforeSave($event)
    {
        foreach ($event->sender->tableSchema->columns as $columnName => $column) {
            if (($column->dbType == 'date')) {
                $event->sender->$columnName = Yii::$app->formatter->asDate($event->sender->$columnName, 'php:Y-m-d');
            }
            if (($column->dbType == 'datetime')) {
                if (strlen($event->sender->$columnName) == 5)
                    $event->sender->$columnName = date("Y-m-d") . " " . $event->sender->$columnName;

                $event->sender->$columnName = Yii::$app->formatter->asDate($event->sender->$columnName, 'php:Y-m-d H:i:s');
            }
        }
        return true;
    }

    public function afterFind($event)
    {
        foreach ($event->sender->tableSchema->columns as $columnName => $column) {
            if (($column->dbType != 'date') and ($column->dbType != 'datetime'))
                continue;
            if (!strlen($event->sender->$columnName)) {
                $event->sender->$columnName = null;
                continue;
            }
            if ($column->dbType == 'date' && $event->sender->$columnName != null) {
                $event->sender->$columnName = Yii::$app->formatter->asDate($event->sender->$columnName, $this->indoFormatDate);
            } elseif ($column->dbType == 'datetime' && $event->sender->$columnName != null) {
                $event->sender->$columnName = Yii::$app->formatter->asDatetime($event->sender->$columnName, $this->indoFormatDateTime);
            }
        }
        return true;
    }

}


text:
// Copyright (c) Microsoft Corporation.  All rights reserved.

using System.Collections.Generic;
using System.IO;
using ExamplesFx.ColorCode.Parsing;

namespace ExamplesFx.ColorCode
{
    /// <summary>
    /// Defines the contract for a source code formatter.
    /// </summary>
    internal interface IFormatter
    {
        /// <summary>
        /// Writes the parsed source code to the ouput using the specified style sheet.
        /// </summary>
        /// <param name="parsedSourceCode">The parsed source code to format and write to the output.</param>
        /// <param name="scopes">The captured scopes for the parsed source code.</param>
        /// <param name="styleSheet">The style sheet according to which the source code will be formatted.</param>
        /// <param name="textWriter">The text writer to which the formatted source code will be written.</param>
        void Write(string parsedSourceCode,
            IList<Scope> scopes,
            IStyleSheet styleSheet,
            TextWriter textWriter);

        /// <summary>
        /// Generates and writes the footer to the output.
        /// </summary>
        /// <param name="styleSheet">The style sheet according to which the footer will be generated.</param>
        /// <param name="textWriter">The text writer to which footer will be written.</param>
        void WriteFooter(IStyleSheet styleSheet,
            TextWriter textWriter);

        /// <summary>
        /// Generates and writes the header to the output.
        /// </summary>
        /// <param name="styleSheet">The style sheet according to which the header will be generated.</param>
        /// <param name="textWriter">The text writer to which header will be written.</param>
        void WriteHeader(IStyleSheet styleSheet,
            TextWriter textWriter);
    }
}


text:
namespace Lucene.Net.Search.Similarities
{

    ///
    /// Normalization model in which the term frequency is inversely related to the
    /// length.
    ///
While this model is parameterless in the
    ///
    /// original article, the thesis
    /// introduces the parameterized variant.
    /// The default value for the {@code c} parameter is {@code 1}.

    /// @lucene.experimental
    ///
    public class NormalizationH2 : Normalization
    {
        private readonly float c;

        ///
        /// Creates NormalizationH2 with the supplied parameter c.
        /// <param name="c"> hyper-parameter that controls the term frequency
        /// normalization with respect to the document length. </param>
        public NormalizationH2(float c)
        {
            this.c = c;
        }

        ///
        /// Calls <seealso cref="#NormalizationH2(float) NormalizationH2(1)"/>
        ///
        public NormalizationH2()
            : this(1)
        {
        }

        public override sealed float Tfn(BasicStats stats, float tf, float len)
        {
            return (float)(tf * SimilarityBase.Log2(1 + c * stats.AvgFieldLength / len));
        }

        public override string ToString()
        {
            return "2";
        }

        ///
        /// Returns the c parameter.
        /// <seealso cref= #NormalizationH2(float) </seealso>
        public virtual float C
        {
            get
            {
                return c;
            }
        }
    }
}


text:
import * as actions from './actions';
import actionTypes from './actionTypes';
import selectors from './selectors';
import reducers from './reducers';

export { actions, actionTypes, reducers, selectors };