text:
// +build !windows

package reaper

import (
	"os/exec"
	"sync"
	"time"

	runc "github.com/containerd/go-runc"
	"github.com/pkg/errors"
	"golang.org/x/sys/unix"
)

// ErrNoSuchProcess is returned when the process no longer exists
var ErrNoSuchProcess = errors.New("no such process")

const bufferSize = 32

type subscriber struct {
	sync.Mutex
	c      chan runc.Exit
	closed bool
}

func (s *subscriber) close() {
	s.Lock()
	if s.closed {
		s.Unlock()
		return
	}
	close(s.c)
	s.closed = true
	s.Unlock()
}

func (s *subscriber) do(fn func()) {
	s.Lock()
	fn()
	s.Unlock()
}

// Reap should be called when the process receives an SIGCHLD.  Reap will reap
// all exited processes and close their wait channels
func Reap() error {
	now := time.Now()
	exits, err := reap(false)
	for _, e := range exits {
		done := Default.notify(runc.Exit{
			Timestamp: now,
			Pid:       e.Pid,
			Status:    e.Status,
		})

		select {
		case <-done:
		case <-time.After(1 * time.Second):
		}
	}
	return err
}

// Default is the default monitor initialized for the package
var Default = &Monitor{
	subscribers: make(map[chan runc.Exit]*subscriber),
}

// Monitor monitors the underlying system for process status changes
type Monitor struct {
	sync.Mutex

	subscribers map[chan runc.Exit]*subscriber
}

// Start starts the command a registers the process with the reaper
func (m *Monitor) Start(c *exec.Cmd) (chan runc.Exit, error) {
	ec := m.Subscribe()
	if err := c.Start(); err != nil {
		m.Unsubscribe(ec)
		return nil, err
	}
	return ec, nil
}

// Wait blocks until a process is signal as dead.
// User should rely on the value of the exit status to determine if the
// command was successful or not.
func (m *Monitor) Wait(c *exec.Cmd, ec chan runc.Exit) (int, error) {
	for e := range ec {
		if e.Pid == c.Process.Pid {
			// make sure we flush all IO
			c.Wait()
			m.Unsubscribe(ec)
			return e.Status, nil
		}
	}
	// return no such process if the ec channel is closed and no more exit
	// events will be sent
	return -1, ErrNoSuchProcess
}

// Subscribe to process exit changes
func (m *Monitor) Subscribe() chan runc.Exit {
	c := make(chan runc.Exit, bufferSize)
	m.Lock()
	m.subscribers[c] = &subscriber{
		c: c,
	}
	m.Unlock()
	return c
}

// Unsubscribe to process exit changes
func (m *Monitor) Unsubscribe(c chan runc.Exit) {
	m.Lock()
	s, ok := m.subscribers[c]
	if !ok {
		m.Unlock()
		return
	}
	s.close()
	delete(m.subscribers, c)
	m.Unlock()
}

func (m *Monitor) getSubscribers() map[chan runc.Exit]*subscriber {
	out := make(map[chan runc.Exit]*subscriber)
	m.Lock()
	for k, v := range m.subscribers {
		out[k] = v
	}
	m.Unlock()
	return out
}

func (m *Monitor) notify(e runc.Exit) chan struct{} {
	const timeout = 1 * time.Millisecond
	var (
		done    = make(chan struct{}, 1)
		timer   = time.NewTimer(timeout)
		success = make(map[chan runc.Exit]struct{})
	)
	stop(timer, true)

	go func() {
		defer close(done)

		for {
			var (
				failed      int
				subscribers = m.getSubscribers()
			)
			for _, s := range subscribers {
				s.do(func() {
					if s.closed {
						return
					}
					if _, ok := success[s.c]; ok {
						return
					}
					timer.Reset(timeout)
					recv := true
					select {
					case s.c <- e:
						success[s.c] = struct{}{}
					case <-timer.C:
						recv = false
						failed++
					}
					stop(timer, recv)
				})
			}
			// all subscribers received the message
			if failed == 0 {
				return
			}
		}
	}()
	return done
}

func stop(timer *time.Timer, recv bool) {
	if !timer.Stop() && recv {
		<-timer.C
	}
}

// exit is the wait4 information from an exited process
type exit struct {
	Pid    int
	Status int
}

// reap reaps all child processes for the calling process and returns their
// exit information
func reap(wait bool) (exits []exit, err error) {
	var (
		ws  unix.WaitStatus
		rus unix.Rusage
	)
	flag := unix.WNOHANG
	if wait {
		flag = 0
	}
	for {
		pid, err := unix.Wait4(-1, &ws, flag, &rus)
		if err != nil {
			if err == unix.ECHILD {
				return exits, nil
			}
			return exits, err
		}
		if pid <= 0 {
			return exits, nil
		}
		exits = append(exits, exit{
			Pid:    pid,
			Status: exitStatus(ws),
		})
	}
}

const exitSignalOffset = 128

// exitStatus returns the correct exit status for a process based on if it
// was signaled or exited cleanly
func exitStatus(status unix.WaitStatus) int {
	if status.Signaled() {
		return exitSignalOffset + int(status.Signal())
	}
	return status.ExitStatus()
}


text:
require_dependency 'libraetd/lib/helpers/etd_helper'

class SubmissionController < ApplicationController

  include AuthenticationHelper
  include UrlHelper
  include ServiceHelper
  include StatisticsHelper
  include WorkHelper

  #skip_before_action :require_auth, only: [ 'public_view' ]
  before_action :authenticate_user!, only: [ 'submit']
  layout "public"

  def public_view
    @id = params[:id]
    @work = get_generic_work( @id )

    @can_view = can_view(@work)
    if @can_view
      @is_preview = @work.is_draft?
      if !@is_preview # on the public page, there shouldn't be the the concept of logging in.
        @hide_login_controls = true
      end
      set_debugging_override()
      @files = get_file_sets(@work)

      # save work view statistics
      record_work_view_event( @work.id ) if @is_preview == false
    else
      render404public()
    end
  end

  def submit
    id = params[:id]
    work = get_generic_work( id )

    if work.present?

      work.draft = 'false'
      if work.embargo_state != Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC &&
          work.embargo_period != GenericWork::EMBARGO_VALUE_CUSTOM
        end_date = GenericWork.calculate_embargo_release_date( work.embargo_period )
        work.embargo_end_date = DateTime.new(end_date.year, end_date.month, end_date.day)
      end

      # set the publication date
      work.date_published = Time.zone.today.strftime( "%Y-%m-%d" )

      # save the changes
      work.save!

      # update the DOI service with the completed metadata
      update_doi_metadata(work)

      # update SIS as necessary
      update_submitted_state(work)

      # create/update the ORCID entry
      OrcidSyncJob.perform_later work.id, current_user.id

      # PER: All actual work is done before the emails are sent in case the email system crashes again.

      # send the author email that they have successfully completed things
      send_author_email(work)

      # send the registrar email that they have successfully completed things
      send_registrar_email(work)
    end

    notice = if work.identifier
      "Thank you for submitting your thesis. Be sure to make note of and refer to the Persistent Link when you refer to this work."
    else
      "Thank you for submitting your thesis. The Persistent Link could not be generated at this time. Check back later for the permananent URL."
    end

    redirect_to locally_hosted_work_url( id ), :flash => { :notice => notice }
  end

  def unpublish
    if ENV['ENABLE_TEST_FEATURES'].present?
      id = params[:id]
      work = get_generic_work( id )
      if work.present?
        work.draft = 'true'
        work.save!
      end
      redirect_to locally_hosted_work_url( id )
    end
  end

  private

  # send the author email that they have successfully completed things
  def send_author_email( work )

    return if work.nil?
    author = Helpers::EtdHelper::lookup_user( User.cid_from_email( work.creator ) )
    return if author.nil?

    # send the email
    ThesisMailers.thesis_submitted_author( work, author.display_name, MAIL_SENDER ).deliver_later

  end

  # send the registrar email that the student has successfully completed things
  def send_registrar_email( work )

    return if work.nil?

    # do nothing for SIS work
    return if work.is_sis_thesis?

    # do nothing if the registrar is blank
    return if work.registrar_computing_id.blank?

    # lookup the registrar info and return if we cannot find them
    registrar = Helpers::EtdHelper::lookup_user( work.registrar_computing_id )
    return if registrar.nil?

    # lookup author information
    author_id = User.cid_from_email( work.creator )
    author = Helpers::EtdHelper::lookup_user( author_id )
    author_name = author.nil? ? author_id : author.display_name

    # send the email
    ThesisMailers.thesis_submitted_registrar( work,
                                             author_name,
                                             registrar.display_name,
                                             registrar.email,
                                             MAIL_SENDER ).deliver_later

  end

  def can_view(work)

    # can view if the work exists and is published, or if it is draft and the owner is logged in.

    # no work, no access
    if work.nil?
      puts "==> work is undefined; view access is DENIED"
      return false
    end

    # this work is owned by the current user regardless of visibility
    if current_user.present? && work.is_mine?( current_user.email )
      puts "==> work is user owned; view access is GRANTED"
      return true
    end

    # if this work has NOT been published.
    if work.is_draft?
      puts "==> work is draft; view access is DENIED"
      return false
    end

    puts "==> work is published; view access is GRANTED"
    return true
  end

  def get_file_sets(work)
    show_files = view_context.allow_file_access(work)
    return [] if !show_files
    file_sets = work.file_sets
    files = []
    file_sets.each { |file|
      # ensure the title on the public page is not blank
      title = file.title.join(" ")
      title = file.label if title.blank?
      title = 'UNKNOWN' if title.blank?

      files.push({
        title: title,
        location: download_path(file),
        date: file.date_uploaded,
        id: file.id
      })
    }
    # ensure they are sorted in upload date order so the oldest is listed first
    files = files.sort { |a,b|
      a[:date] <=> b[:date]
    }

    return files
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Sitecore.FakeDb.Pipelines.AddDbItem
{
    using System.Linq;
    using Sitecore.Data;
    using Sitecore.FakeDb.Data.Engines;

    public class CreateTemplate
    {
        public virtual void Process(AddDbItemArgs args)
        {
            var item = args.DbItem;
            var dataStorage = args.DataStorage;

            var isResolved = this.ResolveTemplate(item, dataStorage);
            if (isResolved)
            {
                new TemplateTreeBuilder().Build(item);

                return;
            }

            if (!ID.IsNullOrEmpty(item.TemplateID) && dataStorage.GetFakeTemplate(item.TemplateID) != null)
            {
                return;
            }

            if (item.TemplateID == ID.Null)
            {
                item.TemplateID = ID.NewID;
            }

            var template = new DbTemplate(item.Name, item.TemplateID)
                {
                    Generated = true
                };

            foreach (var itemField in item.Fields)
            {
                var templatefield = new DbField(itemField.Name, itemField.ID)
                    {
                        Shared = itemField.Shared,
                        Type = itemField.Type,
                        Source = itemField.Source
                    };
                template.Add(templatefield);
            }

            new TemplateTreeBuilder().Build(item);

            dataStorage.AddFakeItem(template);
        }

        protected virtual bool ResolveTemplate(DbItem item, DataStorage dataStorage)
        {
            if (item.TemplateID == TemplateIDs.Template)
            {
                return true;
            }

            if (item.TemplateID == TemplateIDs.BranchTemplate)
            {
                return true;
            }

            if (this.ResolveBranch(item, dataStorage))
            {
                return true;
            }

            if (dataStorage.GetFakeTemplate(item.TemplateID) != null)
            {
                return true;
            }

            if (!ID.IsNullOrEmpty(item.TemplateID))
            {
                return false;
            }

            var fingerprint = string.Concat(item.Fields.Select(f => f.Name));

            // find an item with a generated template that has a matching fields set
            var sourceItem = dataStorage.GetFakeItems()
                .Where(si => si.TemplateID != TemplateIDs.Template)
                .Where(si => dataStorage.GetFakeTemplate(si.TemplateID) != null)
                .Where(si => dataStorage.GetFakeTemplate(si.TemplateID).Generated)
                .FirstOrDefault(si => string.Concat(si.Fields.Select(f => f.Name)) == fingerprint);

            if (sourceItem == null)
            {
                return false;
            }

            // reuse the template
            item.TemplateID = sourceItem.TemplateID;

            return true;
        }

        protected virtual bool ResolveBranch(DbItem item, DataStorage dataStorage)
        {
            if (item.ParentID == ItemIDs.BranchesRoot && ID.IsNullOrEmpty(item.TemplateID))
            {
                item.TemplateID = TemplateIDs.BranchTemplate;
                return true;
            }

            if (ID.IsNullOrEmpty(item.TemplateID))
            {
                return false;
            }

            var branchItem = dataStorage.GetFakeItem(item.TemplateID);
            if (branchItem == null)
            {
                return false;
            }

            if (branchItem.TemplateID != TemplateIDs.BranchTemplate)
            {
                return false;
            }

            item.BranchId = branchItem.ID;
            item.TemplateID = ID.NewID;

            return false;
        }
    }
}


