text:
using testing::_;
using net::test::CryptoTestUtils;
using net::test::PacketSavingConnection;

namespace net {
namespace tools {
namespace test {
namespace {

const char kServerHostname[] = "www.example.com";

class ToolsQuicClientSessionTest : public ::testing::Test {
 protected:
  ToolsQuicClientSessionTest()
      : guid_(1),
        connection_(new PacketSavingConnection(guid_, IPEndPoint(), false)) {
    crypto_config_.SetDefaults();
    session_.reset(new QuicClientSession(kServerHostname, QuicConfig(),
                                         connection_, &crypto_config_));
    session_->config()->SetDefaults();
  }

  void CompleteCryptoHandshake() {
    ASSERT_TRUE(session_->CryptoConnect());
    CryptoTestUtils::HandshakeWithFakeServer(
        connection_, session_->GetCryptoStream());
  }

  QuicGuid guid_;
  PacketSavingConnection* connection_;
  scoped_ptr<QuicClientSession> session_;
  QuicCryptoClientConfig crypto_config_;
};

TEST_F(ToolsQuicClientSessionTest, CryptoConnect) {
  if (!Aes128Gcm12Encrypter::IsSupported()) {
    LOG(INFO) << "AES GCM not supported. Test skipped.";
    return;
  }
  CompleteCryptoHandshake();
}

TEST_F(ToolsQuicClientSessionTest, MaxNumStreams) {
  session_->config()->set_max_streams_per_connection(1, 1);
  if (!Aes128Gcm12Encrypter::IsSupported()) {
    LOG(INFO) << "AES GCM not supported. Test skipped.";
    return;
  }
  // FLAGS_max_streams_per_connection = 1;
  // Initialize crypto before the client session will create a stream.
  CompleteCryptoHandshake();

  QuicReliableClientStream* stream =
      session_->CreateOutgoingReliableStream();
  ASSERT_TRUE(stream);
  EXPECT_FALSE(session_->CreateOutgoingReliableStream());

  // Close a stream and ensure I can now open a new one.
  session_->CloseStream(stream->id());
  stream = session_->CreateOutgoingReliableStream();
  EXPECT_TRUE(stream);
}

TEST_F(ToolsQuicClientSessionTest, GoAwayReceived) {
  if (!Aes128Gcm12Encrypter::IsSupported()) {
    LOG(INFO) << "AES GCM not supported. Test skipped.";
    return;
  }

  CompleteCryptoHandshake();

  // After receiving a GoAway, I should no longer be able to create outgoing
  // streams.
  session_->OnGoAway(QuicGoAwayFrame(QUIC_PEER_GOING_AWAY, 1u, "Going away."));
  EXPECT_EQ(NULL, session_->CreateOutgoingReliableStream());
}

}  // namespace
}  // namespace test
}  // namespace tools
}  // namespace net


text:
<!DOCTYPE html>
<html ng-app="blocItOff">
<head lang="en">
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title>BlocItOff</title>
     <link rel="stylesheet" href="/styles/style.css">
     <link rel="stylesheet" type="text/css" href="/styles/home.css">
</head>
<body ng-controller="indexCtrl">
    <ui-view></ui-view>

    <script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "AIzaSyDrtBXV89h25xX_Pb_dKa_KySGhhwunmjE",
        authDomain: "blocitoff-e911e.firebaseapp.com",
        databaseURL: "https://blocitoff-e911e.firebaseio.com",
        projectId: "blocitoff-e911e",
        storageBucket: "blocitoff-e911e.appspot.com",
        messagingSenderId: "911371939280"
      };
      firebase.initializeApp(config);

    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/2.0.1/angularfire.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
    <script src="/scripts/app.js"></script>
    <script src="/scripts/controllers/homeCtrl.js"></script>
    <script src="/scripts/services/tasks.js"></script>
    <script src="/scripts/controllers/indexCtrl.js"></script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ambari.view.hive20.resources.settings;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import org.apache.ambari.view.ViewContext;
import org.apache.ambari.view.hive20.persistence.utils.ItemNotFound;
import org.apache.ambari.view.hive20.persistence.utils.OnlyOwnersFilteringStrategy;
import org.apache.ambari.view.hive20.persistence.utils.StorageFactory;
import org.apache.ambari.view.hive20.resources.PersonalCRUDResourceManager;
import org.apache.ambari.view.hive20.utils.UniqueConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.List;

/**
 *
 */
public class SettingsResourceManager extends PersonalCRUDResourceManager<Setting> {

  protected final Logger LOG = LoggerFactory.getLogger(getClass());

  private final ViewContext context;

  @Inject
  public SettingsResourceManager(ViewContext context) {
    super(Setting.class, new StorageFactory(context), context);
    this.context = context;
  }

  public List<Setting> getSettings() {
    String username = context.getUsername();
    return super.readAll(new OnlyOwnersFilteringStrategy(username));
  }

  public void removeSetting(String id) throws ItemNotFound {
    super.delete(id);
  }

  public Setting create(Setting setting) {
    List<Setting> settings = getSettings();
    if (checkUniqueViolation(settings, setting)) {
      LOG.error("Setting key: {} already exist for the user.", setting.getKey());
      throw new UniqueConstraintViolationException("Setting key: " + setting.getKey() + " already exists for the user");
    }
    return super.create(setting);
  }

  public Setting update(String id, Setting setting) throws ItemNotFound {
    Setting current = read(id);
    if(!current.getKey().equalsIgnoreCase(setting.getKey())) {
      // If the settings key has changed
      List<Setting> settings = getSettings();
      if (checkUniqueViolation(settings, setting)) {
        LOG.error("Setting key: {} already exist for the user.", setting.getKey());
        throw new UniqueConstraintViolationException("Setting key: " + setting.getKey() + " already exists for the user");
      }
    }
    return super.update(setting, id);
  }

  /**
   * @param settings List of all settings for the user
   * @param setting  new settings to be created
   * @return true if the settings key is not unique
   */
  private boolean checkUniqueViolation(List<Setting> settings, final Setting setting) {
    Optional<Setting> settingOptional = FluentIterable.from(settings).filter(new Predicate<Setting>() {
      @Override
      public boolean apply(@Nullable Setting input) {
        return input.getKey().equalsIgnoreCase(setting.getKey());
      }
    }).first();
    return settingOptional.isPresent();
  }
}


text:
@interface IGMultiDeferred ()
@property (nonatomic, assign, getter = isRunning) BOOL running;
@property (nonatomic, assign, getter = isResolved) BOOL resolved;
@property (nonatomic, assign, getter = isRejected) BOOL rejected;
@end

@implementation IGMultiDeferred

-(id) init {
    self = [super init];
    if (self) {
        self.running = NO;
    }
    return self;
}

-(void) addDeferred:(IGDeferred*)deferred
{

    [self.deferreds addObject:deferred];

    if ([deferred isRejected]) {
        self.reject([self rejectedValues]);
    }

    [deferred addObserver:self
               forKeyPath:@"running"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
}

-(IGMultiDeferred* (^)(IGDeferred*)) add
{
    return ^IGMultiDeferred* (IGDeferred* deferred) {
        [self addDeferred:deferred];
        return self;
    };
}

-(void) dealloc
{
    [self.deferreds enumerateObjectsUsingBlock:^(IGDeferred* defer, NSUInteger idx, BOOL *stop) {
        [defer removeObserver:self forKeyPath:@"running" context:nil];
    }];
}

-(BOOL) allResolved
{
    __block BOOL resolved = YES;
    [self.deferreds enumerateObjectsUsingBlock:^(IGDeferred* defer, NSUInteger idx, BOOL *stop) {
        if (!defer.resolved) {
            resolved = NO;
            *stop = YES;
        }
    }];
    return resolved;
}

-(BOOL) anyRejected
{
    __block BOOL rejected = NO;
    [self.deferreds enumerateObjectsUsingBlock:^(IGDeferred* defer, NSUInteger idx, BOOL *stop) {
        if (defer.reject) {
            rejected = YES;
            *stop = YES;
        }
    }];
    return rejected;
}

-(NSArray*) resovledValues
{
    NSMutableArray* resolvedValues = [NSMutableArray array];
    [self.deferreds enumerateObjectsUsingBlock:^(IGDeferred* defer, NSUInteger idx, BOOL *stop) {
        if (defer.resolved) {
            [resolvedValues addObject:defer.value];
        }
    }];
    return resolvedValues;
}

-(NSArray*) rejectedValues
{
    NSMutableArray* rejectedValues = [NSMutableArray array];
    [self.deferreds enumerateObjectsUsingBlock:^(IGDeferred* defer, NSUInteger idx, BOOL *stop) {
        if (defer.rejected) {
            [rejectedValues addObject:defer.value];
        }
    }];
    return rejectedValues;
}

#pragma makr - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)contex {
    if (!self.running) {
        return;
    }

    if ([self allResolved]) {
        self.running = NO;
        self.resolved = YES;
        self.resolve([self resovledValues]);
    } else if ([self anyRejected]) {
        self.running = NO;
        self.rejected = YES;
        self.reject([self rejectedValues]);
    }
}

@end


text:
require "rails_helper"

feature "order index page" do
  scenario "user views order attributes" do
    order = create(:order)

    visit admin_orders_path

    expect(page).to have_header("Orders")
    expect(page).to have_content(order.id)
  end

  scenario "user clicks through to customer show page" do
    order = create(:order)

    visit admin_orders_path
    click_on(displayed(order.customer))

    expect(page).to have_header(order.customer.name)
  end

  scenario "user clicks through to the order show page", :js do
    order = create(:order)

    visit admin_orders_path
    click_row_for(order)

    expect(page).to have_header(displayed(order))
    expect(page).to have_link(order.customer.name)
  end

  scenario "user clicks through to the edit page" do
    order = create(:order)

    visit admin_orders_path
    click_on "Edit"

    expect(current_path).to eq(edit_admin_order_path(order))
  end

  scenario "user clicks through to the new page" do
    visit admin_orders_path
    click_on("New order")

    expect(current_path).to eq(new_admin_order_path)
  end

  scenario "user deletes record" do
    create(:order)

    visit admin_orders_path
    click_on t("administrate.actions.destroy")

    expect(page).to have_flash(
      t("administrate.controller.destroy.success", resource: "Order")
    )
  end
end


text:
@implementation Note

@dynamic title;
@dynamic date;
@dynamic keywords;
@dynamic body;

@end


text:
( function( window, Backbone, $, _, Post_Customizer, undefined ) {

	"use strict";
	var document = window.document;
	var customizerModel = null;

	Post_Customizer.Models.Core = Backbone.Model.extend( {

		initialize : function( attributes ) {
			this.set( 'localizedData', attributes.localizedData );
		},

		showCustomizer : function( data ) {
			if( customizerModel !== null ) {
				customizerModel.closeCustomizer();
			}

			customizerModel = new Post_Customizer.Models.Customizer( {
				localizedData : this.get( 'localizedData' )
			} );
			customizerModel.openCustomizer();
		},

		getCustomizerModelObject : function() {
			if( customizerModel === null ) {
				return false;
			}
			return customizerModel;
		}

	} );

} )( window, Backbone, jQuery, _, Post_Customizer );


text:
#ifndef WorkerAsyncFileWriterChromium_h
#define WorkerAsyncFileWriterChromium_h

#include "modules/filesystem/AsyncFileWriter.h"
#include "wtf/PassOwnPtr.h"

namespace WebKit {
    class WebFileSystem;
    class WebFileWriter;
    class WebURL;
    class WorkerFileWriterCallbacksBridge;
}

namespace WTF {
    class String;
}
using WTF::String;

namespace WebCore {

class AsyncFileSystem;
class AsyncFileWriterClient;
class Blob;
class WorkerGlobalScope;

class WorkerAsyncFileWriterChromium : public AsyncFileWriter {
public:
    enum WriterType {
        Asynchronous,
        Synchronous,
    };