text:
package android.support.v4.widget;

import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.PopupWindow;

/**
 * Helper for accessing features in PopupWindow introduced after API level 4
 * in a backwards compatible fashion.
 */
public class PopupWindowCompat {
    /**
     * Interface for the full API.
     */
    interface PopupWindowImpl {
        public void showAsDropDown(PopupWindow popup, View anchor, int xoff, int yoff,
                int gravity);
    }

    /**
     * Interface implementation that doesn't use anything above v4 APIs.
     */
    static class BasePopupWindowImpl implements PopupWindowImpl {
        @Override
        public void showAsDropDown(PopupWindow popup, View anchor, int xoff, int yoff,
                int gravity) {
            popup.showAsDropDown(anchor, xoff, yoff);
        }
    }

    /**
     * Interface implementation for devices with at least KitKat APIs.
     */
    static class KitKatPopupWindowImpl extends BasePopupWindowImpl {
        @Override
        public void showAsDropDown(PopupWindow popup, View anchor, int xoff, int yoff,
                int gravity) {
            PopupWindowCompatKitKat.showAsDropDown(popup, anchor, xoff, yoff, gravity);
        }
    }

    /**
     * Select the correct implementation to use for the current platform.
     */
    static final PopupWindowImpl IMPL;
    static {
        final int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 19) {
            IMPL = new KitKatPopupWindowImpl();
        } else {
            IMPL = new BasePopupWindowImpl();
        }
    }

    private PopupWindowCompat() {
        // This class is not publicly instantiable.
    }

    /**
     *
Display the content view in a popup window anchored to the bottom-left
     * corner of the anchor view offset by the specified x and y coordinates.
     * If there is not enough room on screen to show
     * the popup in its entirety, this method tries to find a parent scroll
     * view to scroll. If no parent scroll view can be scrolled, the bottom-left
     * corner of the popup is pinned at the top left corner of the anchor view.

     *
If the view later scrolls to move anchor to a different
     * location, the popup will be moved correspondingly.

     *
     * @param popup the PopupWindow to show
     * @param anchor the view on which to pin the popup window
     * @param xoff A horizontal offset from the anchor in pixels
     * @param yoff A vertical offset from the anchor in pixels
     * @param gravity Alignment of the popup relative to the anchor
     */
    public static void showAsDropDown(PopupWindow popup, View anchor, int xoff, int yoff,
            int gravity) {
        IMPL.showAsDropDown(popup, anchor, xoff, yoff, gravity);
    }
}


text:
package monix.tail.internal

import cats.effect.Sync
import cats.syntax.all._
import monix.tail.Iterant
import monix.tail.Iterant.{Concat, Halt, Last, Next, NextBatch, NextCursor, Scope, Suspend}
import monix.tail.batches.BatchCursor
import scala.annotation.tailrec
import scala.collection.immutable.Queue
import scala.collection.mutable

private[tail] object IterantDropLast {
  /**
    * Implementation for `Iterant#dropLast`
    */
  def apply[F[_], A](source: Iterant[F, A], n: Int)(implicit F: Sync[F]): Iterant[F, A] = {
    if (n <= 0) source
    else Suspend(F.delay(new Loop(n).apply(source)))
  }

  private final class Loop[F[_], A](n: Int)(implicit F: Sync[F])
    extends Iterant.Visitor[F, A, Iterant[F, A]] {

    private[this] var queue = Queue[A]()
    private[this] var length = 0

    def visit(ref: Next[F, A]): Iterant[F, A] = {
      queue = queue.enqueue(ref.item)
      if (length >= n) {
        val (nextItem, nextQueue) = queue.dequeue
        queue = nextQueue
        Next(nextItem, ref.rest.map(this))
      }
      else {
        length += 1
        Suspend(ref.rest.map(this))
      }
    }

    def visit(ref: NextBatch[F, A]): Iterant[F, A] =
      visit(ref.toNextCursor())

    def visit(ref: NextCursor[F, A]): Iterant[F, A] = {
      val NextCursor(cursor, rest) = ref
      val limit = cursor.recommendedBatchSize
      val buffer = mutable.Buffer[A]()

      @tailrec
      def queueLoop(queue: Queue[A], toProcess: Int): Queue[A] = {
        if (!(toProcess > 0 && cursor.hasNext()))
          queue
        else {
          val updatedQueue = queue.enqueue(cursor.next())
          if (length >= n) {
            val (item, dequeuedQueue) = updatedQueue.dequeue
            buffer.append(item)
            queueLoop(dequeuedQueue, toProcess - 1)
          } else {
            length += 1
            queueLoop(updatedQueue, toProcess - 1)
          }
        }
      }

      queue = queueLoop(queue, limit)
      val next: F[Iterant[F, A]] = if (cursor.hasNext()) F.pure(ref) else rest
      NextCursor(BatchCursor.fromSeq(buffer), next.map(this))
    }

    def visit(ref: Suspend[F, A]): Iterant[F, A] =
      Suspend(ref.rest.map(this))

    def visit(ref: Concat[F, A]): Iterant[F, A] =
      ref.runMap(this)

    def visit[S](ref: Scope[F, S, A]): Iterant[F, A] =
      ref.runMap(this)

    def visit(ref: Last[F, A]): Iterant[F, A] = {
      queue = queue.enqueue(ref.item)
      if (length >= n) {
        val (nextItem, nextQueue) = queue.dequeue
        queue = nextQueue
        Last(nextItem)
      } else {
        length += 1
        Halt(None)
      }
    }

    def visit(ref: Halt[F, A]): Iterant[F, A] =
      ref

    def fail(e: Throwable): Iterant[F, A] =
      Iterant.raiseError(e)
  }
}


text:
//
//  GeneralHelper.m
//  MackNotas
//
//  Created by Caio Remedio on 26/04/15.
//  Copyright (c) 2015 Caio Remedio. All rights reserved.
//

#import "GeneralHelper.h"
#import "LocalUser.h"

#include <sys/sysctl.h>
#include <sys/utsname.h>

@implementation GeneralHelper

#pragma mark - Methods

+ (NSString *)pathForUserDataFile {

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    return [path stringByAppendingPathComponent:DATA_FILE_NAME];
}

+ (NSString *)pathForDBFile {

    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    return [path stringByAppendingPathComponent:DATA_DATABASE_FILE];
}

+ (NSString *)updatedTodayAt {
    NSDateFormatter *dF = [NSDateFormatter new];
    NSDate *agoraDate = [NSDate date];

    [dF setDateFormat:@"'Hoje às 'HH:mm"];

    return [dF stringFromDate:agoraDate];
}

+ (NSString *)getDeviceModel {

    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine
                              encoding:NSUTF8StringEncoding];

}

+ (NSString *)getOSVersion {

    return [UIDevice currentDevice].systemVersion;
}

+ (NSString *)decodeJSON:(NSArray *)JSON {

    NSData *buffer = [NSKeyedArchiver archivedDataWithRootObject:JSON];
    NSMutableArray *arrayJSON_copy = [NSKeyedUnarchiver unarchiveObjectWithData:buffer];

    NSError *error;
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:arrayJSON_copy
                        options:NSJSONWritingPrettyPrinted
                        error:&error];
    NSString *json_stringfied = [[NSString alloc] initWithData:jsonData
                                                      encoding:NSUTF8StringEncoding];

    return json_stringfied;
}

+ (NSURLRequest *)requestWithString:(NSString *)url {

    return [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
}

+ (UIBarButtonItem *)barButtonWithLoadingStatus:(BOOL)isLoading {

    UIBarButtonItem *barBtn;

    if (isLoading) {
        UIActivityIndicatorView *actInd = [[UIActivityIndicatorView alloc]
                                           initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        barBtn = [[UIBarButtonItem alloc] initWithCustomView:actInd];
    }
    else {

    }

    return barBtn;
}

+ (void)showActivityIndicatorOnNavBarRight:(BOOL)shouldShow
                         WithRefreshButton:(UIBarButtonItem *)refreshBtn
                         andNavigationItem:(UINavigationItem *)navItem {

    UIBarButtonItem *btn;

    if (shouldShow) {
        UIActivityIndicatorView *actInd = [[UIActivityIndicatorView alloc]
                                           initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [actInd startAnimating];
        btn.enabled = NO;
        btn = [[UIBarButtonItem alloc] initWithCustomView:actInd];
    }
    else {
        btn = refreshBtn;
    }

    [UIView animateWithDuration:0.4f animations:^{
        navItem.rightBarButtonItem.customView.alpha = shouldShow ? 1.0f : 0.0f;
    } completion:^(BOOL finished) {
        navItem.rightBarButtonItem = btn;
    }];
}

#pragma mark - Dates Methods

+ (BOOL)isOnFirstSemester {

    return [GeneralHelper currentMonth] < 8;
}

+ (NSInteger)currentMonth {

    NSDate *today = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"MM"];

    return [formatter stringFromDate:today].integerValue;
}

+ (NSInteger)currentMonthForArray {

    NSDate *today = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"MM"];

    NSInteger currentMonth = [formatter stringFromDate:today].integerValue;

    if (currentMonth < 8) {
        return currentMonth - 1;
    }

    return currentMonth - 8;
}

+ (NSInteger)currentDay {

    NSDate *today = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"dd"];

    return [formatter stringFromDate:today].integerValue;
}

+ (NSInteger)currentWeekDayNumber {

    NSDate *today = [NSDate date];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"e"];

    return [formatter stringFromDate:today].integerValue;
}

+ (BOOL)isTodayWithDay:(NSString *)day andMonth:(NSString *)month {

    NSInteger dayNumber = day.integerValue;
    NSInteger monthNumber = month.integerValue;

    return ([self currentDay] == dayNumber &&
            [self currentMonth] == monthNumber);
}

+ (BOOL)isTomorrowWithDay:(NSString *)day andMonth:(NSString *)month {

    NSInteger dayProva = day.integerValue;
    NSInteger monthProva = month.integerValue;

    /**
     *  Para evitar que o dia 31 se transforme em 32, mes 12 -> mes 13 etc...
     */
    NSDateComponents *dayComponent = [NSDateComponents new];
    dayComponent.day = 1;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *tomorrowDate = [calendar dateByAddingComponents:dayComponent
                                                     toDate:[NSDate date]
                                                    options:0];

    NSDateFormatter *dateFormatDay = [NSDateFormatter new];
    dateFormatDay.dateFormat = @"dd";

    NSDateFormatter *dateFormatMonth = [NSDateFormatter new];
    dateFormatMonth.dateFormat = @"MM";

    NSInteger dayTomorrow = [dateFormatDay stringFromDate:tomorrowDate].integerValue;
    NSInteger monthTomorrow = [dateFormatMonth stringFromDate:tomorrowDate].integerValue;

    return (dayProva == dayTomorrow &&
            monthProva == monthTomorrow);
}

+ (BOOL)isEmailValid:(NSString *)email {

    NSString *emailRegEx =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];

    return [predicate evaluateWithObject:email];
}

@end


text:
var changeCase = require('change-case');

var renameProperty = function(obj, oldName, newName) {
    if(oldName == newName) return;

    obj[newName] = obj[oldName];
    delete obj[oldName];
};

// TODO change it to column aliases in select query - it will be faster and cleaner
var renamePropertiesToCamelCase = function(data) {
    if(data instanceof Array) {
        for(var i = 0; i < data.length; i++)
            for(var prop in data[i])
                renameProperty(data[i], prop, changeCase.camelCase(prop));
    } else {
        for(var prop in data)
            renameProperty(data, prop, changeCase.camelCase(prop));
    }

    return data;
};

module.exports = {
    renamePropertiesToCamelCase: renamePropertiesToCamelCase
};


text:
package org.appng.search.indexer;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class ParseTagsTest {

	private ParseTags parseTags = new ParseTags("appNG");

	@Test
	public void testFile() throws Exception {
		Map<String, StringBuilder> parsed = parseTags.parse(new File("pages/en/42.jsp"));
		Assert.assertEquals("The Hitchhiker's Guide to the Galaxy", parsed.get("title").toString());
		String contents = parsed.get("contents").toString();
		String expected = "The Hitchhiker's Guide to the Galaxy is a comic science fiction series";
		Assert.assertTrue(contents.startsWith(expected));
	}

	@Test
	public void testNestedTags() throws Exception {
		String in = ""
				+ " A "
				+ " B "
				+ " C " + " D ";
		Map<String, StringBuilder> parsed = new ParseTags("a").parse(new ByteArrayInputStream(in.getBytes()));
		System.out.println(parsed);
		Assert.assertEquals("A", parsed.get("field1").toString());
		Assert.assertEquals("B", parsed.get("field2").toString());
		Assert.assertNull(parsed.get("field3"));
		Assert.assertEquals("A B D", parsed.get("contents").toString());
	}

	@Test
	public void testNotIndexed() throws Exception {
		String in = "<appNG:searchable index=\"false\">"
				+ "<appNG:searchable index=\"true\" field=\"field1\"> A </appNG:searchable>"
				+ "<appNG:searchable index=\"true\" field=\"field2\"> B </appNG:searchable>"
				+ "<appNG:searchable index=\"false\"> C </appNG:searchable>" + " D </appNG:searchable>";
		Map<String, StringBuilder> parsed = parseTags.parse(new ByteArrayInputStream(in.getBytes()));
		System.out.println(parsed);
		Assert.assertNull(parsed.get("field1"));
		Assert.assertNull(parsed.get("field2"));
		Assert.assertNull(parsed.get("field3"));
		Assert.assertNull(parsed.get("contents"));
	}

}


text:
/* admin Login Page */
	function showSignForm(){
		$('#signInput').show()
		$('#signInput .form-control').attr("required",true)
		$('[name="formlabel"]').html('Already Had Account')
		$('[name="log"]').html('Sign up')
		$('[name="log"]').attr('name','sign')
		$('[name="pwd"]').change(function(){checkpwd()})
		$('[name="formlabel"]').click(function(){location.href="login.php"})
		$('[name="pwd"]').val('')
		checkNewName('admin')
	}
	/* Show real password */
	function seepwd(i){
		pwd = document.getElementsByName(i)[0];
		pwd.type='text';
		this.onmouseup = function(){
			pwd.type='password';
		};
	}
	/* Add 0 in date time when it less than 10*/
	function add0(e){
		if(e.toString().length==1){
			return '0'+e;
		}else{
			return e
		}
	}
	/* Print current time */
	function printTime(){
		var d = new Date();
		var year = d.getFullYear();
		var day = add0(d.getDate());
		var month = add0(d.getMonth()+1);
		var hours = add0(d.getHours());
		var mins = add0(d.getMinutes());
		var secs = add0(d.getSeconds());
		$('#time').html(year+'/'+month+'/'+day+' '+hours+':'+mins+':'+secs);
	}
	/* use ajax to Check username if exist */
	function checkNewName(pg){
		$('[name="username"]').val($('[name="username"]').val().replace(" ",""))
		if($('[name="username"]').val().length>0 && $('[name="sign"]').length>0){
			$.ajax({
				url:'ajax.php',
				data:{"usercheck":encodeURI(encodeURI($('[name="username"]').val())),"page":pg},
				success:function(data){
					if(data.used=='used'){
						$('[name="username"]').attr('class','form-control alert-danger')
						$('[name="username"]').next().attr('class','seepwd alert-danger')
						$('[name="username"]').next().children('i').attr('class','fa fa-close')
						$('[name="sign"]').attr('disabled','true')
					}else if(data.used=='ok'){
						$('[name="username"]').attr('class','form-control alert-success')
						$('[name="username"]').next().attr('class','seepwd alert-success')
						$('[name="username"]').next().children('i').attr('class','fa fa-check')
					}else if(data.used=='empty'){
						$('[name="username"]').attr('class','form-control')
						$('[name="username"]').next().attr('class','seepwd hidden')
					}
				},
				type:'POST',
				dataType:'json',
				beforeSend:function(){
					$('[name="username"]').next().attr('class','seepwd btn-warning')
					$('[name="username"]').next().children('i').attr('class','fa fa-spinner fa-spin')
				}
			});
		}else{
			$('[name="username"]').attr('class','form-control')
			$('[name="username"]').next().attr('class','seepwd hidden')
		}
	}
	/* use ajax to change order rate */
	function changeRate(){
		if(confirm('Do you want to Rate the order?')){
			starsnum = $('[name="ratelevel"]').val();
			orid = $('[name="rateordid"]').val();
			$.ajax({
				url:'ajax.php',
				data:{"rate":starsnum,"orderid":orid},
				type:'POST'
			});
			stars = ''
			for(var v=0;v<starsnum;v++){
				stars += ""
			}
			$('#rate'+orid).html(stars)
			$('#rate'+orid).attr('onclick',"rateOrder('"+orid+"','"+starsnum+"')")
		}$('#modal-rate').click()
	}
	/* use ajax to change order status */
	function changeOrdStatus(){
		if(confirm('Do you want to change the order status?')){
			orid = $('[name="ordstatusid"]').val();
			status = $('[name="orderstatus"]').val();
			statusname = $('[name="statusname"]').val();
			$.ajax({
				url:'ajax.php',
				data:{"status":status,"orderid":orid},
				type:'POST'
			});
			if(status==3){
				unpaidstyle(orid);
			}else if(status<=2){
				normalstyle(orid,status);
			}
			$('#status'+orid).html(statusname)
			if(status==2){
				$('#status'+orid).html(" "+statusname)
			}
		}$('#modal-status').click()
	}
	/* use ajax to check customer username */
	function checkCusName(){
		$('[name="username"]').val($('[name="username"]').val().replace(" ",""))
		if($('[name="username"]').val().length>0){
			$.ajax({
				url:'ajax.php',
				data:{"usercheck":encodeURI(encodeURI($('[name="username"]').val())),"page":'employee'},
				success:function(data){
					if(data.used=='used'){
						$('[name="username"]').attr('class','form-control alert-danger')
						$('[name="username"]').next().attr('class','alert-danger')
						$('[name="username"]').next().children('i').attr('class','fa fa-close')
						$('[name="submit"]').attr('disabled',true)
					}else if(data.used=='ok'){
						$('[name="username"]').attr('class','form-control alert-success')
						$('[name="username"]').next().attr('class','alert-success')
						$('[name="username"]').next().children('i').attr('class','fa fa-check')
						$('[name="submit"]').attr('disabled',false)
					}else if(data.used=='empty'){
						$('[name="username"]').attr('class','form-control')
						$('[name="username"]').next().attr('class','hidden')
						$('[name="submit"]').attr('disabled',true)
					}
				},
				type:'POST',
				dataType:'json',
				beforeSend:function(){
					$('[name="username"]').next().attr('class','seepwd btn-warning')
					$('[name="username"]').next().children('i').attr('class','fa fa-spinner fa-spin')
				}
			});
		}else{
			$('[name="username"]').attr('class','form-control')
			$('[name="username"]').next().attr('class','seepwd hidden')
		}
	}
	/* Check password when sign up */
	function checkpwd(){
		var pwd = document.getElementsByName('pwd')[0];
		var pwdconf = document.getElementsByName('pwdConfirm')[0];
		var btnsubmit = document.getElementsByName('sign')[0];
		if(pwd.value.length<4){
			alert("Your password length is too short! Please type more than 3 word");
			pwd.className = 'form-control alert-danger';
			pwdconf.className = 'form-control';
			pwd.value = '';
			pwdconf.value = '';
			pwd.focus();
			btnsubmit.disabled = true;
		}else{
			if(pwd.value == pwdconf.value){
				pwd.className = 'form-control alert-success';
				pwdconf.className = 'form-control alert-success';
				btnsubmit.disabled = false;
			}else{
				pwdconf.className = 'form-control alert-danger';
				pwdconf.value = '';
				btnsubmit.disabled = true;
			}
		}
	}
	/* report page range label */
	function minrange(ele,id){
		minsup = $(ele).val()
		$('#'+id).html(minsup)
		$.ajax({
			url:'ajax.php',
			data:{"minsup":minsup},
			success:function(data){
				if(data.empty==0){
					var htmls;
					for(var i=0;i<data.cut2.length;i++){
						items = data.cut2[i][0].split(',');
						item_html = ''+items[0]+'	'+items[1]+'	'
						htmls += '
'+item_html+''+data.cut2[i][1]+'	'+data.cut2[i][2]+'	'+data.cut2[i][3]+'
'
					}
					if(data.cut3.length>0){
						htmls += '
Associate Products 1	Associate Products 2	Associate Products 3	Support
'
						for(var i=0;i<data.cut3.length;i++){
							items = data.cut3[i][0].split(',');
							item_html = ''+items[0]+'	'+items[1]+'	'+items[2]+'	'
							htmls += '
'+item_html+''+data.cut3[i][1]+'
'
						}
					}
					$('#resbody').html(htmls)
					$('#nores').hide()
				}else{
					$('#resbody').html('')
					$('#nores').show()
				}
			},
			type:'POST',
			dataType:'json',
			beforeSend:function(){

			}
		});

	}