    static PassOwnPtr<WorkerAsyncFileWriterChromium> create(WebKit::WebFileSystem* webFileSystem, const WebKit::WebURL& path, WorkerGlobalScope* workerGlobalScope, AsyncFileWriterClient* client, WriterType type)
    {
        return adoptPtr(new WorkerAsyncFileWriterChromium(webFileSystem, path, workerGlobalScope, client, type));
    }
    ~WorkerAsyncFileWriterChromium();

    bool waitForOperationToComplete();

    // FileWriter
    virtual void write(long long position, Blob* data);
    virtual void truncate(long long length);
    virtual void abort();

private:

    WorkerAsyncFileWriterChromium(WebKit::WebFileSystem*, const WebKit::WebURL& path, WorkerGlobalScope*, AsyncFileWriterClient*, WriterType);
    RefPtr<WebKit::WorkerFileWriterCallbacksBridge> m_bridge;
};

} // namespace

#endif // AsyncFileWriterChromium_h


text:
{{vm.comment._id ? '编辑评论' : '新的评论'}}

    <form name="vm.form.commentForm" class="form-horizontal" ng-submit="vm.save(vm.form.commentForm.$valid)" novalidate>
      <fieldset>

          标题
          <input name="title" type="text" ng-model="vm.comment.title" id="title" class="form-control" placeholder="标题" required autofocus>

Comment title is required.

          正文
          <textarea name="content" data-ng-model="vm.comment.content" id="content" class="form-control" cols="30" rows="10" placeholder="正文"></textarea>

          <button type="submit" class="btn btn-default">{{vm.comment._id ? '更新' : '提交'}}</button>

      </fieldset>
    </form>


text:
package com.ror.res.entity;

import  javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Person {

	@Id
	private Long id;

	private String name;

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


text:
using System;
using System.Linq.Expressions;
using System.Reflection;

namespace Dapper.FluentMap.Utils
{
    /// <summary>
    /// Provides helper methods for reflection operations.
    /// </summary>
    public static class ReflectionHelper
    {
        /// <summary>
        /// Returns the <see cref="T:System.Reflection.MemberInfo"/> for the specified lamba expression.
        /// </summary>
        /// <param name="lambda">A lamba expression containing a MemberExpression.</param>
        /// <returns>A MemberInfo object for the member in the specified lambda expression.</returns>
        public static MemberInfo GetMemberInfo(LambdaExpression lambda)
        {
            Expression expr = lambda;
            while (true)
            {
                switch (expr.NodeType)
                {
                    case ExpressionType.Lambda:
                        expr = ((LambdaExpression)expr).Body;
                        break;

                    case ExpressionType.Convert:
                        expr = ((UnaryExpression)expr).Operand;
                        break;

                    case ExpressionType.MemberAccess:
                        var memberExpression = (MemberExpression)expr;
                        MemberInfo mi = memberExpression.Member;
                        // http://stackoverflow.com/a/6658781
                        Type paramType = lambda.Parameters[0].Type;
                        var memberInfo = paramType.GetMember(mi.Name)[0];

                        return memberInfo;

                    default:
                        return null;
                }
            }
        }
    }
}


text:
package io.getlime.security.powerauth.networking.endpoints;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.reflect.TypeToken;

import io.getlime.security.powerauth.ecies.EciesEncryptorId;
import io.getlime.security.powerauth.networking.interfaces.IEndpointDefinition;

public class RemoveTokenEndpoint implements IEndpointDefinition<Void> {

    @NonNull
    @Override
    public String getRelativePath() {
        return "/pa/v3/token/remove";
    }

    @NonNull
    @Override
    public String getHttpMethod() {
        return "POST";
    }

    @Nullable
    @Override
    public String getAuthorizationUriId() {
        return "/pa/token/remove";
    }

    @NonNull
    @Override
    public EciesEncryptorId getEncryptorId() {
        return EciesEncryptorId.NONE;
    }

    @Nullable
    @Override
    public TypeToken<Void> getResponseType() {
        return null;
    }

    @Override
    public boolean isSynchronized() {
        return true;
    }

    @Override
    public boolean isAvailableInProtocolUpgrade() {
        return false;
    }
}


text:
% bitflip_directFIRsymmetric_bandpass_test.m
% Copyright (C) 2017,2018 Robert G. Jenssen
%
% Test case for the bit-flipping algorithm with coefficents of
% a direct-form symmetric FIR bandpass filter.

test_common;

delete("bitflip_directFIRsymmetric_bandpass_test.diary");
delete("bitflip_directFIRsymmetric_bandpass_test.diary.tmp");
diary bitflip_directFIRsymmetric_bandpass_test.diary.tmp

bitflip_bandpass_test_common;

% File name string
strf="bitflip_directFIRsymmetric_bandpass_test";

% Frequency specifications for directFIRsymmetricEsqPW
waf=w([1 nasl napl napu nasu end]);
Adf=[0 0 1 0 0];
Waf=[Wasl 0 Wap 0 Wasu];

function [cost,hM,svec_out]= ...
         directFIRsymmetric_cost(svec,_waf,_Adf,_Waf,_hM0,_nbits,_ndigits)

  persistent waf Adf Waf
  persistent hM0
  persistent nbits nscale ndigits npoints
  persistent init_done=false

  if nargin==7
    cost=inf;
    waf=_waf(:);
    Adf=_Adf(:);
    Waf=_Waf(:);
    hM0=_hM0(:)';
    nbits=_nbits;
    ndigits=_ndigits;
    if nbits ~= 0
      nshift=2^(nbits-1);
      nscale=nshift./(2.^x2nextra(hM0,nshift));
    else
      nscale=1;
    endif
    svec=hM0.*nscale;
    init_done=true;
  elseif nargin ~= 1
    print_usage("[cost,hM,svec_out] = ...\n\
      directFIRsymmetric_cost(svec[,waf,Adf,Waf,hM0,nbits,ndigits])");
  elseif init_done==false
    error("init_done==false");
  endif
  svec=svec(:)';
  if nbits ~= 0
    if isscalar(ndigits) && ndigits == 0
      svec=round(svec)./nscale;
    else
      svec=svec./nscale;
      svec=flt2SD(svec,nbits,ndigits);
    endif
  endif
  hM=svec;
  cost=directFIRsymmetricEsqPW(hM,waf,Adf,Waf);
  svec_out=svec.*nscale;
endfunction

function r=find_range(h)
  r=ceil(-log2(min(abs(h(find(h~=0))))/max(abs(h))));
endfunction

% Initial symmetric FIR filter found by directFIRsymmetric_slb_bandpass_test
hM1 = [  -0.0004538174,  -0.0114029873,  -0.0194431345,  -0.0069796479, ...
          0.0215771882,   0.0348545408,   0.0158541332,  -0.0033225166, ...
          0.0154055974,   0.0414424100,  -0.0021970758,  -0.1162784301, ...
         -0.1760013118,  -0.0669604509,   0.1451751014,   0.2540400868 ]';

% Show the range of bits required by hM1
printf("hM1 has range %d bits\n",find_range(hM1));
r=find_range(round(hM1*nscale));
printf("hM1 rounded to %d bits has range %d bits\n",nbits,r);
if (nbits-r-1)<=0
  enbits=nbits;
  enscale=nscale;
else
  enbits=nbits+nbits-r-1;
  enscale=2^(enbits-1);
endif

% Find vector of exact coefficients
[cost_ex,hM_ex,svec_ex] = directFIRsymmetric_cost([],waf,Adf,Waf,hM1,0,0)

% Find the responses for exact, rounded, truncated and signed-digit coefficients
% Exact
nplot=1024;
wplot=(0:(nplot-1))'*pi/nplot;
A_ex=directFIRsymmetricA(wplot,hM_ex);
% Rounded truncation
[cost_rd,hM_rd,svec_rd] = directFIRsymmetric_cost([],waf,Adf,Waf,hM_ex,enbits,0)
A_rd=directFIRsymmetricA(wplot,hM_rd);
[hM_rd_digits,hM_rd_adders]=SDadders(hM_rd,enbits);
% Find optimised coefficients with bit-flipping
svec_bf=bitflip(@directFIRsymmetric_cost,svec_rd,enbits,bitstart,msize);
[cost_bf,hM_bf]=directFIRsymmetric_cost(svec_bf)
A_bf=directFIRsymmetricA(wplot,hM_bf);
[hM_bf_digits,hM_bf_adders]=SDadders(hM_bf,enbits);
fid=fopen(strcat(strf,"_bf_adders.tab"),"wt");
fprintf(fid,"$%d$",hM_bf_adders);
fclose(fid);
% Find the total number of adders required to implement the bitflipped
% rounded and bitflipped coefficients in transposed-direct-form
h_bft=[hM_bf,hM_bf((end-1):-1:1)];
[h_bft_digits,h_bft_adders]=SDadders(h_bft,enbits);
fid=fopen(strcat(strf,"_bft_adders.tab"),"wt");
fprintf(fid,"$%d$",h_bft_adders);
fclose(fid);
fid=fopen(strcat(strf,"_bft_digits.tab"),"wt");
fprintf(fid,"$%d$",h_bft_digits);
fclose(fid);

% Signed-digit truncation
[cost_sd,hM_sd,svec_sd] = ...
  directFIRsymmetric_cost([],waf,Adf,Waf,hM_ex,enbits,ndigits)
A_sd=directFIRsymmetricA(wplot,hM_sd);
[hM_sd_digits,hM_sd_adders]=SDadders(hM_sd,enbits);
% Find optimised coefficients with bit-flipping and signed-digits
svec_bfsd=bitflip(@directFIRsymmetric_cost,svec_sd,enbits,bitstart,msize);
[cost_bfsd,hM_bfsd]=directFIRsymmetric_cost(svec_bfsd)
A_bfsd=directFIRsymmetricA(wplot,hM_bfsd);
% Find the total number of adders required to implement the bitflipped SD coef.s
[hM_bfsd_digits,hM_bfsd_adders]=SDadders(hM_bfsd,enbits);
fid=fopen(strcat(strf,"_bfsd_adders.tab"),"wt");
fprintf(fid,"$%d$",hM_bfsd_adders);
fclose(fid);
% Find the total number of adders required to implement the bitflipped
% SD coef.s in transposed-direct-form
h_bfsdt=[hM_bfsd,hM_bfsd((end-1):-1:1)];
[h_bfsdt_digits,h_bfsdt_adders]=SDadders(h_bfsdt,enbits);
fid=fopen(strcat(strf,"_bfsdt_adders.tab"),"wt");
fprintf(fid,"$%d$",h_bfsdt_adders);
fclose(fid);
fid=fopen(strcat(strf,"_bfsdt_digits.tab"),"wt");
fprintf(fid,"$%d$",h_bfsdt_digits);
fclose(fid);

% Allocate signed digits with Lim's algorithm
ndigits_Lim=directFIRsymmetric_allocsd_Lim(enbits,ndigits,hM_ex, ...
                                           waf,Adf,ones(size(Waf)));

% Signed-digit truncation with Lim's algorithm
[cost_sdl,hM_sdl,svec_sdl] = ...
  directFIRsymmetric_cost([],waf,Adf,Waf,hM_ex,enbits,ndigits_Lim)
A_sdl=directFIRsymmetricA(wplot,hM_sdl);
[hM_sdl_digits,hM_sdl_adders]=SDadders(hM_sdl,enbits);
% Find optimised lattice coefficients with bit-flipping and signed-digits
svec_bfsdl=bitflip(@directFIRsymmetric_cost,svec_sdl,enbits,bitstart,msize);
[cost_bfsdl,hM_bfsdl]=directFIRsymmetric_cost(svec_bfsdl)
A_bfsdl=directFIRsymmetricA(wplot,hM_bfsdl);
% Find the total number of adders required to implement the SD multipliers
% with Lim's allocation method
[hM_bfsdl_digits,hM_bfsdl_adders]=SDadders(hM_bfsdl,enbits);
fname=strcat(strf,"_adders_Lim.tab");
fid=fopen(fname,"wt");
fprintf(fid,"$%d$",hM_bfsdl_adders);
fclose(fid);

% Allocate signed digits with Ito's algorithm
ndigits_Ito=directFIRsymmetric_allocsd_Ito(enbits,ndigits,hM_ex,waf,Adf,Waf);

% Signed-digit truncation with Ito's algorithm
[cost_sdi,hM_sdi,svec_sdi] = ...
  directFIRsymmetric_cost([],waf,Adf,Waf,hM_ex,enbits,ndigits_Ito)
A_sdi=directFIRsymmetricA(wplot,hM_sdi);
[hM_sdi_digits,hM_sdi_adders]=SDadders(hM_sdi,enbits);
% Find optimised lattice coefficients with bit-flipping and signed-digits
svec_bfsdi=bitflip(@directFIRsymmetric_cost,svec_sdi,enbits,bitstart,msize);
[cost_bfsdi,hM_bfsdi]=directFIRsymmetric_cost(svec_bfsdi)
A_bfsdi=directFIRsymmetricA(wplot,hM_bfsdi);
% Find the total number of adders required to implement the SD multipliers
% with Ito's allocation method
[hM_bfsdi_digits,hM_bfsdi_adders]=SDadders(hM_bfsdi,enbits);
fname=strcat(strf,"_adders_Ito.tab");
fid=fopen(fname,"wt");
fprintf(fid,"$%d$",hM_bfsdi_adders);
fclose(fid);

% Make a LaTeX table for cost
fname=strcat(strf,"_cost.tab");
fid=fopen(fname,"wt");
fprintf(fid,"Exact & %6.4f \\\\ \n",cost_ex);
fprintf(fid,"%d-bit rounded & %6.4f \\\\ \n",nbits,cost_rd);
fprintf(fid,"%d-bit rounded with bitflipping & %6.4f \\\\ \n",nbits,cost_bf);
fprintf(fid,"%d-bit %d-signed-digit & %6.4f \\\\ \n",nbits,ndigits,cost_sd);
fprintf(fid,"%d-bit %d-signed-digit with bitflipping & %6.4f \\\\ \n", ...
        nbits,ndigits,cost_bfsd);
fprintf(fid,"%d-bit %d-signed-digit(Lim alloc.) & %6.4f\\\\\n",
        nbits,ndigits,cost_sdl);
fprintf(fid,"%d-bit %d-signed-digit(Lim alloc.) with bit-flipping & %6.4f\\\\\n",
        nbits,ndigits,cost_bfsdl);
fprintf(fid,"%d-bit %d-signed-digit(Ito alloc.) & %6.4f\\\\\n",
        nbits,ndigits,cost_sdi);
fprintf(fid,"%d-bit %d-signed-digit(Ito alloc.) with bit-flipping & %6.4f\\\\\n",
        nbits,ndigits,cost_bfsdi);
fclose(fid);

% Plot the results
plot(wplot*0.5/pi,20*log10(abs(  A_ex)),"linestyle","-", ...
     wplot*0.5/pi,20*log10(abs(  A_rd)),"linestyle",":", ...
     wplot*0.5/pi,20*log10(abs(  A_bf)),"linestyle","--", ...
     wplot*0.5/pi,20*log10(abs(  A_sd)),"linestyle","-.", ...
     wplot*0.5/pi,20*log10(abs(A_bfsd)),"linestyle","-");
ylabel("Amplitude(dB)");
xlabel("Frequency");
axis([0 0.5 -60 10]);
grid("on");
strt=sprintf("Bandpass direct-form symmetric FIR, nbits=%d,bitstart=%d,\
msize=%d,ndigits=%d",nbits,bitstart,msize,ndigits);
title(strt);
legend("exact","round","bitflip(round)","signed-digit","bitflip(s-d)");
legend("location","northeast");
legend("boxoff");
legend("left");
print(strcat(strf,"_response"),"-dpdflatex");
close

% Plot results with signed-digit allocation
plot(wplot*0.5/pi,20*log10(abs(   A_ex)),"linestyle","-", ...
     wplot*0.5/pi,20*log10(abs(  A_sdl)),"linestyle",":", ...
     wplot*0.5/pi,20*log10(abs(A_bfsdl)),"linestyle","--", ...
     wplot*0.5/pi,20*log10(abs(  A_sdi)),"linestyle","-.", ...
     wplot*0.5/pi,20*log10(abs(A_bfsdi)),"linestyle","-")
xlabel("Frequency");
ylabel("Amplitude(dB)");
axis([0 0.5 -60 10]);
grid("on");
strt=sprintf("Bandpass direct-form symmetric FIR, nbits=%d,bitstart=%d,\
msize=%d,ndigits=%d, Lim and Ito SD allocation",nbits,bitstart,msize,ndigits);
title(strt);
legend("exact","signed-digit (Lim)","bitflip(s-d Lim)","signed-digit (Ito)", ...
       "bitflip(s-d Ito)");
legend("location","northeast");
legend("boxoff");
legend("left");
print(strcat(strf,"_response_allocsd"),"-dpdflatex");
close

% Print the results
print_polynomial(hM_ex,"hM_ex");
print_polynomial(hM_ex,"hM_ex",strcat(strf,"_hM_ex_coef.m"));

print_polynomial(hM_rd,"hM_rd",enscale);
print_polynomial(hM_rd,"hM_rd",strcat(strf,"_hM_rd_coef.m"),enscale);

print_polynomial(hM_bf,"hM_bf",enscale);
print_polynomial(hM_bf,"hM_bf",strcat(strf,"_hM_bf_coef.m"),enscale);

print_polynomial(hM_sd,"hM_sd",enscale);
print_polynomial(hM_sd,"hM_sd",strcat(strf,"_hM_sd_coef.m"),enscale);

print_polynomial(hM_bfsd,"hM_bfsd",enscale);
print_polynomial(hM_bfsd,"hM_bfsd",strcat(strf,"_hM_bfsd_coef.m"),enscale);

print_polynomial(hM_sdl,"hM_sdl",enscale);
print_polynomial(hM_sdl,"hM_sdl",strcat(strf,"_hM_sdl_coef.m"),enscale);

print_polynomial(hM_bfsdl,"hM_bfsdl",enscale);
print_polynomial(hM_bfsdl,"hM_bfsdl",strcat(strf,"_hM_bfsdl_coef.m"),enscale);

print_polynomial(hM_sdi,"hM_sdi",enscale);
print_polynomial(hM_sdi,"hM_sdi",strcat(strf,"_hM_sdi_coef.m"),enscale);

print_polynomial(hM_bfsdi,"hM_bfsdi",enscale);
print_polynomial(hM_bfsdi,"hM_bfsdi",strcat(strf,"_hM_bfsdi_coef.m"),enscale);

% Save the results
save bitflip_directFIRsymmetric_bandpass_test.mat ...
     hM_ex hM_rd hM_bf hM_sd hM_bfsd hM_sdl hM_bfsdl hM_sdi hM_bfsdi

% Done
diary off
movefile bitflip_directFIRsymmetric_bandpass_test.diary.tmp ...
         bitflip_directFIRsymmetric_bandpass_test.diary;


text:
// Generated by CoffeeScript 1.4.0
(function() {
  var IRCMessageHandler, exports, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __slice = [].slice;

  exports = (_ref = window.chat) != null ? _ref : window.chat = {};

  /*
   * Displays messages to the user when certain IRC events occur.
  */

  IRCMessageHandler = (function(_super) {

    __extends(IRCMessageHandler, _super);

    function IRCMessageHandler(_chat) {
      this._chat = _chat;
      this._formatter = new window.chat.MessageFormatter;
      this._chatLog = new chat.ChatLog;
      this._chatLog.whitelist('privmsg');
      this._ignoredMessages = {};
      IRCMessageHandler.__super__.constructor.apply(this, arguments);
    }

    /*
       * Ignore messages of a certain type when in the specified room.
       * @param {Context} context
       * @param {string} type
    */

    IRCMessageHandler.prototype.ignoreMessageType = function(context, type) {
      var _base, _ref1;
      if ((_ref1 = (_base = this._ignoredMessages)[context]) == null) {
        _base[context] = {};
      }
      this._ignoredMessages[context][type.toLowerCase()] = true;
      return this._chat.storage.ignoredMessagesChanged();
    };

    /*
       * Stop ignoring messages of a certain type when in the specified room.
       * @param {Context} context
       * @param {string} type
    */

    IRCMessageHandler.prototype.stopIgnoringMessageType = function(context, type) {
      type = type.toLowerCase();
      if (!this._ignoredMessages[context][type]) {
        return;
      }
      delete this._ignoredMessages[context][type];
      return this._chat.storage.ignoredMessagesChanged();
    };

    IRCMessageHandler.prototype.getIgnoredMessages = function() {
      return this._ignoredMessages;
    };

    IRCMessageHandler.prototype.setIgnoredMessages = function(ignoredMessages) {
      return this._ignoredMessages = ignoredMessages;
    };

    IRCMessageHandler.prototype.getChatLog = function() {
      return this._chatLog.getData();
    };

    IRCMessageHandler.prototype.logMessagesFromWindow = function(win) {
      return win.on('message', this._chatLog.add);
    };

    /*
       * Replays the given chatlog so the user can see the conversation they
       * missed.
    */

    IRCMessageHandler.prototype.replayChatLog = function(opt_chatLogData) {
      var context, win, _i, _len, _ref1, _results;
      if (opt_chatLogData) {
        this._chatLog.loadData(opt_chatLogData);
      }
      _ref1 = this._chatLog.getContextList();
      _results = [];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        context = _ref1[_i];
        win = this._chat.winList.get(context.server, context.channel);
        if (!win) {
          continue;
        }
        _results.push(win.rawHTML(this._chatLog.get(context)));
      }
      return _results;
    };

    /*
       * Sets which window messages will be displayed on.
       *
       * Call this method before calling handle().
    */

    IRCMessageHandler.prototype.setWindow = function(_win) {
      var _ref1;
      this._win = _win;
      return this._formatter.setNick((_ref1 = this._win.conn) != null ? _ref1.irc.nick : void 0);
    };

    IRCMessageHandler.prototype.setCustomMessageStyle = function(customStyle) {
      return this._formatter.setCustomStyle(customStyle);
    };

    IRCMessageHandler.prototype.handle = function() {
      var params, type;
      type = arguments[0], params = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
      this._setDefaultValues(params);
      IRCMessageHandler.__super__.handle.apply(this, [type].concat(__slice.call(params)));
      return this._sendFormattedMessage();
    };

    IRCMessageHandler.prototype._setDefaultValues = function(params) {
      var _ref1;
      this.source = '';
      this._formatter.clear();
      return (_ref1 = this._formatter).setContext.apply(_ref1, params);
    };

    /*
       * The formatter.setMessage() method accepts placeholder variables (#to, #from,
       * #content). By default, the first argument replaces #from, the 2nd argument
       * replaces #to and the last argument replaces #content.
    */

    IRCMessageHandler.prototype._handlers = {
      topic: function(from, topic) {
        this._chat.updateStatus();
        this._formatter.setContent(topic);
        if (!topic) {
          this._formatter.addStyle('notice');
          return this._formatter.setMessage('no topic is set');
        } else if (!from) {
          this._formatter.addStyle('notice');
          return this._formatter.setMessage('the topic is: #content');
        } else {
          this._formatter.addStyle('update');
          return this._formatter.setMessage('#from changed the topic to: #content');
        }
      },
      /*
           * Display when the topic was set and who it was set by.
      */

      topic_info: function(who, time) {
        this._formatter.addStyle('notice');
        this._formatter.setContent(getReadableTime(parseInt(time)));
        this._formatter.setMessage('Topic set by #from on #content.');
        return this._formatter.setPrettyFormat(false);
      },
      join: function(nick) {
        this._formatter.addStyle('update');
        this._formatter.setMessage('#from joined the channel');
        return this._win.nicks.add(nick);
      },
      part: function(nick) {
        this._formatter.addStyle('update');
        this._formatter.setMessage('#from left the channel');
        return this._win.nicks.remove(nick);
      },
      kick: function(from, to, reason) {
        this._formatter.addStyle('update');
        this._formatter.setMessage('#from kicked #to from the channel: #content');
        return this._win.nicks.remove(to);
      },
      nick: function(from, to) {
        if (this._isOwnNick(to)) {
          this._formatter.setFromUs(true);
          this._formatter.setToUs(false);
        }
        this._formatter.addStyle('update');
        this._formatter.setMessage('#from is now known as #to');
        if (!this._win.isServerWindow()) {
          this._win.nicks.remove(from);
          return this._win.nicks.add(to);
        }
      },
      mode: function(from, to, mode) {
        if (!to) {
          return;
        }
        this._formatter.addStyle('update');
        this._formatter.setContent(this._getModeMessage(mode));
        return this._formatter.setMessage('#from #content #to');
      },
      user_mode: function(who, mode) {
        this._formatter.addStyle('notice');
        this._formatter.setContext(void 0, who, mode);
        return this._formatter.setMessage('#to has modes #content');
      },
      quit: function(nick, reason) {
        this._formatter.addStyle('update');
        this._formatter.setMessage('#from has quit: #content');
        this._formatter.setContent(reason);
        return this._win.nicks.remove(nick);
      },
      disconnect: function() {
        this._formatter.addStyle('update');
        this._formatter.setMessage('Disconnected');
        return this._formatter.setFromUs(true);
      },
      connect: function() {
        this._formatter.addStyle('update');
        this._formatter.setMessage('Connected');
        return this._formatter.setFromUs(true);
      },
      privmsg: function(from, msg) {
        this._formatter.addStyle('update');
        this._handleMention(from, msg);
        return this._formatPrivateMessage(from, msg);
      },
      breakgroup: function(msg) {
        if (msg == null) {
          msg = '';
        }
        return this._formatter.setContentMessage(msg);
      },
      error: function(msg) {
        return this._formatter.setContentMessage(msg);
      },
      system: function(msg) {
        return this._formatter.setContentMessage(msg);
      },
      notice: function(msg) {
        this._formatter.addStyle('notice-group');
        return this._formatter.setContentMessage(msg);
      },
      welcome: function(msg) {
        this._formatter.addStyle('group');
        return this._formatter.setContentMessage(msg);
      },
      /*
           * Generic messages - usually boring server stuff like MOTD.
      */

      other: function(cmd) {
        this._formatter.addStyle('group');
        return this._formatter.setContentMessage(cmd.params[cmd.params.length - 1]);
      },
      nickinuse: function(taken, wanted) {
        var msg;
        this._formatter.addStyle('notice');
        msg = "Nickname " + taken + " already in use.";
        if (wanted) {
          msg += " Trying to get nickname " + wanted + ".";
        }
        return this._formatter.setMessage(msg);
      },
      away: function(msg) {
        this._chat.updateStatus();
        this._formatter.addStyle('notice');
        return this._formatter.setContentMessage(msg);
      },
      kill: function(from, to, msg) {
        this._formatter.addStyle('notice');
        /*
               * TODO: We can't use 'from' or 'msg' because they are not being properly
               * parsed by irc.util.parseCommand().
        */

        return this._formatter.setMessage("Kill command used on #to");
      },
      socket_error: function(errorCode) {
        this._formatter.addStyle('error');
        this._formatter.setToUs(true);
        switch (errorCode) {
          case -15:
            return this._formatter.setMessage('Disconnected: Remote host closed socket');
          default:
            return this._formatter.setMessage("Socket Error: " + errorCode);
        }
      }
    };

    IRCMessageHandler.prototype._getModeMessage = function(mode) {
      var post, pre;
      pre = mode[0] === '+' ? 'gave' : 'took';
      post = mode[0] === '+' ? 'to' : 'from';
      mode = this._getMode(mode);
      return "" + pre + " " + mode + " " + post;
    };

    IRCMessageHandler.prototype._getMode = function(mode) {
      switch (mode[1]) {
        case 'o':
          return 'channel operator status';
        case 'O':
          return 'local operator status';
        case 'v':
          return 'voice';
        case 'i':
          return 'invisible status';
        case 'w':
          return 'wall operator status';
        case 'a':
          return 'away status';
        default:
          return mode;
      }
    };

    IRCMessageHandler.prototype._getUserAction = function(msg) {
      return /^\u0001ACTION (.*)\u0001/.exec(msg);
    };

    IRCMessageHandler.prototype._handleMention = function(from, msg) {
      var nickMentioned, _ref1, _ref2;
      nickMentioned = this._nickWasMentioned(from, msg);
      if (nickMentioned) {
        this._chat.recordLastUserToMention(this._win.getContext(), from);
        if (!this._win.isPrivate()) {
          this._formatter.addStyle('mention');
        }
        if (this._shouldNotifyMention()) {
          this._createNotification(from, msg);
        }
      }
      if (!this._isFromWindowInFocus()) {
        this._chat.channelDisplay.activity((_ref1 = this._win.conn) != null ? _ref1.name : void 0, this._win.target);
        if (nickMentioned) {
          return this._chat.channelDisplay.mention((_ref2 = this._win.conn) != null ? _ref2.name : void 0, this._win.target);
        }
      }
    };

    IRCMessageHandler.prototype._createNotification = function(from, msg) {
      var notification, win,
        _this = this;
      win = this._win;
      notification = new chat.NickMentionedNotification(win.target, from, msg);
      win.notifications.add(notification);
      return win.notifications.on('clicked', function() {
        var _base;
        _this._chat.switchToWindow(win);
        return typeof (_base = chrome.app.window.current()).focus === "function" ? _base.focus() : void 0;
      });
    };

    IRCMessageHandler.prototype._nickWasMentioned = function(from, msg) {
      var nick, _ref1;
      nick = (_ref1 = this._win.conn) != null ? _ref1.irc.nick : void 0;
      if (this._isOwnNick(from)) {
        return false;
      }
      if (this._formatter.hasStyle('notice')) {
        return false;
      }
      if (this._formatter.hasStyle('direct')) {
        return false;
      }
      if (this._win.isPrivate()) {
        return true;
      }
      return chat.NickMentionedNotification.shouldNotify(nick, msg);
    };

    IRCMessageHandler.prototype._shouldNotifyMention = function() {
      return !this._isFromWindowInFocus() || !window.document.hasFocus();
    };

    IRCMessageHandler.prototype._isFromWindowInFocus = function() {
      return this._win.equals(this._chat.currentWindow);
    };

    IRCMessageHandler.prototype._formatPrivateMessage = function(from, msg) {
      var m;
      this._formatter.setMessage('#content');
      this._formatter.setPrettyFormat(false);
      if (m = this._getUserAction(msg)) {
        this._formatter.setContent("" + from + " " + m[1]);
        return this._formatter.addStyle('action');
      } else {
        if (this._formatter.hasStyle('notice')) {
          this.source = "-" + from + "-";
        } else if (this._formatter.hasStyle('direct')) {
          this.source = ">" + from + "<";
        } else {
          this.source = from;
        }
        return this._formatter.setContent(msg);
      }
    };

    IRCMessageHandler.prototype._sendFormattedMessage = function() {
      if (!this._formatter.hasMessage() || this._shouldIgnoreMessage(this._win.getContext(), this.type)) {
        return;
      }
      this._formatter.addStyle(this.type);
      return this._win.message(this.source, this._formatter.format(), this._formatter.getStyle());
    };

    IRCMessageHandler.prototype._shouldIgnoreMessage = function(context, type) {
      var _ref1;
      return (_ref1 = this._ignoredMessages[context]) != null ? _ref1[type] : void 0;
    };

    IRCMessageHandler.prototype._isOwnNick = function(nick) {
      var _ref1;
      return (_ref1 = this._win.conn) != null ? _ref1.irc.isOwnNick(nick) : void 0;
    };

    return IRCMessageHandler;

  })(MessageHandler);

  exports.IRCMessageHandler = IRCMessageHandler;

}).call(this);