text:
Voting is a feature that allows federation members to vote on something. At the moment of this document creation federation members can vote to add a new federation member, remove federation member, add hash to whitelisted hashes store or remove hash from there. Whitelisted hashes are being interpreted by other components. For example smart contracts feature uses whitelisted hashes as hashes of smart contracts allowed on the network.

Voting can be enabled or disabled by setting bool variable `PoAConsensusOptions.VotingEnabled` during network setup.

Voting works like that:

1. Federation member calls API that constructs pending voting data
2. When federation member mines a block voting data is included in the special output in coinbase transaction
3. Other federation members do the same and when 51% of fed members voted poll's execution is scheduled (this will happen after max reorg blocks)
4. Change is applied

### Api endpoints

- `getfedmembers` - returns a list of all active federation members.
- `getpendingpolls` - returns a list of all polls that are not executed yet and doesn't have >=51% of fed members voted in favor.
- `getfinishedpolls` - returns a list of polls which were already voted for by >=51% of federation members.
- `schedulevote_addfedmember` - votes in favor of adding a new federation member.
- `schedulevote_kickfedmember` -  votes in favor of removing existing federation member.
- `getwhitelistedhashes` - provides a list of whitelisted hashes.
- `schedulevote_whitelisthash` -  votes in favor of whitelisting a new hash.
- `schedulevote_removehash` - votes in favor of removing existing whitelisted hash.
- `getscheduledvotes` - provides a list of all votes that will be included in the next block federation member mines.

It's important to note that endpoints that start with `schedulevote_` used both for voting in favor of existing poll and also to create a new poll. Voting in favor is done by voting for the same objective as was voted for by another fed member.

### Important architectural details

Because federation can be modified we can't validate all the headers we can download since at some point header might be signed by a federation member we don't yet know about and therefore we can't validate the signature.

To solve this max reorg was introduced to PoA network. Voting result is executed only after max reorg blocks passes. This is needed to make sure that we have enough data to know how federation will look like at any point in the future starting from CT + 1 till CT + max reorg. This gives us guarantee that max reorg headers in from of consensus can always be verified. This logic is in `PoAHeaderSignatureRule`.

Headers that are beyond max reorg from consensus tip and contain a signature that is invalid are marked as insufficient and will be validated again when consensus advances.


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_local"
        android:icon="@drawable/ic_sd_card"
        android:orderInCategory="200"
        android:title="Local"
        app:showAsAction="always" />

    <item
        android:id="@+id/action_toggle"
        android:orderInCategory="100"
        android:title="Toggle"
        app:showAsAction="always" />
</menu>


text:
<?php

class Google_Service_AndroidEnterprise_GroupLicense extends Google_Model
{
  public $acquisitionKind;
  public $approval;
  public $numProvisioned;
  public $numPurchased;
  public $permissions;
  public $productId;

  public function setAcquisitionKind($acquisitionKind)
  {
    $this->acquisitionKind = $acquisitionKind;
  }
  public function getAcquisitionKind()
  {
    return $this->acquisitionKind;
  }
  public function setApproval($approval)
  {
    $this->approval = $approval;
  }
  public function getApproval()
  {
    return $this->approval;
  }
  public function setNumProvisioned($numProvisioned)
  {
    $this->numProvisioned = $numProvisioned;
  }
  public function getNumProvisioned()
  {
    return $this->numProvisioned;
  }
  public function setNumPurchased($numPurchased)
  {
    $this->numPurchased = $numPurchased;
  }
  public function getNumPurchased()
  {
    return $this->numPurchased;
  }
  public function setPermissions($permissions)
  {
    $this->permissions = $permissions;
  }
  public function getPermissions()
  {
    return $this->permissions;
  }
  public function setProductId($productId)
  {
    $this->productId = $productId;
  }
  public function getProductId()
  {
    return $this->productId;
  }
}


text:
Some applications are required to display a large number of locations or markers. Despite the v3 JavaScript API's
significant improvement to performance, naively plotting thousands of markers on a map can quickly lead to to a
degraded user experience. Too many markers on the map cause both visual overload and sluggish interaction with the map.
To overcome this poor performance, the information displayed on the map needs to be simplified, we need a marker
clustering solution.

## Build your marker

By default, the bundle doesn't need any configuration. Most of the service have a default configuration which allows
you to use the given objects like they are. The ``ivory_google_map.marker_cluster`` service is. The configuration
describes below is this default configuration.

```yaml
# app/config/config.yml

ivory_google_map:
    marker_cluster:
        # Your own marker cluster class
        class: "My\Fucking\MarkerCluster"

        # Your own marker cluster helper class
        helper_class: "My\Fucking\MarkerClusterHelper"

        # Prefix used for the generation of the marker cluster javascript variable
        prefix_javascript_variable: "marker_cluster_"

        # Marker cluster type
        type: "default"

        # Custom marker cluster options
        # By default there is no marker cluster options
        options:
            option: "value"
```

``` php
<?php

// Requests the ivory google map marker cluster service
$markerCluster = $this->get('ivory_google_map.marker_cluster');
```