text:
<?php

namespace app\modules\business\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\business\models\DriverDetails;

/**
 * DriverDetailsSearch represents the model behind the search form about `app\modules\business\models\DriverDetails`.
 */
class DriverDetailsSearch extends DriverDetails
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'customer_type', 'vehicle'], 'integer'],
            [['name', 'place', 'address', 'account_details', 'phone', 'status'], 'safe'],
            [['earning_percentage'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = DriverDetails::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
		$query->where(['=','customer_type',3]);
        $query->andFilterWhere([
            'id' => $this->id,
            'customer_type' => $this->customer_type,
            'vehicle' => $this->vehicle,
            'earning_percentage' => $this->earning_percentage,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'place', $this->place])
            ->andFilterWhere(['like', 'address', $this->address])
            ->andFilterWhere(['like', 'account_details', $this->account_details])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'status', $this->status]);

        return $dataProvider;
    }
}


text:
package dotty.tools.dotc
package typer

import core._
import Contexts._
import Types._
import Symbols._
import Decorators._
import typer.ProtoTypes._
import ast.{tpd, untpd}
import ast.Trees._
import scala.util.control.NonFatal

/** A version of Typer that keeps all symbols defined and referenced in a
 *  previously typed tree.
 *
 *  All definition nodes keep their symbols. All leaf nodes for idents, selects,
 *  and TypeTrees keep their types. Indexing is a no-op.
 *
 *  Otherwise, everything is as in Typer.
 */
class ReTyper extends Typer {
  import tpd._

  protected def promote(tree: untpd.Tree)(implicit ctx: Context): tree.ThisTree[Type] = {
    assert(tree.hasType, i"$tree ${tree.getClass} ${tree.uniqueId}")
    tree.withType(tree.typeOpt)
  }

  override def typedIdent(tree: untpd.Ident, pt: Type)(implicit ctx: Context): Tree =
    promote(tree)

  override def typedSelect(tree: untpd.Select, pt: Type)(implicit ctx: Context): Tree = {
    assert(tree.hasType, tree)
    val qual1 = typed(tree.qualifier, AnySelectionProto)
    untpd.cpy.Select(tree)(qual1, tree.name).withType(tree.typeOpt)
  }

  override def typedSelectFromTypeTree(tree: untpd.SelectFromTypeTree, pt: Type)(implicit ctx: Context): Tree = {
    assert(tree.hasType)
    val qual1 = typed(tree.qualifier, AnySelectionProto)
    untpd.cpy.SelectFromTypeTree(tree)(qual1, tree.name).withType(tree.typeOpt)
  }

  override def typedLiteral(tree: untpd.Literal)(implicit ctc: Context): Literal =
    promote(tree)

  override def typedThis(tree: untpd.This)(implicit ctx: Context): Tree =
    promote(tree)

  override def typedSuper(tree: untpd.Super, pt: Type)(implicit ctx: Context): Tree =
    promote(tree)

  override def typedTypeTree(tree: untpd.TypeTree, pt: Type)(implicit ctx: Context): TypeTree =
    promote(tree)

  override def typedBind(tree: untpd.Bind, pt: Type)(implicit ctx: Context): Bind = {
    assert(tree.hasType)
    val body1 = typed(tree.body, pt)
    untpd.cpy.Bind(tree)(tree.name, body1).withType(tree.typeOpt)
  }

  override def localDummy(cls: ClassSymbol, impl: untpd.Template)(implicit ctx: Context) = impl.symbol

  override def retrieveSym(tree: untpd.Tree)(implicit ctx: Context): Symbol = tree.symbol
  override def symbolOfTree(tree: untpd.Tree)(implicit ctx: Context): Symbol = tree.symbol

  override def localTyper(sym: Symbol) = this

  override def index(trees: List[untpd.Tree])(implicit ctx: Context) = ctx

  override def tryInsertApplyOrImplicit(tree: Tree, pt: ProtoType)(fallBack: (Tree, TyperState) => Tree)(implicit ctx: Context): Tree =
    fallBack(tree, ctx.typerState)

  override def addTypedModifiersAnnotations(mdef: untpd.MemberDef, sym: Symbol)(implicit ctx: Context): Unit =
    () // was: typedModifiers(Modifiers(sym), sym)
       // but annotations are not transformed after typer, so no use to check them.

  override def ensureConstrCall(cls: ClassSymbol, parents: List[Tree])(implicit ctx: Context): List[Tree] =
    parents

  override def encodeName(tree: untpd.NameTree)(implicit ctx: Context) = tree

  override def handleUnexpectedFunType(tree: untpd.Apply, fun: Tree)(implicit ctx: Context): Tree = fun.tpe match {
    case mt @ MethodType(_, formals) =>
      val args: List[Tree] = tree.args.zipWithConserve(formals)(typedExpr(_, _)).asInstanceOf[List[Tree]]
      assignType(untpd.cpy.Apply(tree)(fun, args), fun, args)
    case _ =>
      super.handleUnexpectedFunType(tree, fun)
  }

  override def typedUnadapted(tree: untpd.Tree, pt: Type)(implicit ctx: Context) =
    try super.typedUnadapted(tree, pt)
    catch {
      case NonFatal(ex) =>
        println(i"exception while typing $tree of class ${tree.getClass} # ${tree.uniqueId}")
        throw ex
    }

  override def checkVariance(tree: Tree)(implicit ctx: Context) = ()
}


text:
import vrep

propellers = ['propeller1Vel', 'propeller2Vel', 'propeller3Vel', 'propeller4Vel']

def init_rotors(clientID):
    # Clear all signals
    for i in range(len(propellers)):
        vrep.simxClearFloatSignal(clientID, propellers[i], vrep.simx_opmode_oneshot)

    # Set all propellers to zero
    for i in range(len(propellers)):
        vrep.simxSetFloatSignal(clientID, propellers[i], 0.0, vrep.simx_opmode_oneshot)

def move_rotors(clientID, propeller_vels):
        vrep.simxSetFloatSignal(clientID, propellers[0], propeller_vels[0], vrep.simx_opmode_oneshot)
        vrep.simxSetFloatSignal(clientID, propellers[1], propeller_vels[1], vrep.simx_opmode_oneshot)
        vrep.simxSetFloatSignal(clientID, propellers[2], propeller_vels[2], vrep.simx_opmode_oneshot)
        vrep.simxSetFloatSignal(clientID, propellers[3], propeller_vels[3], vrep.simx_opmode_oneshot)


text:
import {Nymph, Entity} from 'nymph-client';

export class Rendition extends Entity {
  // === Constructor ===

  constructor (id) {
    super(id);
    this.data.enabled = true;
    this.data.acOther = 1;
  }
}

// === Static Properties ===

// The name of the server class
Rendition.class = '\\uMailPHP\\Entities\\Rendition';

Nymph.setEntityClass(Rendition.class, Rendition);

export default Rendition;


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

namespace Mozu.Api.Contracts.CommerceRuntime.Orders
{
		///
		///	Properties of the resulting order validation performed by an order validation capability.
		///
		public class OrderValidationResult
		{
			///
			///Date and time when the entity was created, represented in UTC Date/Time.
			///
			public DateTime? CreatedDate { get; set; }

			///
			///Array list of validation and status messages associated with shipping rates, orders, and product purchasable state.
			///
			public List<OrderValidationMessage> Messages { get; set; }

			///
			///The current status of an object. This status is specific to the object including payment (New, Authorized, Captured, Declined, Failed, Voided, Credited, CheckRequested, or RolledBack), discount (Active, Scheduled, or Expired), returns (ReturnAuthorized), tenant, package (Fulfilled or NotFulfilled), application, master and product catalogs, orders (Pending, Submitted, Processing, Pending Review, Closed, or Canceled), and order validation results (Pass, Fail, Error, or Review).
			///
			public string Status { get; set; }

			///
			///Read-only identifier defined by the order validation capability that uniquely identifies this validation operation.
			///
			public string ValidationId { get; set; }

			///
			///Read-only name of this order validator supplied by the capability.
			///
			public string ValidatorName { get; set; }

			///
			///The type of order validator supplied by the capability. At this time, the only supported validator type is Fraud.
			///
			public string ValidatorType { get; set; }

		}

}


text:
import * as React from 'react'
import type { Subscribe } from './ReactHigherEventTypes.js'

const SubscribeContext = React.createContext<Subscribe | null>(null)

export default (SubscribeContext: React$Context<Subscribe | null>)


text:
require_relative "elasticsearch/transport/transport/http/aws"
module AwsEsTransport
  VERSION = "0.1.3"
end