If you want to learn more, you can read
[this documentation](https://github.com/egeloen/ivory-google-map/blob/master/doc/usage/overlays/marker_cluster.md).


text:
package io.github.avatarhurden.tribalwarsengine.managers;

import io.github.avatarhurden.tribalwarsengine.components.ProgressStatus;
import io.github.avatarhurden.tribalwarsengine.enums.Server;
import io.github.avatarhurden.tribalwarsengine.main.Configuration;
import io.github.avatarhurden.tribalwarsengine.objects.World;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

public class WorldManager {

	private static WorldManager instance;
	private ServerFileManager downloader;

	private List<World> worlds;
	private World selectedWorld;

	public static void initialize(ProgressStatus bar) {
		instance = new WorldManager();
		instance.loadConfigs(bar);
	}

	public static WorldManager get() {
		if (instance == null)
			instance = new WorldManager();
		return instance;
	}

	private WorldManager() {
		downloader = new ServerFileManager();
	}

	private void loadConfigs(ProgressStatus bar) {
		Server server = Server.getServer(Configuration.get().getConfig("server", "br"));
		Configuration.get().setConfig("server", server.getName());

		bar.setMessage("Baixando lista de Mundos");
		bar.setProgress(20);

		JSONArray worldList;
		try {
			worldList = downloader.getServerConfigOnline(server);
		} catch (Exception e) {
			worldList = downloader.tryGetServerConfigLocal(server);
		}

		worlds = new ArrayList<World>();
		for (int i = 0; i < worldList.length(); i++) {
			bar.listIncrement(i, worldList.length(), 100);
			bar.setMessage("Carregando " + worldList.getJSONObject(i).getString("name"));
			worlds.add(new World(worldList.getJSONObject(i)));
		}

		bar.endSubProgress();
	}

	public World getDefaultWorld() {
		String def = Configuration.get().getConfig("default_world_" +
				Configuration.get().getConfig("server", "br"), "");
			if (def.equals(""))
				return worlds.get(0);
	        return getWorldByName(def);
	}

	public void setDefaultWorld(World world) {
		Configuration.get().setConfig("default_world_" +
				Configuration.get().getConfig("server", "br"), world.getName());
	}

    public World getWorldByName(String name) {
        for (World server : worlds) {
            if (server.getName().equals(name)) {
                return server;
            }
        }
        return null;
    }

    public void setSelectedWorld(World world) {
    	selectedWorld = world;
    }

    public void setSelectedWorld(String world) {
    	setSelectedWorld(getWorldByName(world));
    }

    public static World getSelectedWorld() {
    	if (get().selectedWorld == null)
    		get().selectedWorld = get().getDefaultWorld();
    	return get().selectedWorld;
    }

    public List<World> getList() {
    	return worlds;
    }
}


text:
<!DOCTYPE html>
<!--
Copyright (c) 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/extras/cc/display_item_list.html">
<link rel="import" href="/extras/cc/display_item_debugger.html">

<script>
'use strict';

tv.b.unittest.testSuite(function() {
  test('instantiate', function() {
    var displayItemList = new tv.e.cc.DisplayItemListSnapshot(
      {id: '31415'},
      10,
      {
        'params': {
          'layer_rect': [-15, -15, 46, 833],
          'items': [
            'BeginClipDisplayItem',
            'EndClipDisplayItem'
          ]
        },
        'skp64': '[another skia picture in base64]'});
    displayItemList.preInitialize();
    displayItemList.initialize();

    var dbg = new tv.e.cc.DisplayItemDebugger();
    this.addHTMLOutput(dbg);
    assert.isUndefined(dbg.displayItemList_);
    assert.isUndefined(dbg.picture_);
    dbg.displayItemList = displayItemList;
    assert.isDefined(dbg.displayItemList_);
    assert.isDefined(dbg.picture_);
    assert.equal(dbg.displayItemList_.items.length, 2);
    dbg.style.border = '1px solid black';
  });

  test('selections', function() {
    var displayItemList = new tv.e.cc.DisplayItemListSnapshot(
      {id: '31415'},
      10,
      {
        'params': {
          'layer_rect': [-15, -15, 46, 833],
          'items': [
            'BeginClipDisplayItem',
            'TransformDisplayItem',
            {'name': 'DrawingDisplayItem', 'skp64': '[skia picture in base64]'},
            'EndTransformDisplayItem',
            'EndClipDisplayItem'
          ]
        },
        'skp64': '[another skia picture in base64]'});
    displayItemList.preInitialize();
    displayItemList.initialize();

    var dbg = new tv.e.cc.DisplayItemDebugger();
    this.addHTMLOutput(dbg);
    dbg.displayItemList = displayItemList;
    assert.isDefined(dbg.displayItemList_);
    assert.isDefined(dbg.picture_);
    assert.equal(dbg.displayItemList_.items.length, 5);

    var initialPicture = dbg.picture_;
    assert.isAbove(initialPicture.guid, 0);

    // Select the drawing display item and make sure the picture updates.
    var listView = dbg.displayItemListView_;
    listView.selectedElement = listView.getElementByIndex(3);
    var updatedPicture = dbg.picture_;
    assert.isAbove(updatedPicture.guid, 0);
    assert.notEqual(initialPicture.guid, updatedPicture.guid);

    // Select the TransformDisplayItem and make sure the picture is blank.
    listView.selectedElement = listView.getElementByIndex(2);
    assert.isUndefined(dbg.picture_);

    // Deselect a list item and make sure the picture is reset to the original.
    listView.selectedElement = undefined;
    updatedPicture = dbg.picture_;
    assert.isAbove(updatedPicture.guid, 0);
    assert.equal(initialPicture.guid, updatedPicture.guid);

    dbg.style.border = '1px solid black';
  });
});
</script>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Contr. Univ. Mich. Herb. 14: 79 (1980)

#### Original name
Phlebogaster Fogel

### Remarks
null


text:
Criar uma conta

    <form class="form-signin" role="form" ng-submit="Register($event)">
      <input type="teste" class="form-control" ng-model="user.name" placeholder="Nome" required="" autofocus="">

      <input type="email" class="form-control" ng-model="user.email" placeholder="Email" required="" autofocus="">

      <input type="password" class="form-control" ng-model="user.password" placeholder="Senha" required="">

{{errors}}

      <button class="btn btn-lg btn-primary btn-block" type="submit">Registrar</button>
    </form>


text:
class A {
  public String toString() {
    return super.toString();
  }
}

interface II {}


text:
package ma.glasnost.orika.test.community;

import java.util.ArrayList;
import java.util.List;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import org.junit.Test;

/**
 * @author
 *
 */
public class Issue71TestCase {

        @Test
        public void testEnumListMap() {
            final MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
            final MapperFacade mapper = mapperFactory.getMapperFacade();

            final A a = new A();
            final List<MyEnum> myEnumList = new ArrayList<MyEnum>();
            myEnumList.add(MyEnum.foo);
            a.setMyEnum(myEnumList);
            mapper.map(a, A2.class);

        }

        public static enum MyEnum {
            foo, bar
        }

        public static class A {
            private List<MyEnum>    myEnum;

            public List<MyEnum> getMyEnum() {
                return myEnum;
            }

            public void setMyEnum(final List<MyEnum> myEnum) {
                this.myEnum = myEnum;
            }
        }

        public static enum MyEnum2 {
            foo, bar
        }

        public static class A2 {
            private List<MyEnum2>   myEnum;

            public List<MyEnum2> getMyEnum() {
                return myEnum;
            }

            public void setMyEnum(final List<MyEnum2> myEnum) {
                this.myEnum = myEnum;
            }
        }
    }


text:
r"""Library for reconstructing wikipedia talk pages.

Copyright 2017 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License.

You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0

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

-------------------------------------------------------------------------------
"""
import copy
import json
import logging
import os
import resource

import apache_beam as beam
from wikiconv.conversation_reconstruction.construct_utils import conversation_constructor
import six

from google.cloud import storage

class ReconstructConversation(beam.DoFn):
  """Wikipedia talk page reconstruction."""

  def __init__(self, storage_client=None):
    self._storage_client = storage_client

  def start_bundle(self):
    if not self._storage_client:
      self._storage_client = storage.Client()

  def merge(self, ps1, ps2):
    # Merge two page states, ps1 is the later one
    deleted_ids_ps2 = {d[1]: d for d in ps2['deleted_comments']}
    deleted_ids_ps1 = {d[1]: d for d in ps1['deleted_comments']}
    deleted_ids_ps2.update(deleted_ids_ps1)
    extra_ids = [
        key for key in deleted_ids_ps2.keys() if key not in deleted_ids_ps1
    ]
    ret_p = copy.deepcopy(ps1)
    ret_p['deleted_comments'] = list(deleted_ids_ps2.values())
    conv_ids = ps2['conversation_id']
    auth = ps2['authors']
    ret_p['conversation_id'] = ret_p['conversation_id']
    ret_p['authors'] = ret_p['authors']
    for i in extra_ids:
      ret_p['conversation_id'][i] = conv_ids[i]
      ret_p['authors'][i] = auth[i]
    ret_p['conversation_id'] = ret_p['conversation_id']
    ret_p['authors'] = ret_p['authors']
    return ret_p

  def process(self, info, tmp_input):
    """Main reconstruction processing routine.

    Args:
      info: the beam DoFn input, a tuple of the page_id and data.
      tmp_input: a path to copy JSON revision files from. This allows data to be
        copied to this local machine's disk for external sorting (when there are
        more revisions than can fit in memory).

    Yields:
      tagged output.

    """
    log_interval = 100
    # The max memory used in of this process KB, before warning are logged.
    memory_threshold = 1000000

    (page_id, data) = info
    if not page_id:
      return
    logging.info('USERLOG: Reconstruction work start on page: %s', page_id)
    # Load input from cloud
    last_revision = data['last_revision']
    page_state = data['page_state']
    error_log = data['error_log']
    # Clean type formatting
    if last_revision:
      assert len(last_revision) == 1
      last_revision = last_revision[0]
    else:
      last_revision = None
    if page_state:
      assert len(page_state) == 1
      page_state = page_state[0]
      page_state['page_state']['actions'] = {
          int(pos): tuple(val)
          for pos, val in six.iteritems(page_state['page_state']['actions'])
      }
      page_state['authors'] = {}
      for action_id, authors in six.iteritems(page_state['authors']):
        page_state['authors'][action_id] = [tuple(author) for author in authors]
    else:
      page_state = None
    if error_log:
      assert len(error_log) == 1
      error_log = error_log[0]
    else:
      error_log = None
    rev_ids = []
    rev_ids = data['to_be_processed']
    # Return when the page doesn't have updates to be processed
    if not rev_ids or (
        error_log and error_log['rev_id'] <= min(r['rev_id'] for r in rev_ids)):
      assert ((last_revision and page_state) or ((last_revision is None) and
                                                 (page_state is None)))
      if last_revision:
        yield beam.pvalue.TaggedOutput('last_revision',
                                       json.dumps(last_revision))
        yield beam.pvalue.TaggedOutput('page_states', json.dumps(page_state))
      if error_log:
        yield beam.pvalue.TaggedOutput('error_log', json.dumps(error_log))
      logging.info('Page %s has no sufficient input in this time period.',
                   (page_id))
      return

    processor = conversation_constructor.ConversationConstructor()
    if page_state:
      logging.info('Page %s existed: loading page state.', (page_id))
      # Load previous page state.
      processor.load(page_state['deleted_comments'])
      latest_content = last_revision['text']
    else:
      latest_content = ''

    # Initialize
    last_revision_id = 'None'
    page_state_bak = None
    cnt = 0
    # Sort revisions by temporal order in memory.
    revision_lst = sorted(rev_ids, key=lambda x: (x['timestamp'], x['rev_id']))
    last_loading = 0
    logging.info('Reconstruction on page %s started.', (page_id))
    for key in revision_lst:
      rev_id_str = str(key['rev_id'])
      if 'text' not in key:
        if tmp_input.startswith('gs://'):
          # Read from cloud storage
          bucket_name_end = tmp_input.find('/', 5)
          bucket = self._storage_client.get_bucket(tmp_input[5:bucket_name_end])
          revision = json.loads(
              bucket.get_blob(
                  os.path.join(tmp_input[bucket_name_end + 1:], page_id,
                               rev_id_str)).download_as_string())
        else:
          # Read directly.
          with open(os.path.join(tmp_input, page_id, rev_id_str), 'r') as f:
            revision = json.load(f)
      else:
        revision = key
      revision['rev_id'] = int(revision['rev_id'])
      # Process revision by revision.
      if 'rev_id' not in revision:
        continue
      cnt += 1
      last_revision_id = revision['rev_id']
      if not revision['text']:
        revision['text'] = ''
      logging.debug('REVISION CONTENT: %s', revision['text'])
      try:
        page_state, actions, latest_content = processor.process(
            page_state, latest_content, revision)
      except AssertionError:
        yield beam.pvalue.TaggedOutput(
            'error_log',
            json.dumps({
                'page_id': page_id,
                'rev_id': last_revision_id
            }))
        break

      for action in actions:
        yield json.dumps(action)
      memory_used = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
      if memory_used >= memory_threshold:
        logging.warn(
            'MEMORY USED MORE THAN THERESHOLD in PAGE %s REVISION %d : %d KB',
            revision['page_id'], revision['rev_id'], memory_used)
      if (cnt % log_interval == 0 and cnt) and page_state:
        # Reload after every LOG_INTERVAL revisions to keep the low memory
        # usage.
        processor = conversation_constructor.ConversationConstructor()
        page_state_bak = copy.deepcopy(page_state)
        last_loading = cnt
        processor.load(page_state['deleted_comments'])
        page_state['deleted_comments'] = []
      revision = None
    if page_state_bak and cnt != last_loading:
      # Merge the last two page states if a reload happens while processing,
      # otherwise in a situation where a week's data contains LOG_INTERVAL + 1
      # revisions, the page state may only contain data from one revision.
      page_state = self.merge(page_state, page_state_bak)
    if error_log:
      yield beam.pvalue.TaggedOutput('error_log', json.dumps(error_log))
    yield beam.pvalue.TaggedOutput('page_states', json.dumps(page_state))
    yield beam.pvalue.TaggedOutput(
        'last_revision', json.dumps({
            'page_id': page_id,
            'text': latest_content
        }))
    logging.info(
        'USERLOG: Reconstruction on page %s complete! last revision: %s',
        page_id, last_revision_id)


text:
//
// Copyright © 2012 - 2013 Nauck IT KG     http://www.nauck-it.de
//
// Author:
//  Daniel Nauck        <d.nauck(at)nauck-it.de>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System.Linq;
using System.Net;
using License.Manager.Core.Model;
using License.Manager.Core.Persistence;
using License.Manager.Core.ServiceModel;
using Raven.Client;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.ServiceInterface;

namespace License.Manager.Core.ServiceInterface
{
    [Authenticate]
    public class CustomerService : Service
    {
        private readonly IDocumentSession documentSession;

        public CustomerService(IDocumentSession documentSession)
        {
            this.documentSession = documentSession;
        }

        public object Post(CreateCustomer request)
        {
            var customer = new Customer().PopulateWith(request);

            documentSession.Store(customer);
            documentSession.SaveChanges();

            return
                new HttpResult(customer)
                    {
                        StatusCode = HttpStatusCode.Created,
                        Headers =
                            {
                                {HttpHeaders.Location, Request.AbsoluteUri.CombineWith(customer.Id)}
                            }
                    };
        }

        public object Put(UpdateCustomer request)
        {
            var customer = documentSession.Load<Customer>(request.Id);
            if (customer == null)
                HttpError.NotFound("Customer not found!");

            customer.PopulateWith(request);

            documentSession.Store(customer);
            documentSession.SaveChanges();

            return customer;
        }

        public object Delete(UpdateCustomer request)
        {
            var customer = documentSession.Load<Customer>(request.Id);
            if (customer == null)
                HttpError.NotFound("Customer not found!");

            documentSession.Delete(customer);
            documentSession.SaveChanges();

            return
                new HttpResult
                    {
                        StatusCode = HttpStatusCode.NoContent,
                    };
        }

        public object Get(GetCustomer request)
        {
            var customer = documentSession.Load<Customer>(request.Id);
            if (customer == null)
                HttpError.NotFound("Customer not found!");

            return customer;
        }

        public object Get(FindCustomers request)
        {
            var query = documentSession.Query<CustomerAllPropertiesIndex.Result, CustomerAllPropertiesIndex>();

            if (!string.IsNullOrWhiteSpace(request.Name))
                query = query.Search(c => c.Query, request.Name);

            if (!string.IsNullOrWhiteSpace(request.Company))
                query = query.Search(c => c.Query, request.Company);

            if (!string.IsNullOrWhiteSpace(request.Email))
                query = query.Search(c => c.Query, request.Email);

            return query
                .OfType<Customer>()
                .ToList();
        }
    }
}


text:
from . import Service

class Keys(Service):
    """ Consume `Keys API <http://developer.github.com/v3/users/keys/>`_

    .. warning::
        You must be authenticated for all requests
    """

    def list(self):
        """ Get public keys

        :returns: A :doc:`result`
        """
        request = self.make_request('users.keys.list')
        return self._get_result(request)

    def get(self, key_id):
        """ Get a public key

        :param int key_id: Key id
        """
        request = self.make_request('users.keys.get',
            key_id=key_id)
        return self._get(request)

    def add(self, data):
        """ Add a public key

        :param dict data: Key (title and key attributes required)

        ::

            key_service.add(dict(title='host', key='ssh-rsa AAA...'))
        """
        request = self.make_request('users.keys.add',
            body=data)
        return self._post(request)

    def update(self, key_id, data):
        """ Update a public key

        :param int key_id: Key id
        :param dict data: Key (title and key attributes required)

        ::

            key_service.update(42, dict(title='host', key='ssh-rsa AAA...'))
        """
        request = self.make_request('users.keys.update',
            key_id=key_id, body=data)
        return self._patch(request)

    def delete(self, key_id):
        """ Delete a public key

        :param int key_id: Key id
        """
        request = self.make_request('users.keys.delete',
            key_id=key_id)
        self._delete(request)


text:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { select } from 'react-select-event';

import { GraphPeriod, Props } from './GraphPeriod';

const props: Props = {
  onChange: jest.fn(),
  refId: 'A',
  variableOptionGroup: { options: [] },
};

describe('Graph Period', () => {
  it('should enable graph_period by default', () => {
    render(<GraphPeriod {...props} />);
    expect(screen.getByLabelText('Graph period')).not.toBeDisabled();
  });

  it('should disable graph_period when toggled', async () => {
    const onChange = jest.fn();
    render(<GraphPeriod {...props} onChange={onChange} />);
    const s = screen.getByTestId('A-switch-graph-period');
    await userEvent.click(s);
    expect(onChange).toHaveBeenCalledWith('disabled');
  });

  it('should set a different value when selected', async () => {
    const onChange = jest.fn();
    render(<GraphPeriod {...props} onChange={onChange} />);
    const selectEl = screen.getByLabelText('Graph period');
    expect(selectEl).toBeInTheDocument();

    await select(selectEl, '1m', {
      container: document.body,
    });
    expect(onChange).toHaveBeenCalledWith('1m');
  });
});


text:
pyowm.uvindexapi30 package
==========================

Subpackages
-----------

.. toctree::

Submodules
----------

pyowm.uvindexapi30.uvindex module
---------------------------------

.. automodule:: pyowm.uvindexapi30.uvindex
    :members:
    :undoc-members:
    :show-inheritance:

pyowm.uvindexapi30.uvindex_manager module
-----------------------------------------

.. automodule:: pyowm.uvindexapi30.uvindex_manager
    :members:
    :undoc-members:
    :show-inheritance:

pyowm.uvindexapi30.uv_client module
-----------------------------------

.. automodule:: pyowm.uvindexapi30.uv_client
    :members:
    :undoc-members:
    :show-inheritance:

pyowm.uvindexapi30.uris module
------------------------------

.. automodule:: pyowm.uvindexapi30.uris
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: pyowm.uvindexapi30
    :members:
    :undoc-members:
    :show-inheritance:


text:
**i. Integrate disparate water management data for the Bear River Basin, Utah to search and discover data universally**
This use case is demonstrated by searching data across the sources from questions 1 to 10. These questions are organized from generic in asking about water system components, their connectivity, metadata, and specific asking about attribute data values. This use case demonstrates how the users can use WaM-DaM to generate a synthetic view of the data available within a watershed, organize various different data types (e.g., time series, parameters) with appropriate metadata, identify discrepancies among data sources and consider them in preparing a model input data, track data provenance (e.g., sources, methods), relate synonymous data by overcoming sematic heterogeneity, identify relationship between nodes and links, organize models structures of object and their attributes

1.What are the available water management components in the Lower Bear River Watershed, Utah?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q1.png)

2.What is the attribute's "surface area" value(s) of Hyrum Reservoir in the Lower Bear River Watershed, Utah?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q2.png)

3.What other attribute data are available for Hyrum Reservoir?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q3.png)

4.What are the Elevation-Storage-Area data for Hyrum Reservoir?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q4.png)

5.What are the sources, methods, organizations, and contact people for data about Hyrum Reservoir?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q5.png)

6.What is the start and end nodes for the "Blacksmith Fork…" and "From Boxelder…" link instances?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q6.png)

7.What are the links that end at a node instance (e.g., links that supply water to a demand site)?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q7.png)

8.What are the links that start at a node instance (e.g., links that discharge water from a demand site)?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q8.png)

9.What are the objects of WEAP and how are they organized in WaM-DaM? search an object(s) by their category (s)
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q9.png)

10.How are the attributes of WEAP and how are they organized in WaM-DaM? Search an attribute(s) by their category(s).
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q10.png)

11.What are the available networks and scenarios in the Lower Bear River, and what are their spatial reference and vertical datum?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q11.png)

**ii. Compare differences in topology, metadata, and data values between two scenarios in the Lower Bear River watershed, Utah**
12.How do two scenarios differ in topology in a master network?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/q12.png)

13.How do two scenarios differ in metadata in a master network?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/q13.png)

14.How do two scenarios differ in data values in a master network?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/q14.png)

**iii. Identify available and missing data to expand the Lower Bear River Model to the Bear River Watershed**

15.What are the available instances and their data of Object Types used in WEAP in the upper Bear River Watershed?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/Q16.png)