text:
plugin.SocialFacebook = cc.Class.extend({

    /**
     methods of protocol : InterfaceSocial
     */
    init: function () {
        this._shareInfo = {
            'url': window.location.href
        };
    },
    configDeveloperInfo: function (cpInfo) {
        //invalid on html5
    },
    share: function (shareInfo) {
        var url = shareInfo["SharedURLPath"];
        if(url !== null){
            this._shareInfo.url = url;
        }

        cc.Browser.openURL("http://www.facebook.com/sharer/sharer.php?u=" + url);
    },
    setDebugMode: function (debug) {
        //invalid on html5
    },
    getSDKVersion: function () {
        return "unkown";
    },
    getPluginVersion: function () {
        return plugin.Version;
    }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns="http://maven.apache.org/XDOC/2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>Jawr :: Features</title>
  </properties>

 Free and open source: Released under an Apache 2.0 license, Jawr can be used free of charge with or
			without modifications, for both commercial and noncommercial purposes.

 Easy to setup: All you need to start using Jawr is to declare a couple of servlets in you deployment descriptor, create a simple .properties configuration file,
			and use the Jawr tag library to import css and javascript resources to your pages. A complete setup takes a matter of minutes and requires little or no modifications over time.

 Lightweight: Bundling and compression is done once at server startup so there is no overhead to requests. Also, a cache component
			is available and enabled by default to serve resources directly from memory instead of from the filesystem.

 Built-in minification and postprocessing: Jawr includes JSMin and the YUI compressor, both from Yahoo!. A custom minificator for
			CSS is also included, although the YUI compressor can be used for CSS too. For each bundle, a customizable postprocessing chain is executed
			during startup. Relative URLs in CSS files are rewritten by a postprocessor so they keep working with a different relative path. It is also
			easy to create custom postprocessors to perform any modifications to your js and css files at deploy time.
			  Learn more.

 Proxy-friendly gzip support: For each bundle there are two URLs that point to a gzipped and a regular version of the resource. Since the URLs
			are be generated within a JSP, the request headers are analyzed to decide if the browser will support gzipping and the appropriate URL is written out.
			With this system, caching proxies will not be a problem since it works around known Internet Explorer problems with the VARY header.

 Caching enforcement: Jawr will try its best to force your clients to cache the resources. If a browser asks if a file changed, a 304 (not modified)
			header is sent back with no content. On the other hand, with Jawr you will be 100% sure that new versions of your bundles are downloaded by all
			clients. Every URL to your resources will include an automatically generated, content-based prefix that changes automatically whenever a
			resource is updated. Once you deploy a new version, the URL to the bundle will change as well so it will be impossible that a client uses an
			older, cached version.

 Flexible bundling scheme: Choose which files go into which bundle, and in which order. Choose whether you want a bundle minified or not.
			Choose whether a bundle will be used only in development mode (for adding things such as console loggers). Create partially minified bundles.
			Create bundles which are automatically added within an Internet Explorer conditional comment.
			All with a very easy to use configuration system.
			  Learn more.

 CDN compatible: Jawr can be used easily with a CDN for even better response times.

 Global bundles: Some bundles such as libraries will be needed anywhere in your site where there is javascript code. Same goes for base CSS
			stylesheets. With Jawr, these will be added to pages automatically so you don't need to repeat the same import statement everywhere.

 Dynamic pages not required: Jawr can be used in plain HTML pages, so even if your application uses a mix of HTML and JSP (or other template based dynamic
			technology), Jawr can be used on every page.
			  Learn more.

 CoffeeScript: Jawr allows you to use coffeescript resource in your bundle mapping. Jawr will handle the compilation to Javascript.
			  Learn more.

 Less: Jawr allows you to use less resource in your bundle mapping. Jawr will handle the compilation to CSS.
			  Learn more.

 Sass: Jawr allows you to use SASS resource in your bundle mapping. Jawr will handle the compilation to CSS.
			  Learn more.

 CSS skin: Jawr allows you to define skin (theme) for your CSS bundle. This means that the user will get the CSS bundle skin depending on his current skin setting.
			  Learn more.

 Sprite generation support: You can define you sprite in your CSS by putting annotations and Jawr will generate the CSS bundles and the image sprites associated.
			  Learn more.

 Base64 encoded image support: Jawr allows you to define the image which you want to encode in base64 to minimize the HTTP request. It also support MHTML generation for IE6 and IE7.
			  Learn more.

 JMX support: You could modify the behaviour of Jawr at runtime using a JMX console. For example, you could pass an entire application from production mode to debug mode,
			or modify only one session.
			  Learn more.

 Bundle preprocessing: By default, the bundle processing is done at server startup, but you could preprocess your bundles, and use them directly. This will reduce the startup time of your application
			because Jawr will skip the bundle processing.
			  Learn more.

 Spring MVC support: Instead of configuring the Jawr servlet, you can tightly integrate it with your Spring MVC application by
			adding the provided Jawr Controller to your Spring descriptor.
			  Learn more.

 JSF/Facelets support: If you are using JSF with Facelets as the view technology, you can still use Jawr using a specific tag library.
			  Learn more.

 Wicket support: Jawr provides components for JS, CSS and images handled by Jawr.
			 Learn more.

 Grails plugin: Jawr can be used seamlessly in Grails applications, using a provided plugin that includes a GSP tag library.
			 Learn more.

 DWR integration: You can use DWR and have Jawr handle the serving of the static and dynamic scripts DWR generates, with the
					added feature of being able to bundle them together and with other scripts from your application.
					 Learn more.

 Struts/Commons Validator integration: finally you can minify and compress the validation scripts generated by this framework.
						With Jawr you can also bundle the Validator static javascript with other scripts in your application.
						 Learn more.

 Library friendly: Open source javascript libraries can be used seamlessly with Jawr. Most of these are modular or have plugins: add the modules or
			plugins you need and bundle all together. And, even if you minify them (thus eliminating comments), you can still keep the mandatory licenses in
			the bundle. The libraries tutorial will show you how to integrate popular js libraries such
			as Protoype, JQuery or YUI.

</document>


text:
using UnityEngine;
using System.Collections;

public class SwordsmanSounds : MonoBehaviour {

	public AudioClip swordClink;
	public AudioClip death;
	public AudioClip cackle;

	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {

	}

	public void PlaySound(AudioClip clip) {
		if(audio.isPlaying && audio.clip != clip)
		{
			audio.Stop();
			audio.clip = clip;
			audio.Play();
		} else if (!audio.isPlaying) {
			audio.clip = clip;
			audio.Play();
		}
	}

	public void StopSound(AudioClip clip) {
		if(audio.clip == clip) {
			audio.Stop();
			audio.clip = null;
		}
	}
}


text:
package org.apache.storm.kafka.spout.subscription;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.kafka.common.TopicPartition;
import org.apache.storm.kafka.spout.config.builder.SingleTopicKafkaSpoutConfiguration;
import org.apache.storm.task.TopologyContext;
import org.junit.Test;

public class RoundRobinManualPartitionerTest {

    private TopicPartition createTp(int partition) {
        return new TopicPartition(SingleTopicKafkaSpoutConfiguration.TOPIC, partition);
    }

    private Set<TopicPartition> partitionsToTps(int[] expectedPartitions) {
        Set<TopicPartition> expectedTopicPartitions = new HashSet<>();
        for(int i = 0; i < expectedPartitions.length; i++) {
            expectedTopicPartitions.add(createTp(expectedPartitions[i]));
        }
        return expectedTopicPartitions;
    }

    @Test
    public void testRoundRobinPartitioning() {
        List<TopicPartition> allPartitions = new ArrayList<>();
        for(int i = 0; i < 11; i++) {
            allPartitions.add(createTp(i));
        }
        List<TopologyContext> contextMocks = new ArrayList<>();
        String thisComponentId = "A spout";
        List<Integer> allTasks = Arrays.asList(new Integer[]{0, 1, 2});
        for(int i = 0; i < 3; i++) {
            TopologyContext contextMock = mock(TopologyContext.class);
            when(contextMock.getThisTaskIndex()).thenReturn(i);
            when(contextMock.getThisComponentId()).thenReturn(thisComponentId);
            when(contextMock.getComponentTasks(thisComponentId)).thenReturn(allTasks);
            contextMocks.add(contextMock);
        }
        RoundRobinManualPartitioner partitioner = new RoundRobinManualPartitioner();

        Set<TopicPartition> partitionsForFirstTask = partitioner.getPartitionsForThisTask(allPartitions, contextMocks.get(0));
        assertThat(partitionsForFirstTask, is(partitionsToTps(new int[]{0, 3, 6, 9})));

        Set<TopicPartition> partitionsForSecondTask = partitioner.getPartitionsForThisTask(allPartitions, contextMocks.get(1));
        assertThat(partitionsForSecondTask, is(partitionsToTps(new int[]{1, 4, 7, 10})));

        Set<TopicPartition> partitionsForThirdTask = partitioner.getPartitionsForThisTask(allPartitions, contextMocks.get(2));
        assertThat(partitionsForThirdTask, is(partitionsToTps(new int[]{2, 5, 8})));
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>

App Engine Python SDK
    v1.6.9 rev.445

The Python runtime is available as an experimental Preview feature.

google

appengine

api

search

search

GeoPoint

google.appengine.api.search.search.GeoPoint Member List

This is the complete list of members for google.appengine.api.search.search.GeoPoint, including all inherited members.

__eq__ (defined in google.appengine.api.search.search.GeoPoint)	google.appengine.api.search.search.GeoPoint

__init__	google.appengine.api.search.search.GeoPoint

__repr__ (defined in google.appengine.api.search.search.GeoPoint)	google.appengine.api.search.search.GeoPoint

latitude (defined in google.appengine.api.search.search.GeoPoint)	google.appengine.api.search.search.GeoPoint

latitude	google.appengine.api.search.search.GeoPoint

longitude (defined in google.appengine.api.search.search.GeoPoint)	google.appengine.api.search.search.GeoPoint

longitude	google.appengine.api.search.search.GeoPoint

<address class="footer">
    Maintained by tzmartin
</address>


text:
<?php

namespace Magento\Eav\Test\Unit\Model\Entity\Attribute\Backend;

class AbstractTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $_model;

    protected function setUp()
    {
        $this->_model = $this->getMockForAbstractClass(
            'Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend',
            [],
            '',
            false
        );
    }

    public function testGetAffectedFields()
    {
        $valueId = 10;
        $attributeId = 42;

        $attribute = $this->getMock(
            'Magento\Eav\Model\Entity\Attribute\AbstractAttribute',
            ['getBackendTable', 'isStatic', 'getAttributeId', '__wakeup'],
            [],
            '',
            false
        );
        $attribute->expects($this->any())->method('getAttributeId')->will($this->returnValue($attributeId));

        $attribute->expects($this->any())->method('isStatic')->will($this->returnValue(false));

        $attribute->expects($this->any())->method('getBackendTable')->will($this->returnValue('table'));

        $this->_model->setAttribute($attribute);

        $object = new \Magento\Framework\DataObject();
        $this->_model->setValueId($valueId);

        $this->assertEquals(
            ['table' => [['value_id' => $valueId, 'attribute_id' => $attributeId]]],
            $this->_model->getAffectedFields($object)
        );
    }
}


text:
package com.awplab.core.mongodb.admin;

import java.util.AbstractList;

/**
 * Created by andyphillips404 on 8/17/16.
 */
public class IndexList extends AbstractList<Integer> {
    private int size = 0;

    private int offset = 0;

    public IndexList(int size) {
        this.size = size;
    }

    public IndexList(int size, int offset) {
        this.size = size;
        this.offset = offset;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    @Override
    public Integer get(int index) {
        if (index >= size) throw new IndexOutOfBoundsException();
        return index + offset;
    }

    @Override
    public int size() {
        return size;
    }
}


text:
package sun.awt.image;

@SuppressWarnings("serial") // JDK-implementation class
public class ImageFormatException extends Exception {
    public ImageFormatException(String s) {
        super(s);
    }
}


text:
/** @internal
 ** @file     vl_pegasos.c
 ** @brief    vl_pegasos.c
 ** @author   Andrea Vedaldi
 **/

/* AUTORIGHTS
Copyright (C) 2007-09 Andrea Vedaldi and Brian Fulkerson

This file is part of VLFeat, available under the terms of the
GNU GPLv2, or (at your option) any later version.
*/

#include <mexutils.h>
#include <vl/pegasos.h>

#include <assert.h>
#include <string.h>

#include "kdtree.h"

/* option codes */
enum {
  opt_verbose, opt_bias_multiplier, opt_num_iterations,
  opt_starting_iteration, opt_starting_model
} ;

/* options */
vlmxOption  options [] = {
  {"Verbose",           0,   opt_verbose             },
  {"BiasMultiplier",    1,   opt_bias_multiplier     },
  {"NumIterations",     1,   opt_num_iterations      },
  {"StartingIteration", 1,   opt_starting_iteration  },
  {"StartingModel",     1,   opt_starting_model      },
  {0,                   0,   0                       }
} ;

/** ------------------------------------------------------------------
 ** @brief MEX entry point
 **/

void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_DATA, IN_LABELS, IN_LAMBDA, IN_END} ;
  enum {OUT_MODEL = 0} ;

  int            verbose = 0 ;
  int            opt ;
  int            next = IN_END ;
  mxArray const *optarg ;

  double biasMultiplier = 0 ;
  double lambda ;
  void * data ;
  mxClassID dataClass ;
  vl_type dataType ;
  vl_size numSamples ;
  vl_size dimension ;
  vl_size numIterations = 0 ;
  vl_uindex startingIteration = 1 ;

  VL_USE_MATLAB_ENV ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < 3) {
    vlmxError(vlmxErrInvalidArgument,
              "At least three arguments are required.") ;
  } else if (nout > 2) {
    vlmxError(vlmxErrInvalidArgument,
              "Too many output arguments.");
  }

  dataClass = mxGetClassID(IN(DATA)) ;

  if (! vlmxIsMatrix (IN(DATA), -1, -1) ||
      ! vlmxIsReal (IN(DATA))) {
    vlmxError(vlmxErrInvalidArgument,
              "DATA must be a real matrix.") ;
  }

  dimension = mxGetM(IN(DATA)) ;
  numSamples = mxGetN(IN(DATA)) ;

  switch (dataClass) {
  case mxSINGLE_CLASS : dataType = VL_TYPE_FLOAT ; break ;
  case mxDOUBLE_CLASS : dataType = VL_TYPE_DOUBLE ; break ;
  default:
    vlmxError(vlmxErrInvalidArgument,
              "DATA must be either SINGLE or DOUBLE.") ;
  }

  if (mxGetClassID(IN(LABELS)) != mxINT8_CLASS) {
    vlmxError(vlmxErrInvalidArgument, "LABELS must be INT8.") ;
  }
  if (! vlmxIsVector(IN(LABELS), numSamples)) {
    vlmxError(vlmxErrInvalidArgument, "LABELS is not a vector of dimension compatible with DATA.") ;
  }

  if (! vlmxIsPlainScalar(IN(LAMBDA))) {
    vlmxError(vlmxErrInvalidArgument, "LAMBDA is not a plain scalar.") ;
  }
  lambda = *mxGetPr(IN(LAMBDA)) ;

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {
    switch (opt) {
      case opt_bias_multiplier :
        if (!vlmxIsPlainScalar(optarg)) {
          vlmxError(vlmxErrInvalidArgument, "BIASMULTIPLIER is not a plain scalar.") ;
        }
        biasMultiplier = *mxGetPr(optarg) ;
        break ;
      case opt_num_iterations :
        if (!vlmxIsPlainScalar(optarg)) {
          vlmxError(vlmxErrInvalidArgument, "NUMITERATIONS is not a plain scalar.") ;
        }
        if (*mxGetPr(optarg) < 0) {
          vlmxError(vlmxErrInvalidArgument, "NUMITERATIONS is negative.") ;
        }
        numIterations = (vl_size) *mxGetPr(optarg) ;
        break ;
      case opt_starting_iteration :
        if (!vlmxIsPlainScalar(optarg)) {
          vlmxError(vlmxErrInvalidArgument, "STARTINGITERATION is not a plain scalar.") ;
        }
        if (*mxGetPr(optarg) < 1) {
          vlmxError(vlmxErrInvalidArgument, "STARTINGITERATION is smaller than 1.") ;
        }
        startingIteration = (vl_size) *mxGetPr(optarg) ;
        break ;

      case opt_starting_model :
        if (!vlmxIsVector(optarg, -1)) {
          vlmxError(vlmxErrInvalidArgument, "STARTINGMODEL is not a plain vector.") ;
        }
        OUT(MODEL) = mxDuplicateArray(optarg) ;
        break ;

      case opt_verbose :
        ++ verbose ;
        break ;
    }
  }

  if (numIterations == 0) {
    numIterations = (vl_size) 10 / (lambda + 1) ;
  }

  data = mxGetData (IN(DATA)) ;
  numSamples = mxGetN (IN(DATA)) ;
  dimension = mxGetM (IN(DATA)) ;

  if (! OUT(MODEL)) {
    OUT(MODEL) = mxCreateNumericMatrix(dimension + (biasMultiplier > 0),
                                       1,
                                       dataClass, mxREAL) ;
  } else {
    if (mxGetClassID(OUT(MODEL)) != dataClass) {
      vlmxError(vlmxErrInvalidArgument, "STARTINGMODEL is not of the same class of DATA.") ;
    }
    if (mxGetNumberOfElements(OUT(MODEL)) != dimension + (biasMultiplier > 0)) {
      vlmxError(vlmxErrInvalidArgument, "STARTINGMODEL has incompatible dimension.") ;
    }
  }

  if (verbose) {
    mexPrintf("vl_pegasos: Lambda = %g\n", lambda) ;
    mexPrintf("vl_pegasos: BiasMultiplier = %g\n", biasMultiplier) ;
    mexPrintf("vl_pegasos: NumIterations = %d\n", numIterations) ;
  }

  switch (dataType) {
    case VL_TYPE_FLOAT :
      vl_pegasos_train_binary_svm_f((float *)mxGetData(OUT(MODEL)),
                                    (float const *)mxGetPr(IN(DATA)), dimension, numSamples,
                                    (vl_int8 const *)mxGetData(IN(LABELS)),
                                    lambda,
                                    biasMultiplier,
                                    startingIteration,
                                    numIterations,
                                    NULL) ;
      break ;
    case VL_TYPE_DOUBLE:
      vl_pegasos_train_binary_svm_d((double *)mxGetData(OUT(MODEL)),
                                    (double const *)mxGetData(IN(DATA)), dimension, numSamples,
                                    (vl_int8 const *)mxGetData(IN(LABELS)),
                                    lambda,
                                    biasMultiplier,
                                    startingIteration,
                                    numIterations,
                                    NULL) ;
      break ;
  }

}


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

<TITLE>
org.springframework.orm (Spring Framework API 2.5)
</TITLE>

<META NAME="date" CONTENT="2007-11-19">

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

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package org.springframework.orm

Root package for Spring's O/R Mapping integration classes.

See:

          Description

Exception Summary

ObjectOptimisticLockingFailureException
Exception thrown on an optimistic locking violation for a mapped object.

ObjectRetrievalFailureException
Exception thrown if a mapped object could not be retrieved via its identifier.

Package org.springframework.orm Description

Root package for Spring's O/R Mapping integration classes.
Contains generic DataAccessExceptions related to O/R Mapping.

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

The Spring Framework

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2007 The Spring Framework.


text:
If you have a simple query to run and you want to do it inline, you can do so:

```js
db.run("select * from products", function(err,res){
  //all products returned in array
});
```

You can parameterize the query using placeholders. Note that the values need to be specified as an array:

```js
db.run("select * from products where name LIKE $1",["%fruity%"], function(err,res){
  //all matching products returned in array
});
```

For additional parameters, use `$2`, `$3`, etc.

## Using `where()`

You can save yourself from repeated `select * from` typing by accessing the loaded tables on your DB instance and then using `where()`. Our `find` syntax is quite helpful, but we've added this method so you can find what you need if your WHERE statement is complex:

```js
db.products.where("id=$1 OR id=$2", [10,21], function(err,products){
  //products 10 and 21
});
```

## Using `find()`

You don't need to `select *` your way through your data, Massive supports simple `find` syntax:

```js
//find by id
db.products.find(1, function(err,res){
  //res.id == 1
});

//another way to do the above
db.users.findOne(1, function(err,user){
  //returns user with id (or whatever your PK is) of 1
});

//find first match
db.users.findOne({email : "test@test.com"}, function(err,user){
  //returns the first match
});

//all active users
db.users.find({active: true}, function(err,users){
  //all users who are active
});

//Send in an ORDER clause and a LIMIT with OFFSET
var options = {
  limit : 10,
  order : "id",
  offset: 20
}
db.products.find({}, options, function(err,products){
  //products ordered in descending fashion
});

//You only want the sku and name back
var options = {
  limit : 10,
  columns : ["sku", "name"]
}
db.products.find({}, options, function(err,products){
  // an array of sku and name
});

//an IN query
db.products.find({id : [10,21]}, function(err,products){
  //products 10 and 21
});

//a NOT IN query
db.products.find({"id <>": [10,21]}, function(err,products){
  //products other than 10 and 21
});

db.products.find({"id < " : 2}, function(err,res){
  //id less than 2
});

db.products.find({"id < " : 2}, function(err,res){
  //id greater than 2
});

//Send in an ORDER clause by passing in a second argument
db.products.find({},{order: "price desc"} function(err,products){
  //products ordered in descending fashion
});
```

Massive also supports JSON specification if you have a `json` or `jsonb` column you want to use:

```js
//match a JSON field
db.products.find({"specs->>weight": 30}, function(err, products) {
  //products where the 'specs' field is a JSON document containing {weight: 30}
  //note that the corresponding SQL query would be phrased specs->>'weight'; Massive adds the quotes for you
});

//match a JSON field with an IN list (note NOT IN is not supported for JSON fields at this time)
db.products.find({"specs->>weight": [30, 35]}, function(err, products) {
  //products where the 'specs' field is a JSON document containing {weight: 30}
  //note that the corresponding SQL query would be phrased specs->>'weight'; Massive adds the quotes for you
});

//drill down a JSON path
db.products.find({"specs#>>{dimensions,length}": 15}, function(err, products) {
  //products where the 'specs' field is a JSON document having a nested 'dimensions' object containing {length: 15}
  //note that the corresponding SQL query would be phrased specs->>'{dimensions,length}'; Massive adds the quotes for you
});
```

## Using `count()`

You can get the number of records for a query by using the count method:

```js
db.products.count({id: [1, 2]}, function(err,res){
  //returns 2 as the result
});
```

## Using Schemas

If you like to separate your tables based on a schema, you can still work with them easily with Massive. For instance, our `users` table might be part of the `membership` schema:

```js
db.membership.users.find(1, function(err,res){
  //user returned
});
```


text:
FROM ubuntu:14.04
MAINTAINER Jan Safranek, jsafrane@redhat.com
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update -qq && apt-get install -y nfs-kernel-server -qq
RUN mkdir -p /exports
ADD run_nfs.sh /usr/local/bin/
ADD index.html /exports/index.html

EXPOSE 2049/tcp

ENTRYPOINT ["/usr/local/bin/run_nfs.sh", "/exports"]


text:
""" This module provides a structure to hang the configuration settings. We
use an empty class structure and manually populate it. The global defaults
will be overlaid with any settings from the local agent configuration file.
For a specific application we will then deep copy the global default
settings and then overlay that with application settings obtained from the
server side core application. Finally, to allow for local testing and
debugging, for selected override configuration settings, we will apply back
the global defaults or those from local agent configuration.

"""

import os
import logging
import copy

# The Settings objects and the global default settings. We create a
# distinct type for each sub category of settings that the agent knows
# about so that an error when accessing a non existant setting is more
# descriptive and identifies the category of settings. When applying
# server side configuration we create normal Settings object for new
# sub categories we don't know about.

class Settings(object):
    def __repr__(self):
        return repr(self.__dict__)
    def __iter__(self):
        return iter(flatten_settings(self).items())

class ThreadProfilerSettings(Settings): pass
class TransactionTracerSettings(Settings): pass
class ErrorCollectorSettings(Settings): pass
class BrowserMonitorSettings(Settings): pass
class TransactionNameSettings(Settings): pass
class TransactionMetricsSettings(Settings): pass
class RumSettings(Settings): pass
class SlowSqlSettings(Settings): pass
class AgentLimitsSettings(Settings): pass
class ConsoleSettings(Settings): pass
class DebugSettings(Settings): pass
class CrossApplicationTracerSettings(Settings): pass
class XraySessionSettings(Settings): pass
class AnalyticsEventsSettings(Settings): pass
class AnalyticsEventsTransactionsSettings(Settings): pass

_settings = Settings()
_settings.thread_profiler = ThreadProfilerSettings()
_settings.xray_session = XraySessionSettings()
_settings.transaction_tracer = TransactionTracerSettings()
_settings.error_collector = ErrorCollectorSettings()
_settings.browser_monitoring = BrowserMonitorSettings()
_settings.transaction_name = TransactionNameSettings()
_settings.transaction_metrics = TransactionMetricsSettings()
_settings.rum = RumSettings()
_settings.slow_sql = SlowSqlSettings()
_settings.agent_limits = AgentLimitsSettings()
_settings.console = ConsoleSettings()
_settings.debug = DebugSettings()
_settings.cross_application_tracer = CrossApplicationTracerSettings()
_settings.analytics_events = AnalyticsEventsSettings()
_settings.analytics_events.transactions = AnalyticsEventsTransactionsSettings()

_settings.log_file = os.environ.get('NEW_RELIC_LOG', None)

def _environ_as_bool(name, default=False):
    flag = os.environ.get(name, default)
    if default is None or default:
        try:
            flag = not flag.lower() in ['off', 'false', '0']
        except AttributeError:
            pass
    else:
        try:
            flag = flag.lower() in ['on', 'true', '1']
        except AttributeError:
            pass
    return flag

def _parse_ignore_status_codes(value, target):
    items = value.split()
    for item in items:
        try:
            negate = item.startswith('!')
            if negate:
                item = item[1:]

            start, end = item.split('-')

            values = set(range(int(start), int(end)+1))

            if negate:
                target.symmetric_difference_update(values)
            else:
                target.update(values)

        except ValueError:
            if negate:
                target.remove(int(item))
            else:
                target.add(int(item))
    return target

_LOG_LEVEL = {
    'CRITICAL': logging.CRITICAL,
    'ERROR': logging.ERROR,
    'WARNING': logging.WARNING,
    'INFO': logging.INFO,
    'DEBUG': logging.DEBUG,
}

_settings.enabled = _environ_as_bool('NEW_RELIC_ENABLED', False)

_settings.log_level = os.environ.get('NEW_RELIC_LOG_LEVEL', 'INFO').upper()

if _settings.log_level in _LOG_LEVEL:
    _settings.log_level = _LOG_LEVEL[_settings.log_level]
else:
    _settings.log_level = logging.INFO

_settings.license_key = os.environ.get('NEW_RELIC_LICENSE_KEY', None)

_settings.ssl = _environ_as_bool('NEW_RELIC_SSL', True)

_settings.host = os.environ.get('NEW_RELIC_HOST', 'collector.newrelic.com')
_settings.port = int(os.environ.get('NEW_RELIC_PORT', '0'))

_settings.proxy_scheme = os.environ.get('NEW_RELIC_PROXY_SCHEME', None)
_settings.proxy_host = os.environ.get('NEW_RELIC_PROXY_HOST', None)
_settings.proxy_port = int(os.environ.get('NEW_RELIC_PROXY_PORT', '0'))
_settings.proxy_user = os.environ.get('NEW_RELIC_PROXY_USER', None)
_settings.proxy_pass = os.environ.get('NEW_RELIC_PROXY_PASS', None)

_settings.app_name = os.environ.get('NEW_RELIC_APP_NAME', 'Python Application')

_settings.monitor_mode = _environ_as_bool('NEW_RELIC_MONITOR_MODE', True)

_settings.collect_errors = True
_settings.collect_traces = True
_settings.collect_analytics_events = True

_settings.apdex_t = 0.5
_settings.web_transactions_apdex = {}

_settings.capture_params = False
_settings.ignored_params = []

_settings.capture_environ = True
_settings.include_environ = ['REQUEST_METHOD', 'HTTP_USER_AGENT',
                              'HTTP_REFERER', 'CONTENT_TYPE',
                              'CONTENT_LENGTH']

_settings.sampling_rate = 0

_settings.startup_timeout = float(
       os.environ.get('NEW_RELIC_STARTUP_TIMEOUT', '0.0'))
_settings.shutdown_timeout = float(
       os.environ.get('NEW_RELIC_SHUTDOWN_TIMEOUT', '2.5'))

_settings.beacon = None
_settings.error_beacon = None
_settings.application_id = None
_settings.browser_key = None
_settings.episodes_url = None
_settings.js_agent_loader = None
_settings.js_agent_file = None

_settings.url_rules = []
_settings.metric_name_rules = []
_settings.transaction_name_rules = []

_settings.cross_process_id = None
_settings.trusted_account_ids = []
_settings.encoding_key = None

_settings.thread_profiler.enabled = True
_settings.cross_application_tracer.enabled = True
_settings.xray_session.enabled = True

_settings.analytics_events.enabled = True
_settings.analytics_events.capture_attributes = True
_settings.analytics_events.max_samples_stored = 1200
_settings.analytics_events.transactions.enabled = True

_settings.transaction_tracer.enabled = True
_settings.transaction_tracer.transaction_threshold = None
_settings.transaction_tracer.record_sql = 'obfuscated'
_settings.transaction_tracer.stack_trace_threshold = 0.5
_settings.transaction_tracer.explain_enabled = True
_settings.transaction_tracer.explain_threshold = 0.5
_settings.transaction_tracer.function_trace = []
_settings.transaction_tracer.generator_trace = []
_settings.transaction_tracer.top_n = 20
_settings.transaction_tracer.capture_attributes = True

_settings.error_collector.enabled = True
_settings.error_collector.capture_source = False
_settings.error_collector.ignore_errors = []
_settings.error_collector.ignore_status_codes = _parse_ignore_status_codes(
        '100-102 200-208 226 300-308 404', set())
_settings.error_collector.capture_attributes = True

_settings.browser_monitoring.enabled = True
_settings.browser_monitoring.auto_instrument = True
_settings.browser_monitoring.loader = 'rum'  # Valid values: 'full', 'none'
_settings.browser_monitoring.loader_version = None
_settings.browser_monitoring.debug = False
_settings.browser_monitoring.ssl_for_http = None
_settings.browser_monitoring.capture_attributes = False

_settings.transaction_name.limit = None
_settings.transaction_name.naming_scheme = os.environ.get(
        'NEW_RELIC_TRANSACTION_NAMING_SCHEME')

_settings.slow_sql.enabled = True

_settings.agent_limits.data_collector_timeout = 30.0
_settings.agent_limits.transaction_traces_nodes = 2000
_settings.agent_limits.sql_query_length_maximum = 16384
_settings.agent_limits.slow_sql_stack_trace = 30
_settings.agent_limits.sql_explain_plans = 30
_settings.agent_limits.slow_sql_data = 10
_settings.agent_limits.merge_stats_maximum = 5
_settings.agent_limits.errors_per_transaction = 5
_settings.agent_limits.errors_per_harvest = 20
_settings.agent_limits.slow_transaction_dry_harvests = 5
_settings.agent_limits.thread_profiler_nodes = 20000
_settings.agent_limits.browser_transactions = 10
_settings.agent_limits.xray_transactions = 10
_settings.agent_limits.xray_profile_overhead = 0.05
_settings.agent_limits.xray_profile_maximum = 500

_settings.console.listener_socket = None
_settings.console.allow_interpreter_cmd = False

_settings.debug.ignore_all_server_settings = False
_settings.debug.local_settings_overrides = []

_settings.debug.log_agent_initialization = False
_settings.debug.log_data_collector_calls = False
_settings.debug.log_data_collector_payloads = False
_settings.debug.log_malformed_json_data = False
_settings.debug.log_transaction_trace_payload = False
_settings.debug.log_thread_profile_payload = False
_settings.debug.log_normalization_rules = False
_settings.debug.log_raw_metric_data = False
_settings.debug.log_normalized_metric_data = False
_settings.debug.record_transaction_failure = False

_settings.debug.enable_coroutine_profiling = False

def global_settings():
    """This returns the default global settings. Generally only used
    directly in test scripts and test harnesses or when applying global
    settings from agent configuration file. Making changes to the settings
    object returned by this function will not have any effect on any
    applications that have already been initialised. This is because when
    the settings are obtained from the core application a snapshot of these
    settings will be taken.

    >>> global_settings = global_settings()
    >>> global_settings.browser_monitoring.auto_instrument = False
    >>> global_settings.browser_monitoring.auto_instrument
    False

    """

    return _settings

def flatten_settings(settings):
    """This returns dictionary of settings flattened into a single
    key namespace rather than nested hierarchy.

    """

    def _flatten(settings, name, object):
        for key, value in object.__dict__.items():
            if isinstance(value, Settings):
                if name:
                    _flatten(settings, '%s.%s' % (name, key), value)
                else:
                    _flatten(settings, key, value)
            else:
                if name:
                    settings['%s.%s' % (name, key)] = value
                else:
                    settings[key] = value

        return settings

    return _flatten({}, None, settings)

def global_settings_dump():
    """This returns dictionary of global settings flattened into a single
    key namespace rather than nested hierarchy. This is used to send the
    global settings configuration back to core application.

    """

    settings = flatten_settings(_settings)

    # Strip out any sensitive settings as can be sent unencrypted.
    # The license key is being sent already, but no point sending
    # it again.

    del settings['license_key']

    del settings['proxy_user']
    del settings['proxy_pass']

    return settings

# Creation of an application settings object from global default settings
# and any server side configuration settings.

def apply_config_setting(settings_object, name, value):
    """Apply a setting to the settings object where name is a dotted path.
    If there is no pre existing settings object for a sub category then
    one will be created and added automatically.

    >>> name = 'browser_monitoring.auto_instrument'
    >>> value = False
    >>>
    >>> global_settings = global_settings()
    >>> _apply_config_setting(global_settings, name, value)

    """

    target = settings_object
    fields = name.split('.', 1)

    while len(fields) > 1:
        if not hasattr(target, fields[0]):
            setattr(target, fields[0], Settings())
        target = getattr(target, fields[0])
        fields = fields[1].split('.', 1)

    setattr(target, fields[0], value)

def fetch_config_setting(settings_object, name):
    """Fetch a setting from the settings object where name is a dotted path.

    >>> name = 'browser_monitoring.auto_instrument'
    >>>
    >>> global_settings = global_settings()
    >>> _fetch_config_setting(global_settings, name)
    'browser_monitoring.auto_instrument'

    """

    target = settings_object
    fields = name.split('.', 1)

    target = getattr(target, fields[0])

    while len(fields) > 1:
        fields = fields[1].split('.', 1)
        target = getattr(target, fields[0])

    return target

def create_settings_snapshot(server_side_config={}, settings=_settings):
    """Create a snapshot of the global default settings and overlay it
    with any server side configuration settings. Any local settings
    overrides to take precedence over server side configuration settings
    will then be reapplied to the copy. Note that the intention is that
    the resulting settings object will be cached for subsequent use
    within the application object the settings pertain to.

    >>> server_config = { 'browser_monitoring.auto_instrument': False }
    >>>
    >>> settings_snapshot = create_settings_snapshot(server_config)

    """

    settings_snapshot = copy.deepcopy(settings)

    # Break out the server side agent config settings which
    # are stored under 'agent_config' key.

    agent_config = server_side_config.pop('agent_config', {})

    # Remap as necessary any server side agent config settings.

    if 'transaction_tracer.transaction_threshold' in agent_config:
        value = agent_config['transaction_tracer.transaction_threshold']
        if value == 'apdex_f':
            agent_config['transaction_tracer.transaction_threshold'] = None

    # Overlay with global server side configuration settings.

    for (name, value) in server_side_config.items():
        apply_config_setting(settings_snapshot, name, value)

    # Overlay with agent server side configuration settings.
    # Assuming for now that agent service side configuration
    # can always take precedence over the global server side
    # configuration settings.

    for (name, value) in agent_config.items():
        apply_config_setting(settings_snapshot, name, value)

    # Reapply on top any local setting overrides.

    for name in _settings.debug.local_settings_overrides:
        value = fetch_config_setting(_settings, name)
        apply_config_setting(settings_snapshot, name, value)

    return settings_snapshot

def ignore_status_code(status):
    return status in _settings.error_collector.ignore_status_codes


text:
function f(addUndefined1 = "J", addUndefined2?: number) {
    return addUndefined1.length + (addUndefined2 || 0);
}
function g(addUndefined = "J", addDefined: number) {
    return addUndefined.length + addDefined;
}
let total = f() + f('a', 1) + f('b') + f(undefined, 2);
total = g('c', 3) + g(undefined, 4);

function foo1(x: string = "string", b: number) {
    x.length;
}

function foo2(x = "string", b: number) {
    x.length; // ok, should be string
}

function foo3(x: string | undefined = "string", b: number) {
    x.length; // ok, should be string
    x = undefined;
}

function foo4(x: string | undefined = undefined, b: number) {
    x; // should be string | undefined
    x = undefined;
}

type OptionalNullableString = string | null | undefined;
function allowsNull(val: OptionalNullableString = "") {
    val = null;
    val = 'string and null are both ok';
}
allowsNull(null); // still allows passing null

// .d.ts should have `string | undefined` for foo1, foo2, foo3 and foo4
foo1(undefined, 1);
foo2(undefined, 1);
foo3(undefined, 1);
foo4(undefined, 1);

function removeUndefinedButNotFalse(x = true) {
    if (x === false) {
        return x;
    }
}

declare const cond: boolean;
function removeNothing(y = cond ? true : undefined) {
    if (y !== undefined) {
        if (y === false) {
            return y;
        }
    }
    return true;
}

//// [defaultParameterAddsUndefinedWithStrictNullChecks.js]
function f(addUndefined1, addUndefined2) {
    if (addUndefined1 === void 0) { addUndefined1 = "J"; }
    return addUndefined1.length + (addUndefined2 || 0);
}
function g(addUndefined, addDefined) {
    if (addUndefined === void 0) { addUndefined = "J"; }
    return addUndefined.length + addDefined;
}
var total = f() + f('a', 1) + f('b') + f(undefined, 2);
total = g('c', 3) + g(undefined, 4);
function foo1(x, b) {
    if (x === void 0) { x = "string"; }
    x.length;
}
function foo2(x, b) {
    if (x === void 0) { x = "string"; }
    x.length; // ok, should be string
}
function foo3(x, b) {
    if (x === void 0) { x = "string"; }
    x.length; // ok, should be string
    x = undefined;
}
function foo4(x, b) {
    if (x === void 0) { x = undefined; }
    x; // should be string | undefined
    x = undefined;
}
function allowsNull(val) {
    if (val === void 0) { val = ""; }
    val = null;
    val = 'string and null are both ok';
}
allowsNull(null); // still allows passing null
// .d.ts should have `string | undefined` for foo1, foo2, foo3 and foo4
foo1(undefined, 1);
foo2(undefined, 1);
foo3(undefined, 1);
foo4(undefined, 1);
function removeUndefinedButNotFalse(x) {
    if (x === void 0) { x = true; }
    if (x === false) {
        return x;
    }
}
function removeNothing(y) {
    if (y === void 0) { y = cond ? true : undefined; }
    if (y !== undefined) {
        if (y === false) {
            return y;
        }
    }
    return true;
}

//// [defaultParameterAddsUndefinedWithStrictNullChecks.d.ts]
declare function f(addUndefined1?: string, addUndefined2?: number): number;
declare function g(addUndefined: string | undefined, addDefined: number): number;
declare let total: number;
declare function foo1(x: string | undefined, b: number): void;
declare function foo2(x: string | undefined, b: number): void;
declare function foo3(x: string | undefined, b: number): void;
declare function foo4(x: string | undefined, b: number): void;
declare type OptionalNullableString = string | null | undefined;
declare function allowsNull(val?: OptionalNullableString): void;
declare function removeUndefinedButNotFalse(x?: boolean): false | undefined;
declare const cond: boolean;
declare function removeNothing(y?: boolean | undefined): boolean;


text:
import java.io.*;
import java.util.*;

class DailyTemperature
{
    public static void main(String[] args)
    {
        System.out.println("=== Daily Temperature ===");
        Solution solution = new Solution();
        int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
        System.out.println("temperatures = "+Arrays.toString(temperatures));
        System.out.println("higher = "+Arrays.toString(solution.dailyTemperatures(temperatures)));
    }
}

class Solution
{
    public int[] dailyTemperatures(int[] temperatures) {
        int[] ret = new int[temperatures.length];

        HashMap<Integer, List<Integer>> map = new HashMap<>();
        for (int t = 30; t <= 100; t++) {
            map.put(t, new ArrayList<Integer>());
        }

        for (int i = 0; i < temperatures.length; i++) {
            int t = temperatures[i];
            List<Integer> list = map.get(t);
            list.add(i);
        }

        //System.out.println("map = "+map);

        for (int i = 0; i < temperatures.length; i++) {
            int t = temperatures[i];
            for (int j = t+1; j <= 100; j++) {
                List<Integer> list = map.get(j);
                int largerIdx = findFirstLarger(list, 0, list.size()-1, i);
                if (largerIdx < 0) {
                    continue;
                }
                if (ret[i]==0 || (largerIdx - i) < ret[i]) {
                    ret[i] = largerIdx - i;
                }
            }
        }

        return ret;
    }

    public int findFirstLarger(List<Integer> list, int left, int right, int idx) {
        if(right < left) { return -1; }

        if (right - left <= 1) {
            if (list.get(left) > idx) {
                return list.get(left);
            } else if(list.get(right) > idx) {
                return list.get(right);
            } else {
                return -1;
            }
        } else {
            int mid = (left+right)/2;
            if (list.get(mid) < idx) {
                return findFirstLarger(list, mid, right, idx);
            } else {
                return findFirstLarger(list, left, mid, idx);
            }
        }
    }
}