16.What are the missing instances to expand the WEAP Lower Bear River model to the entire watershed?
![](https://github.com/amabdallah/WaM-DaM1.0/blob/master/Files/q17.png)


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Redirecting…</title>
  <link rel="canonical" href="/v0.5/docs/reference/config/istio.routing.v1alpha1.html">
  <meta http-equiv="refresh" content="0; url=/v0.5/docs/reference/config/istio.routing.v1alpha1.html">

Redirecting…

  Click here if you are not redirected.


text:
published: true
title: Good Java practices for clarity
---
# Enums instead of booleans

Using enums instead of booleans where appropriate can bring a lot of clarity to your code.

For example, say you had an access control implemented as follows:

{% highlight java %}
public class AccessControl {
	private boolean isPrivate;

	public boolean isPrivate(){
    	return isPrivate;
    }

	public boolean isPublic(){
    	return !isPrivate;
    }
}
{% endhighlight %}

Sure, you can call methods to determine if the access is public or private. But, for one thing, it's not very extensible. If you wanted to add another access level, such as "private to group", the code becomes much more complex.

In any case, though, the code can be made clearer by using an enum:

{% highlight java %}
public static class AccessControl {

   public enum Level {
       PUBLIC, PRIVATE
   };

   private Level access;

   public Level getAccessLevel(){
       return access;
   }
}
{% endhighlight %}

Now, you can use conditional logic like:

{% highlight java %}
AccessControl accessControl = new AccessControl();
AccessControl.Level level = accessControl.getAccessLevel();
if(level.equals(AccessControl.Level.PRIVATE)){
	// do something
}
{% endhighlight %}

It's very clear which access level your logic is working with, and it's easy to extend to more enums if necessary.

# Specify your units!

When working with variables that reference quantities, it's extremely important to specify your units. Otherwise someone maintaining your code later (probably you!) won't be able to distinguish if you were referring to grams, dollars, feet, miles, milliseconds, seconds, or farthings. This can lead to very real problems; In 1999, NASA lost a [$125 million Mars probe](http://articles.latimes.com/1999/oct/01/news/mn-17288) because the programmers didn't take into account unit conversions.

So, if you're working with time, for example, instead of using
{% highlight java %}
int TIME_ELAPSED = 10;
{% endhighlight %}

specify the units, such as
{% highlight java %}
int TIME_ELAPSED_MILLIS = 10;
{% endhighlight %}

# Never rely on enum ordinal values

When working with enums, be very explicit about their values. Never rely on their order to derive meaning.

For example, instead of using
{% highlight java %}
public enum CompassPoint {
    North,
    East,
    South,
    West;
}
{% endhighlight %}

and relying on the order of those enums to derive their values, be explicit about their values, like this
{% highlight java %}
public enum CompassDirection {
    NORTH(0),
    EAST(90),
    SOUTH(180),
    WEST(270);
}
{% endhighlight %}

This reduces brittleness. Code that relies on the order of the enums won't break if they are reordered. Additionally, more enums can be added with out worrying about their order.

For more, see this discussion on StackOverflow: [Is enum order sensitivity an antipattern?](https://softwareengineering.stackexchange.com/questions/290842/is-enum-order-sensitivity-an-antipattern).


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Threading.Tasks

Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
    Public Class ModuleNameSimplifierTest
        Inherits AbstractSimplificationTests

        <WorkItem(624131)>
        <WpfFact(), Trait(Traits.Feature, Traits.Features.Simplification)>
        Public Async Function TestSimplifyModuleNameInNewStatement() As Task
            Dim input =
        <Workspace>
            <Project Language="Visual Basic" CommonReferences="true">
                <Document>
Imports System
Namespace N
    Module M
        Class D
        End Class
    End Module
End Namespace
Module Program
    Sub Main(args As String())
        Dim d = New N.{|SimplifyParent:M.D|}()
    End Sub
End Module
                </Document>
            </Project>
        </Workspace>

            Dim expected =
              <text>
Imports System
Namespace N
    Module M
        Class D
        End Class
    End Module
End Namespace
Module Program
    Sub Main(args As String())
        Dim d = New N.D()
    End Sub
End Module
            </text>

            Await TestAsync(input, expected)
        End Function

        <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)>
        Public Async Function TestSimplifyModuleNameInNestedNamespaces() As Task
            Dim input =
        <Workspace>
            <Project Language="Visual Basic" CommonReferences="true">
                <Document>
Namespace N
    Namespace M
        Module K
            Class C
                Shared Sub Foo()
                End Sub
            End Class
        End Module
        Namespace L
            Module K
                Class C
                    Shared Sub Foo()

                    End Sub
                End Class
            End Module
            Class C
                Shared Sub Foo()
                    {|SimplifyExtension:N.M.K.C.Foo|}()
                End Sub
            End Class
        End Namespace
    End Namespace
End Namespace
                </Document>
            </Project>
        </Workspace>

            Dim expected =
              <text>
Namespace N
    Namespace M
        Module K
            Class C
                Shared Sub Foo()
                End Sub
            End Class
        End Module
        Namespace L
            Module K
                Class C
                    Shared Sub Foo()

                    End Sub
                End Class
            End Module
            Class C
                Shared Sub Foo()
                    M.C.Foo()
                End Sub
            End Class
        End Namespace
    End Namespace
End Namespace
            </text>

            Await TestAsync(input, expected)
        End Function

        <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)>
        Public Async Function TestSimplifyModuleNameInDelegateConstruct() As Task
            Dim input =
        <Workspace>
            <Project Language="Visual Basic" CommonReferences="true">
                <Document>
Imports System
Namespace N
    Module M
        Class C
            Shared Sub Foo()

            End Function
        End Class
    End Module
End Namespace
Module Program
    Delegate Sub myDel()
    Sub Main(args As String())
        Dim m As myDel = AddressOf {|SimplifyExtension:N.M.C.Foo|}
    End Sub
End Module
                </Document>
            </Project>
        </Workspace>

            Dim expected =
              <text>
Imports System
Namespace N
    Module M
        Class C
            Shared Sub Foo()

            End Function
        End Class
    End Module
End Namespace
Module Program
    Delegate Sub myDel()
    Sub Main(args As String())
        Dim m As myDel = AddressOf N.C.Foo
    End Sub
End Module
            </text>

            Await TestAsync(input, expected)
        End Function

        <WorkItem(608198)>
        <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)>
        Public Async Function TestDontSimplifyModuleNameInFieldInitializerAndConflictOfModuleNameAndField() As Task
            Dim input =
        <Workspace>
            <Project Language="Visual Basic" CommonReferences="true">
                <Document>
Module X
    Dim x As Action = Sub() Console.WriteLine(Global.X.{|SimplifyParent:x|})
End Module
                </Document>
            </Project>
        </Workspace>

            Dim expected =
              <text>
Module X
    Dim x As Action = Sub() Console.WriteLine(x)
End Module
            </text>

            Await TestAsync(input, expected)
        End Function

        <WorkItem(608198)>
        <WpfFact, Trait(Traits.Feature, Traits.Features.Simplification)>
        Public Async Function TestDontSimplifyModuleNameInFieldInitializerAndConflictOfModuleNameAndField_2() As Task
            Dim input =
        <Workspace>
            <Project Language="Visual Basic" CommonReferences="true">
                <Document>
Module X
    Dim x As Action = Sub() Console.WriteLine(Global.{|SimplifyParent:X|}.x)
End Module
                </Document>
            </Project>
        </Workspace>

            Dim expected =
              <text>
Module X
    Dim x As Action = Sub() Console.WriteLine(Global.X.x)
End Module
            </text>

            Await TestAsync(input, expected)
        End Function

    End Class
End Namespace


text:
struct KeyOriginInfo
{
    unsigned char fingerprint[4]; //!< First 32 bits of the Hash160 of the public key at the root of the path
    std::vector<uint32_t> path;

    friend bool operator==(const KeyOriginInfo& a, const KeyOriginInfo& b)
    {
        return std::equal(std::begin(a.fingerprint), std::end(a.fingerprint), std::begin(b.fingerprint)) && a.path == b.path;
    }

    SERIALIZE_METHODS(KeyOriginInfo, obj) { READWRITE(obj.fingerprint, obj.path); }

    void clear()
    {
        memset(fingerprint, 0, 4);
        path.clear();
    }
};

#endif // BITSEND_SCRIPT_KEYORIGIN_H


text:
Creates a binary image from a gray image based on the threshold values.

**plantcv.threshold.otsu**(*gray_img, max_value, object_type="light"*)

**returns** thresholded/binary image

- **Parameters:**
    - gray_img - Grayscale image data
    - max_value - Value to apply above threshold (255 = white)
    - object_type - "light" or "dark" (default: "light"). If object is lighter than the background then standard
    thresholding is done. If object is darker than the background then inverse thresholding is done.

- **Context:**
    - Used to help differentiate plant and background

**Grayscale image (green-magenta channel)**

![Screenshot](img/documentation_images/otsu_threshold/original_image1.jpg)

```python
from plantcv import plantcv as pcv

# Set global debug behavior to None (default), "print" (to file),
# or "plot" (Jupyter Notebooks or X11)
pcv.params.debug = "print"

# Create binary image from a gray image based on threshold values.
# Targeting dark objects in the image.
threshold_dark = pcv.threshold.otsu(gray_img=gray_img, max_value=255, object_type='dark')

```

**Thresholded image**

![Screenshot](img/documentation_images/otsu_threshold/thresholded_dark.jpg)

**Grayscale image (blue-yellow channel)**

![Screenshot](img/documentation_images/otsu_threshold/original_image.jpg)

```python

# Create binary image from a gray image based on threshold values.
# Targeting light objects in the image.
threshold_light = pcv.threshold.otsu(gray_img=gray_img, max_value=255, object_type='light')

```

**Thresholded image (inverse)**

![Screenshot](img/documentation_images/otsu_threshold/thresholded_light.jpg)

**Source Code:** [Here](https://github.com/danforthcenter/plantcv/blob/main/plantcv/plantcv/threshold/threshold_methods.py)


text:
package com.bbd.dafei.web.controller;

import com.bbd.dafei.biz.shared.CommonService;
import com.bbd.dafei.biz.shared.RaBlackListService;
import com.bbd.dafei.biz.shared.RaCompanyService;
import com.bbd.dafei.common.modal.commonenum.BlackReasonTypeEnum;
import com.bbd.dafei.common.modal.dto.KeyValDTO;
import com.bbd.dafei.common.modal.vo.BlacklistVO;
import com.bbd.dafei.common.modal.vo.BlacklistVerifyVO;
import com.bbd.dafei.common.modal.vo.RaCompanyVO;
import com.bbd.dafei.common.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Ian.Su
 * @version $Id: BlacklistController.java, v 0.1 2017/6/8 14:24 Ian.Su Exp $
 */

@RestController
@RequestMapping("/blacklist")
@Api(value = "/blacklist", tags = "黑名单管理")
public class BlacklistController extends BaseController {

    @Autowired
    private RaBlackListService blackListService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private RaCompanyService companyService;

    @ApiOperation(value = "根据名称搜索企业", notes = "根据名称搜索企业")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "company", value = "企业名称关键字", paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/search.do", method = RequestMethod.GET)
    public ResponseBean<PageInfo<RaCompanyVO>> query(String company) {

        return ResponseBean.successResponse(companyService.search(company));

    }

    //黑名单导出EXCEL表头
    private static final String blacklistExport = "[" +
            "{\"key\":\"companyId\",\"value\":\"企业id\"}" +
            "{\"key\":\"company\",\"value\":\"企业名\"}" +
            "{\"key\":\"industry\",\"value\":\"所属行业\"}" +
            "{\"key\":\"province\",\"value\":\"省份\"}" +
            "{\"key\":\"gmtCreate\",\"value\":\"入库时间\"}" +
            "{\"key\":\"joinReason\",\"value\":\"加入原因\"}" +
            "{\"key\":\"joinSrouce\",\"value\":\"加入来源\"}" +
            "{\"key\":\"joinDate\",\"value\":\"加入时间\"}" +
            "{\"key\":\"cancelReason\",\"value\":\"移出原因\"}" +
            "{\"key\":\"cancelDate\",\"value\":\"移出时间\"}" +
            "]";

    //黑名单待核实导出EXCEL表头
    private static final String blacklistVerifyExport = "[" +
            "{\"key\":\"companyId\",\"value\":\"企业id\"}" +
            "{\"key\":\"companyName\",\"value\":\"企业名\"}" +
            "{\"key\":\"industry\",\"value\":\"行业\"}" +
            "{\"key\":\"province\",\"value\":\"省份\"}" +
            "{\"key\":\"dataVersion\",\"value\":\"计算版本\"}" +
            "{\"key\":\"typeName\",\"value\":\"类型\"}" +
            "{\"key\":\"blackCreateDate\",\"value\":\"入库时间\"}" +
            "{\"key\":\"joinReason\",\"value\":\"加入原因\"}" +
            "{\"key\":\"addSource\",\"value\":\"加入来源\"}" +
            "{\"key\":\"joinDate\",\"value\":\"加入时间\"}" +
            "{\"key\":\"cancelReason\",\"value\":\"移出原因\"}" +
            "{\"key\":\"cancelDate\",\"value\":\"移出时间\"}" +
            "]";

    @ApiOperation(value = "查询黑名单列表", notes = "分页查询黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "company", value = "企业名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", defaultValue = "10", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "order", value = "排序字段", defaultValue = "入库时间", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "ascDesc", value = "排序方式", defaultValue = "倒序", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "/query.do", method = RequestMethod.GET)
    public ResponseBean<PageInfo<BlacklistVO>> query(String company, PageInfoIgnore pageInfo,
                                                     @RequestParam(defaultValue = "入库时间") String order,
                                                     @RequestParam(defaultValue = "倒序") String ascDesc) {

        order = parseOrder(order);

        ascDesc = ("倒序".equals(ascDesc) ? "desc" : "asc");

        pageInfo = blackListService.queryAndReason(company, order, ascDesc, pageInfo);

        return ResponseBean.successResponse(pageInfo);

    }

    @ApiOperation(value = "导入黑名单", notes = "导入黑名单")
    @RequestMapping(value = "/import.do", method = RequestMethod.POST)
    public ResponseBean<String> importBlacklist(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        File excel = null;
        try {

            String filename = file.getOriginalFilename();
            filename = System.nanoTime() + filename.substring(filename.lastIndexOf("."));
            String path = commonService.getTempPath() + "/" + filename;
            excel = new File(path);
            file.transferTo(excel);
            ResponseBean<Workbook> rb = blackListService.importBlacklist(excel);
            Workbook wb = rb.getContent();
            //导入成功
            if (wb == null) {
                ResponseBean<String> responseBean = new ResponseBean<>();
                responseBean.setCode(rb.getCode());
                responseBean.setMsg(rb.getMsg());
                return ResponseBean.successResponse(null, "导入成功");
            } else {
                //导入的excel数据重复,将生成的workbook保存到文件,返回文件名到前端
                String errorFileName = System.nanoTime() + filename.substring(filename.lastIndexOf("."));
                FileOutputStream os = new FileOutputStream(commonService.getTempPath() + errorFileName);
                os.flush();
                //将Excel写出
                wb.write(os);
                //关闭流
                os.close();
                return ResponseBean.errorResponse(203, "excel数据有误", errorFileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导入黑名单失败", e);
            return ResponseBean.errorResponse("导入黑名单失败:" + e.getMessage());
        } finally {
            if (excel != null) {
                excel.delete();
            }
        }

    }

    @RequestMapping(value = "/addBlacklist.do", method = RequestMethod.GET)
    @ApiOperation(value = "添加到黑名单", notes = "后台添加黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司id", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "company", value = "公司名称)", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "addFrontUser", value = "加入来源)", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "joinDate", value = "加入时间(yyyy-MM-dd,yyyy-MM-dd HH:mm:ss)", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "addReason", value = "加入原因", paramType = "query", required = true, dataType = "String")
    })
    public ResponseBean addBlacklist(String companyId, String company, String addUser, String joinDate, String addReason) throws Exception {
        List<KeyValDTO<Integer, String>> addReasons = new ArrayList<>();
        KeyValDTO keyValDTO = new KeyValDTO();
        //添加黑名单原因:其他
        keyValDTO.setK(BlackReasonTypeEnum.ADD_REASON_OTHER.getCode());
        keyValDTO.setV(addReason);
        addReasons.add(keyValDTO);
        blackListService.addBlacklistManage(addUser, companyId, company,
                null, null, null, DateUtils.parseDate(joinDate, new String[]{"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"}), Constants.BLACKLIST_JOIN_TYPE_MANAGE, addReasons);
        return ResponseBean.successResponse(null, "添加成功");
    }

    @RequestMapping(value = "/deleteBlackListByIds.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "删除黑名单", notes = "删除黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "黑名单id", paramType = "query", required = true, dataType = "Integer")
    })
    public ResponseBean deleteBlackListByIds(@RequestParam("ids") List<Integer> ids) throws Exception {
        blackListService.deleteBlackListByIds(ids);
        return ResponseBean.successResponse(null, "删除成功");
    }

    @RequestMapping(value = "/updateBlacklist.do", method = RequestMethod.GET)
    @ApiOperation(value = "修改黑名单", notes = "后台修改黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "blackId", value = "黑名单id", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "addFrontUser", value = "加入来源)", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "joinDate", value = "加入时间(yyyy-MM-dd)", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "addReason", value = "加入原因", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cancelDate", value = "移出时间(yyyy-MM-dd)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "cancelReason", value = "移出原因", paramType = "query", dataType = "String")
    })
    public ResponseBean updateBlacklist(Integer blackId, String addUser, String joinDate, String addReason, String cancelDate, String cancelReason) throws Exception {
        Date cancel = null;
        if (StringUtils.isNotEmpty(cancelDate)) {
            cancel = DateUtils.parseDate(cancelDate, new String[]{"yyyy-MM-dd"});
        }
        blackListService.updateBlacklist(blackId, addUser,
                DateUtils.parseDate(joinDate, new String[]{"yyyy-MM-dd"}), addReason, cancel, cancelReason);
        return ResponseBean.successResponse(null, "修改成功");
    }

    @RequestMapping(value = "/exportBlacklist.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出黑名单", notes = "导出黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "blacklistIds", value = "黑名单id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "company", value = "企业名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "order", value = "排序字段", defaultValue = "入库时间", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "ascDesc", value = "排序方式", defaultValue = "倒序", paramType = "query", dataType = "String", required = true)
    })
    public Object exportBlacklist(@RequestParam(value = "blacklistIds", required = false) List<Integer> blacklistIds, String company,
                                  @RequestParam(defaultValue = "入库时间") String order,
                                  @RequestParam(defaultValue = "倒序") String ascDesc, HttpServletResponse response, HttpServletRequest req) throws Exception {

        ascDesc = ("倒序".equals(ascDesc) ? "desc" : "asc");
        order = parseOrder(order);
        PageInfoIgnore pageInfo = new PageInfoIgnore();
        //page = 0 查询全部
        pageInfo.setPage(0);
        pageInfo.setPageSize(0);
        List<BlacklistVO> blacklistVOList = null;
        //如果有黑名单id参数,则直接通过id查询,否则按其他条件查询
        if (CollectionUtils.isNotEmpty(blacklistIds)) {
            blacklistVOList = blackListService.queryAndReasonByIds(blacklistIds, order, ascDesc);
        } else {
            pageInfo = blackListService.queryAndReason(company, order, ascDesc, pageInfo);
            if (pageInfo != null) {
                blacklistVOList = pageInfo.getItems();
            }
        }

        HSSFWorkbook hssfWorkbook = ExportExcel.exportExcel("黑名单", blacklistExport, blacklistVOList, "yyyy-MM-dd");
        response.setCharacterEncoding("utf-8");
        // 清空response
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + CommonUtil.getFileName("黑名单.xls", req));
        response.setContentType("application/octet-stream");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        hssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();

        return ResponseBean.successResponse("");
    }

    @ApiOperation(value = "移除黑名单", notes = "个人中心-黑名单移除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", paramType = "query", value = "黑名单ID值", dataType = "Integer"),
            @ApiImplicitParam(name = "companyId", paramType = "query", value = "企业ID", dataType = "String"),
            @ApiImplicitParam(name = "cancelReason", paramType = "query", value = "移除原因", dataType = "String", required = true),
            @ApiImplicitParam(name = "cancelDate", paramType = "query", value = "移除时间(yyyy-MM-dd)", dataType = "String", required = true)
    })
    @RequestMapping(value = "/cancel.do", method = RequestMethod.GET)
    public ResponseBean<String> cancelBlacklist(@RequestParam Integer id,
                                                String companyId,
                                                @RequestParam String cancelReason,
                                                String cancelDate) throws Exception {

        if (id == null) {
            id = blackListService.findBlackListByCompanyId(companyId);
        }
        Date cancel = null;
        if (StringUtils.isNotEmpty(cancelDate)) {
            cancel = DateUtils.parseDate(cancelDate, new String[]{"yyyy-MM-dd"});
        }
        List<KeyValDTO<Integer, String>> reasons = new ArrayList<>();
        KeyValDTO<Integer, String> keyValDTO = new KeyValDTO();
        //移出黑名单原因:其他
        keyValDTO.setK(BlackReasonTypeEnum.CANCEL_REASON_OTHER.getCode());
        keyValDTO.setV(cancelReason);
        reasons.add(keyValDTO);
        blackListService.cancelBlack(id, companyId, reasons, getSessionUser().getUsername(), cancel, false);
        return ResponseBean.successResponse("已成功移除黑名单");
    }

    @ApiOperation(value = "删除所有黑名单", notes = "删除所有黑名单")
    @RequestMapping(value = "/deleteAllBlackList.do", method = RequestMethod.GET)
    public ResponseBean<Object> deleteAllBlackList() throws Exception {
        blackListService.deleteAllBlacklist();
        return ResponseBean.successResponse("成功删除所有黑名单");
    }

    @ApiOperation(value = "删除所有非用户添加的黑名单", notes = "删除所有非用户添加的黑名单")
    @RequestMapping(value = "/deleteAllManageBlackList.do", method = RequestMethod.GET)
    public ResponseBean<Object> deleteAllManageBlackList() throws Exception {
        blackListService.deleteAllManagedBlackList();
        return ResponseBean.successResponse("成功删除所有非用户添加的黑名单");
    }

    @ApiOperation(value = "查询黑名单核实列表", notes = "分页查询黑名单核实列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型:1新增黑名单,2已移除->本次为黑,3已加入->本次为灰", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", defaultValue = "10", paramType = "query", dataType = "Integer", required = true)
    })
    @RequestMapping(value = "/findBlackListVerifyPage.do", method = RequestMethod.GET)
    public ResponseBean<PageInfo<BlacklistVerifyVO>> findBlackListVerifyPage(String type, int page, int pageSize) {
        PageInfo<BlacklistVerifyVO> pageInfo = blackListService.findBlackListVerifyPage(page, pageSize, type);
        return ResponseBean.successResponse(pageInfo);
    }

    @RequestMapping(value = "/exportBlacklistVerify.do", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "导出待核实黑名单", notes = "导出待核实黑名单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型:1新增黑名单,2已移除->本次为黑,3已加入->本次为灰", paramType = "query", dataType = "String")
    })
    public Object exportBlacklistVerify(String type, HttpServletResponse response, HttpServletRequest req) throws Exception {

        PageInfo<BlacklistVerifyVO> pageInfo = blackListService.findBlackListVerifyPage(0, 0, type);
        List<BlacklistVerifyVO> blacklistVerifyVOList = pageInfo.getItems();

        HSSFWorkbook hssfWorkbook = ExportExcel.exportExcel("黑名单待核实", blacklistVerifyExport, blacklistVerifyVOList, "yyyy-MM-dd");
        response.setCharacterEncoding("utf-8");
        // 清空response
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + CommonUtil.getFileName("黑名单待核实.xls", req));
        response.setContentType("application/octet-stream");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        hssfWorkbook.write(outputStream);
        outputStream.flush();
        outputStream.close();

        return ResponseBean.successResponse("");
    }

    /**
     * 解析排序参数
     *
     * @param orderParam
     * @return
     */
    private String parseOrder(String orderParam) {
        if ("加入时间".equals(orderParam)) {
            return "join_date";
        }
        if ("移出时间".equals(orderParam)) {
            return "cancelDate";
        }
        return "gmt_create";

    }

}


text:
<?php

namespace Knp\Rad\ResourceResolver;

interface Parser
{
    /**
     * @return bool
     */
    public function supports($string);

    /**
     * @return array
     */
    public function parse($string);
}