text:
layout: bidder
title: AMX RTB
description: AMX RTB Prebid Bid Adapter
hide: true
schain_supported: true
gdpr_supported: true
usp_supported: true
coppa_supported: true
userIds: britepoolId, criteo, id5Id, identityLink, liveIntentId, netId, parrableId, pubCommonId, unifiedId, amxId
biddercode: amx
safeframes_ok: true
media_types: banner, video, native
pbjs: true
pbs: true
pbs_app_supported: true
fpd_supported: true
gvl_id: 737
---

### Bid Params

{: .table .table-bordered .table-striped }
| Name        | Scope    | Description                                                     | Example                         | Type     |
|-------------|----------|-----------------------------------------------------------------|---------------------------------|----------|
| `tagId`     | required | Tag ID                                                          | `'cHJlYmlkLm9yZw'`              | `string` |
| `testMode`  | optional | Activate 100% fill ads                                          | `true`                          | `boolean`|
| `adUnitId`  | optional | Ad Unit ID used in reporting. Will default to `bid.adUnitCode`  | `'sticky_banner'`               | `string` |

### Test Parameters

To enable 100% fill test ads, you can use the following `params`:

```javascript
{
  testMode: true,
  tagId: "cHJlYmlkLm9yZw"
}
```

This will produce a bid at $10 with a test creative.

Note that the `tagId` is case-sensitive. Do not use `cHJlYmlkLm9yZw` in production environments: this ID is for testing only.

### First Party Data

From Prebid.js >= 4.30, publishers can use the `ortb2` configuration parameter to provide First Party Data. We accept all standard OpenRTB fields for both:

- `ortb2.site`
- `ortb2.user`

Note that all fields are optional. For contextual data (e.g. categories), standard IAB taxonomies are supported. We do not support passing first party data via bid parameters.

#### Example - Setting ortb2.site and ortb2.user fields

```javascript
pbjs.setBidderConfig({
  bidders: ["amx"],
  config: {
    ortb2: {
      site: {
        keywords: "kw1,kw2",
        cat: ["IAB2"],
        sectioncat: ["IAB2-1"],
        pagecat: ["IAB2-22"],
        content: {
          context: 5
        }
      },
      user: {
        yob: 1981,
        keywords: "kw3",
      }
    }
  }
})
```


text:
package com.tiyuzazhi.app;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.tiyuzazhi.api.UserApi;
import com.tiyuzazhi.beans.User;
import com.tiyuzazhi.component.RoundedImageView;
import com.tiyuzazhi.utils.ImageLoader;
import com.tiyuzazhi.utils.TPool;
import com.tiyuzazhi.utils.ToastUtils;

/**
 * @author chris.xue
 */
public class UserInfoActivity extends Activity {
    private Handler handler;
    private int normalColor;
    private int unsetColor;

    private RoundedImageView header;
    private TextView email;
    private TextView company;
    private TextView mobile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.user_profile);
        super.onCreate(savedInstanceState);
        View back = findViewById(R.id.backButton);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        handler = new Handler(Looper.getMainLooper());
        header = (RoundedImageView) findViewById(R.id.header);
        unsetColor = Color.parseColor("#abadae");
        normalColor = Color.parseColor("#00367e");
        email = (TextView) findViewById(R.id.email);
        company = (TextView) findViewById(R.id.company);
        mobile = (TextView) findViewById(R.id.mobile);
        Button logoutButton = (Button) findViewById(R.id.logout);
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtils.show("正在退出...");
                TPool.post(new Runnable() {
                    @Override
                    public void run() {
                        boolean success = UserApi.logout();
                        if (success) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    setResult(Activity.RESULT_OK);
                                    finish();
                                }
                            });
                        } else {
                            ToastUtils.show("退出账户失败,请稍候重试");
                        }
                    }
                });
            }
        });
        init();
    }

    private void init() {
        TPool.post(new Runnable() {
            @Override
            public void run() {
                final User user = UserApi.getUserInfo();
                if (user != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(user.getEmail()) || TextUtils.equals("null", user.getEmail().toLowerCase())) {
                                email.setText("未设置");
                                email.setTextColor(unsetColor);
                            } else {
                                email.setText(user.getEmail());
                                email.setTextColor(normalColor);
                            }
                            if (TextUtils.isEmpty(user.getCompany()) || TextUtils.equals("null", user.getCompany().toLowerCase())) {
                                company.setText("未设置");
                                company.setTextColor(unsetColor);
                            } else {
                                company.setText(user.getCompany());
                                company.setTextColor(normalColor);
                            }
                            if (TextUtils.isEmpty(user.getMobile()) || TextUtils.equals("null", user.getMobile().toLowerCase())) {
                                mobile.setText("未设置");
                                mobile.setTextColor(unsetColor);
                            } else {
                                mobile.setText(user.getMobile());
                                mobile.setTextColor(normalColor);
                            }
                        }
                    });
                    ImageLoader.loadPic(user.getIconPath(), new ImageLoader.ImageLoaderCallback() {
                        @Override
                        public void finish(Bitmap image) {
                            header.setImageBitmap(image);
                        }

                        @Override
                        public void error(Exception e) {
                            Log.e("UserInfoActivity", "Load header failed", e);
                        }
                    });
                } else {
                    ToastUtils.show("未能获取到用户信息,请稍候重试");
                }
            }
        });

    }
}

redpajama_set_name: RedPajamaGithub


text:
etcdns
======

Extended Go `net` dialing with DNS caching backed by [etcd](https://github.com/coreos/etcd) a highly-available key value store.

example
=======

Service discovery using etcdns:

```Go

import (
	net "github.com/crackcomm/etcdns/net"
)

// on server & client
func init() {
	net.SetCluster([]string{"etcd.com:4001"})
}

func server() {
	go net.Register("secret.service", []string{"10.0.0.1:5051"}) // register service in etcd
	http.ListenAndServe("10.0.0.1:5051", nil)                 // start listening for connections
}

func client() {
	conn, err := net.Dial("tcp", "secret.service")
	if err != nil {
		fmt.Printf("Error dialing secret.service")
	}
	defer conn.Close()
	// we are now connected to 10.0.0.1:5051
}
```

godoc
=====

[godoc](http://godoc.org/github.com/crackcomm/etcdns/net)


text:
var fs = require("zed/fs");
var session = require("zed/session");

module.exports = function(info) {
    var path = info.path;
    var json;
    return session.getText(path).then(function(text) {
        try {
            json = JSON.parse(text);
        } catch (e) {
            return console.error("Could not parse package.json");
        }
        return fs.listFiles();
    }).then(function(files) {
        var packageFiles = [];
        var packageRoot = path.split("/").slice(0, -1).join("/");
        files.forEach(function(path) {
            if (path.indexOf(packageRoot) === 0) {
                var filename = path.substring(packageRoot.length + 1);
                if (filename !== "package.json" && filename !== "config.json") {
                    packageFiles.push(filename);
                }
            }
        });
        json.files = packageFiles;
        return session.setText(path, JSON.stringify(json, null, 4));
    });
};


text:
require 'spec_helper'

describe ActsAsExplorable::Element do

  subject { ActsAsExplorable::Element }

  describe '.build' do
    it 'should be callable' do
      expect(subject).to respond_to(:build)
    end

    it 'should create an element' do
      expect(ActsAsExplorable::Element.build(:position, 'position:gk', Player)).to be_instance_of(ActsAsExplorable::Element::DynamicFilter)
    end
  end
end


text:
A starter kit for web development.

## Installation

    $ docker-compose up
    $ yarn

## Usage

    $ yarn run dev
    $ yarn run prod

## Features

* [Docker](https://www.docker.com)
* [Browsersync](https://browsersync.io)
* [PHP 7.3.0](https://hub.docker.com/_/php)
* [MySQL](https://hub.docker.com/_/mysql)
* [Adminer](https://hub.docker.com/_/adminer)
* [PostCSS](http://postcss.org)
* [Css Nano](https://github.com/ben-eb/cssnano)
* [ESLint](https://eslint.org)
* [Rollup](https://rollupjs.org)
* [Uglify JS 3](https://github.com/mishoo/UglifyJS2)
* [@ariiiman/s](https://github.com/ariiiman/s)


text:
package com.migibert.kheo.client;

import java.io.IOException;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import com.migibert.kheo.core.Server;

public class SshClient {

    public static String execute(Server server, String command) throws IOException {
        try (SSHClient ssh = new SSHClient();) {
            ssh.addHostKeyVerifier(new PromiscuousVerifier());
            ssh.connect(server.host, server.sshPort);
            ssh.authPassword(server.user, server.password);
            try (Session session = ssh.startSession()) {
                Command cmd = session.exec(command);
                return IOUtils.readFully(cmd.getInputStream()).toString();
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>Macro command parameters - Macros</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../styles/styles.css">

Macro command parameters

main |
Macros |
Using macros

Macro command parameters define the conditions and the way the macro command is going to be executed.

To set up the additional parameters for the macro command created complete the recording using
Ctrl-Shift-. instead of Ctrl-. and choose its parameter values using the
dialog box:

Allow screen output while executing the macro

  Setting this parameter to 0 will disable screen refreshing operations
  for the time necessary to complete the macro command execution. All
  changes made to screen content will be complete after the command execution.

Execute after FAR Manager startup

  Allows to execute the macro command immediately after FAR Manager startup.

The following conditions are possible for the active and inactive panels activating the macro command:

Panel type

[x] - execute if the panel is used by a plugin
[ ] - execute if the panel is used by FAR file list
[?] - ignore the panel type

Execute for the folders

[x] - execute if there's a folder under the cursor on the panel
[ ] - execute if there's a file under the cursor on the panel
[?] - disregard the type of an element under the cursor

Selection is present

[x] - execute if there are files or folders selected on the panel
[ ] - execute if there are no files or folders selected on the panel
[?] - ignore the file or folder selection state

Miscellaneous activation conditions:

Command line is empty

[x] - execute only if the command line is empty
[ ] - execute only if the command line is not empty
[?] - ignore the command line state

Text block is selected

[x] - execute only if there's a selected text block in the internal viewer/editor, command line or dialog input text box.
[ ] - execute if there's no selected text block
[?] - ignore the block selection state

 Notes:

* FAR Manager checks all above conditions before executing the macro command.

* There are several key combinations (particularly Enter, Esc, F1, Ctrl-F5, Ctrl-Down,
MsWheelUp and MsWheelDown with all Ctrl, Shift and Alt combinations) that cannot be
entered in shortcut assignment dialog box directly because these combinations perform
some special functions in FAR. To assign one of these key
comdinations select it from the drop-down selection box instead.

See also:

Record a macro,
Delete a macro


text:
const assert = require('assert');
const itsThisForThat = require('../lib/itsthisforthat')();

describe('itsthisforthat', () => {
  describe('init', () => {
    let defaultRequestOptions = {};

    before(() => {
      defaultRequestOptions = {
        hostname: 'itsthisforthat.com',
        port: 80,
        basePath: '/api.php'
      };
    });

    it('should have correct default request options', () => {
      assert.deepEqual(
        itsThisForThat.defaultRequestOptions,
        defaultRequestOptions,
        'default request options should have correct initial property values'
      );
    });
  });

  describe('functions', () => {
    describe('#getIdea()', () => {
      function validateIdea(idea) {
        assert.ok(idea, 'idea should not be undefined, null or empty');
        assert.ok(
          idea.this,
          'idea.this should not be undefined, null or empty'
        );
        assert.ok(
          idea.that,
          'idea.that should not be undefined, null or empty'
        );
      }

      it('should respond with valid idea object', async () => {
        try {
          let idea = await itsThisForThat.getIdea();
          validateIdea(idea);
        } catch (error) {
          assert.ifError(error);
        }
      });
    });
  });
});


text:
int
main(int argc, char* argv[])
{
	openlog("liuchang", LOG_CONS | LOG_PID | LOG_PERROR, LOG_USER) ;
       	syslog(LOG_DEBUG,"This is a debug information %m") ;
	syslog(LOG_INFO, "This is a info information %m") ;
	syslog(LOG_ERR, "This is a error information %m") ;
	syslog(LOG_CRIT, "THIS is a crit informastion %m");
	closelog();
	return 0;
}


text:
<?php

namespace IAtelier\Atelier;

use Illuminate\Database\Eloquent\Model;

class Keyword extends Model
{
    protected $fillable = ['word'];
}


text:
class CreateCalories < ActiveRecord::Migration
  def change
    create_table :calories do |t|
      t.integer :quantity

      t.timestamps
    end
  end
end


text:
/**
 * @fileoverview Left and Right sides of most math operators should not be identical
 * @author Matt Hall
 */
"use strict";

var areExpressionsEquivalent = require('../utils/ast-equality').checkEquality;

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "Left and Right sides of most math operators should not be identical",
            category: "Fill me in",
            recommended: false
        },
        fixable: null,  // or "code" or "whitespace"
        schema: [
            // fill in your schema
        ]
    },

    create: function(context) {

        // variables should be defined here

        // + and * are the only math operators ignored
        // because x + x and x * x does make sense
        var operatorsToCheck = [
            '-',
            '/',
            '%',
        ];

        var operatorErrors = {
            '-': 'x - x is always 0. This may be an error or can be reduced to just 0.',
            '/': 'x / x is always 1. This may be an error or can be reduced to just 1.',
            '%': 'x % x is always 0. This may be an error or can be reduced to just 0.'
        };

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        // any helper functions should go here or else delete this section

        function checkMathExpression(node) {
            var operator = node.operator;

            var potentialError = operatorErrors[operator];

            // check if we need to investigate this node or not
            if (!potentialError) {
                return;
            }

            if (areExpressionsEquivalent(node.left, node.right)) {
                context.report({
                    node: node,
                    message: 'Left and right hand sides of "{{ operator }}" are identical. {{ extraError }}',
                    data: {
                        operator: operator,
                        extraError: potentialError
                    }
                });
            }
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {
            'BinaryExpression': checkMathExpression
        };
    }
};


text:
mbed OS is an open-source embedded operating system designed for the "things" in the Internet of Things (IoT). mbed OS includes the features you need to develop a connected product using an ARM Cortex-M microcontroller.

mbed OS provides a platform that includes:
 - Security foundations.
 - Cloud management services.
 - Drivers for sensors, I/O devices and connectivity.

mbed OS is modular, configurable software that you can customize it to your device and to reduce memory requirements by excluding unused software.

## Release Notes

The [Release Notes](https://docs.mbed.com/docs/mbed-os-release-notes/en/latest/) detail the current release and previous versions.

## Continuous Integration Status

We run continuous integration on all of our branches and pull requests to verify the stability of mbed OS. The following are the Travis CI indicators for mbed OS.

 - Master branch [![Master Branch CI Badge](https://travis-ci.org/ARMmbed/mbed-os.svg?branch=master)](https://travis-ci.org/ARMmbed/mbed-os)
 - Latest release [![Latest Tag CI Badge](https://travis-ci.org/ARMmbed/mbed-os.svg?branch=latest)](https://travis-ci.org/ARMmbed/mbed-os/branches)

## Getting Started for Developers

You need [mbed CLI](https://github.com/ARMmbed/mbed-cli) to build mbed OS. For more details, read the [mbed OS Handbook](https://docs.mbed.com/docs/mbed-os-handbook/en/latest/).

## Getting Started for Contributors

We have a [Contributing and Publishing Guide](https://docs.mbed.com/docs/mbed-os-handbook/en/latest/cont/contributing/) in the mbed OS Handbook.


text:
#pragma once
#include <aws/sagemaker/SageMaker_EXPORTS.h>
#include <aws/sagemaker/SageMakerRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/sagemaker/model/UserSettings.h>
#include <utility>

namespace Aws
{
namespace SageMaker
{
namespace Model
{

  /**
   */
  class AWS_SAGEMAKER_API UpdateUserProfileRequest : public SageMakerRequest
  {
  public:
    UpdateUserProfileRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "UpdateUserProfile"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The domain ID.

     */
    inline const Aws::String& GetDomainId() const{ return m_domainId; }

    /**
     *
The domain ID.

     */
    inline bool DomainIdHasBeenSet() const { return m_domainIdHasBeenSet; }

    /**
     *
The domain ID.

     */
    inline void SetDomainId(const Aws::String& value) { m_domainIdHasBeenSet = true; m_domainId = value; }

    /**
     *
The domain ID.

     */
    inline void SetDomainId(Aws::String&& value) { m_domainIdHasBeenSet = true; m_domainId = std::move(value); }

    /**
     *
The domain ID.

     */
    inline void SetDomainId(const char* value) { m_domainIdHasBeenSet = true; m_domainId.assign(value); }

    /**
     *
The domain ID.

     */
    inline UpdateUserProfileRequest& WithDomainId(const Aws::String& value) { SetDomainId(value); return *this;}

    /**
     *
The domain ID.

     */
    inline UpdateUserProfileRequest& WithDomainId(Aws::String&& value) { SetDomainId(std::move(value)); return *this;}

    /**
     *
The domain ID.

     */
    inline UpdateUserProfileRequest& WithDomainId(const char* value) { SetDomainId(value); return *this;}

    /**
     *
The user profile name.

     */
    inline const Aws::String& GetUserProfileName() const{ return m_userProfileName; }

    /**
     *
The user profile name.

     */
    inline bool UserProfileNameHasBeenSet() const { return m_userProfileNameHasBeenSet; }

    /**
     *
The user profile name.

     */
    inline void SetUserProfileName(const Aws::String& value) { m_userProfileNameHasBeenSet = true; m_userProfileName = value; }

    /**
     *
The user profile name.

     */
    inline void SetUserProfileName(Aws::String&& value) { m_userProfileNameHasBeenSet = true; m_userProfileName = std::move(value); }

    /**
     *
The user profile name.

     */
    inline void SetUserProfileName(const char* value) { m_userProfileNameHasBeenSet = true; m_userProfileName.assign(value); }

    /**
     *
The user profile name.

     */
    inline UpdateUserProfileRequest& WithUserProfileName(const Aws::String& value) { SetUserProfileName(value); return *this;}

    /**
     *
The user profile name.

     */
    inline UpdateUserProfileRequest& WithUserProfileName(Aws::String&& value) { SetUserProfileName(std::move(value)); return *this;}

    /**
     *
The user profile name.

     */
    inline UpdateUserProfileRequest& WithUserProfileName(const char* value) { SetUserProfileName(value); return *this;}

    /**
     *
A collection of settings.

     */
    inline const UserSettings& GetUserSettings() const{ return m_userSettings; }

    /**
     *
A collection of settings.

     */
    inline bool UserSettingsHasBeenSet() const { return m_userSettingsHasBeenSet; }

    /**
     *
A collection of settings.

     */
    inline void SetUserSettings(const UserSettings& value) { m_userSettingsHasBeenSet = true; m_userSettings = value; }

    /**
     *
A collection of settings.

     */
    inline void SetUserSettings(UserSettings&& value) { m_userSettingsHasBeenSet = true; m_userSettings = std::move(value); }

    /**
     *
A collection of settings.

     */
    inline UpdateUserProfileRequest& WithUserSettings(const UserSettings& value) { SetUserSettings(value); return *this;}

    /**
     *
A collection of settings.

     */
    inline UpdateUserProfileRequest& WithUserSettings(UserSettings&& value) { SetUserSettings(std::move(value)); return *this;}

  private:

    Aws::String m_domainId;
    bool m_domainIdHasBeenSet;

    Aws::String m_userProfileName;
    bool m_userProfileNameHasBeenSet;

    UserSettings m_userSettings;
    bool m_userSettingsHasBeenSet;
  };

} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
package mvm.rya.api.resolver.impl;

import mvm.rya.api.resolver.RyaTypeResolver;
import mvm.rya.api.resolver.RyaTypeResolverMapping;

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

/**
 * Date: 8/29/12
 * Time: 2:04 PM
 */
public class ServiceBackedRyaTypeResolverMappings {

    public List<RyaTypeResolverMapping> getResolvers() {
        ServiceLoader<RyaTypeResolver> loader = ServiceLoader.load(RyaTypeResolver.class);
        List<RyaTypeResolverMapping> resolvers = new ArrayList<RyaTypeResolverMapping>();
        for (RyaTypeResolver aLoader : loader) {
            resolvers.add(new RyaTypeResolverMapping(aLoader));
        }
        return resolvers;
    }
}


text:
<title>GGCs database: "Top 25 clusters"</title>

<?php include 'inte2.php'?>

    Enjoy a view of our most popular clusters
    (links,
    articles)

 according to the total number of visit

<?php

// connessione al database

include 'conn.php';

// leggo le statistiche

$querylink2 = "SELECT * FROM accesscount ORDER BY n_vis DESC LIMIT 25";
$res_visited = mysql_query($querylink2) or die("Query failed");

?>

Most visited pages

<?
$nvisited=1;
while ($l_visited = mysql_fetch_array($res_visited)){

echo '
';
echo '#'.$nvisited;
echo '	';

echo '';
// scrivo il nome dell'ammasso

print "".$l_visited[0]."";
// echo $l_visited[0];
// se c'e', scrivo l'altra denominazione
if ($l_visited[1])
   {
     echo ' (';
     echo $l_visited[1];
     echo ') ';
   }
echo ' ';
// il numero delle visite...
echo $l_visited[2];
print "
\n";
//print "
";
$nvisited++;
}
?>

Take a look also at the table of our most viewed papers or see the list of
	 recently updated clusters

<?php include 'coda.html' ?>


text:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:dd="http://rice.kuali.org/dd" xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.0.xsd         http://rice.kuali.org/dd         http://rice.kuali.org/dd/dd.xsd">
<!--
 Copyright 2006-2009 The Kuali Foundation

 Licensed under the Educational Community License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.opensource.org/licenses/ecl2.php

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

  <bean id="PositionObjectBenefitMaintenanceDocument" parent="PositionObjectBenefitMaintenanceDocument-parentBean"/>

  <bean id="PositionObjectBenefitMaintenanceDocument-parentBean" abstract="true" parent="MaintenanceDocumentEntry">
    <property name="businessObjectClass" value="org.kuali.kfs.module.ld.businessobject.PositionObjectBenefit"/>
    <property name="maintainableClass" value="org.kuali.kfs.sys.document.FinancialSystemMaintainable"/>
    <property name="maintainableSections">
      <list>
        <ref bean="PositionObjectBenefitMaintenanceDocument-EditPositionObjectBenefit"/>
      </list>
    </property>
    <property name="defaultExistenceChecks">
      <list>
        <bean parent="ReferenceDefinition" p:attributeName="universityFiscal" p:attributeToHighlightOnFail="universityFiscalYear"/>
        <bean parent="ReferenceDefinition" p:attributeName="chartOfAccounts" p:attributeToHighlightOnFail="chartOfAccountsCode"/>
        <bean parent="ReferenceDefinition" p:attributeName="financialObject" p:attributeToHighlightOnFail="financialObjectCode"/>
        <bean parent="ReferenceDefinition" p:attributeName="financialObjectBenefitsType" p:attributeToHighlightOnFail="financialObjectBenefitsTypeCode"/>
      </list>
    </property>
    <property name="lockingKeys">
      <list>
        <value>universityFiscalYear</value>
        <value>chartOfAccountsCode</value>
        <value>financialObjectCode</value>
        <value>financialObjectBenefitsTypeCode</value>
      </list>
    </property>

    <property name="documentTypeName" value="LOBN"/>
    <property name="documentAuthorizerClass" value="org.kuali.kfs.sys.document.authorization.FinancialSystemMaintenanceDocumentAuthorizerBase"/>
    <property name="workflowAttributes">
    	<ref bean="PositionObjectBenefitMaintenanceDocument-workflowAttributes"/>
    </property>
  </bean>

<!-- Maintenance Section Definitions -->

  <bean id="PositionObjectBenefitMaintenanceDocument-EditPositionObjectBenefit" parent="PositionObjectBenefitMaintenanceDocument-EditPositionObjectBenefit-parentBean"/>

  <bean id="PositionObjectBenefitMaintenanceDocument-EditPositionObjectBenefit-parentBean" abstract="true" parent="MaintainableSectionDefinition">
    <property name="id" value="Edit Position Object Benefit"/>
    <property name="title" value="Edit Position Object Benefit"/>
    <property name="maintainableItems">
      <list>
        <bean parent="MaintainableFieldDefinition" p:name="universityFiscalYear" p:required="true"/>
        <bean parent="MaintainableFieldDefinition" p:name="chartOfAccountsCode" p:required="true"/>
        <bean parent="MaintainableFieldDefinition" p:name="financialObjectCode" p:required="true"/>
        <bean parent="MaintainableFieldDefinition" p:name="financialObjectBenefitsTypeCode" p:required="true"/>
        <bean parent="MaintainableFieldDefinition" p:name="active" p:required="false"/>
      </list>
    </property>
  </bean>

  <!-- workflow attributes -->
  <bean id="PositionObjectBenefitMaintenanceDocument-workflowAttributes" parent="PositionObjectBenefitMaintenanceDocument-workflowAttributes-parentBean"/>

  <bean id="PositionObjectBenefitMaintenanceDocument-workflowAttributes-parentBean" class="org.kuali.rice.krad.datadictionary.WorkflowAttributes" abstract="true"/>
</beans>


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("osu!Sync")]
[assembly: AssemblyDescription("Share your beatmaps")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nw520")]
[assembly: AssemblyProduct("osu!Sync")]
[assembly: AssemblyCopyright("2019 | Open-Source")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("da8900bf-73d7-45cb-a805-3ea353a3bb2d")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]


text:
@interface GPSInstJamAnalyzer ()

@property (nonatomic, strong) GPSLogItem *          lastItem;
@property (nonatomic, strong) GPSLogItem *          lastReportItem;

@property (nonatomic, strong) TSPair *              penddingJam;
@property (nonatomic, strong) NSMutableArray *      trafficJamArr;

@property (nonatomic, strong) CTInstReportModel *   reportModel;

@end

@implementation GPSInstJamAnalyzer

- (instancetype)init {
    self = [super init];
    if (self) {
        self.trafficJamArr = [[NSMutableArray alloc] init];
        self.anaStat = eJamAnalyzeStatNone;
    }
    return self;
}

- (void)appendGPSInfo:(GPSLogItem*)item
{
    BOOL isJam = [self isJamItem:item];

    if (self.trafficJamArr.count == 0) {
        if (isJam) {
            self.penddingJam = TSPairMake(item, item, nil);
            [self.trafficJamArr addObject:item];
            self.anaStat = eJamAnalyzeStatPendding;
        }
    } else {
        [self.trafficJamArr addObject:item];
        if (isJam) {
            if ([self isJamItem:self.lastItem]) {
                self.penddingJam.second = item;
            } else {
                GPSLogItem * oneItem = self.penddingJam.second;
                CGFloat jamDist = [oneItem distanceFrom:item];
                CGFloat jamDuring = [item.timestamp timeIntervalSinceDate:oneItem.timestamp];

                if (jamDist < 100 || jamDuring < 10) {
                    self.penddingJam.second = item;
                }
            }
        } else {
            GPSLogItem * oneItem = self.penddingJam.second;
            CGFloat jamDist = [oneItem distanceFrom:item];
            CGFloat jamDuring = [item.timestamp timeIntervalSinceDate:oneItem.timestamp];

            if (jamDist > 200 && jamDuring > 30) {
                // 判断jam结束了,上报并清除jam缓存
                if (eJamAnalyzeStatConfirmed == self.anaStat) {
                    [self reportJamEnded];
                }
                [self reset];
            }
        }
    }

    self.lastItem = item;

    eJamAnalyzeStat stat = [self checkJamStat:self.penddingJam];
    if (stat == eJamAnalyzeStatConfirmed) {
        if (eJamAnalyzeStatConfirmed != self.anaStat) {
            [self reportJamStart];
        } else if (self.penddingJam.second) {
            GPSLogItem * lastReportItem = self.penddingJam.second;
            CGFloat jamDist = [lastReportItem distanceFrom:item];
            CGFloat jamDuring = [item.timestamp timeIntervalSinceDate:lastReportItem.timestamp];
            if ((jamDist > 100 && jamDuring > 60*3) || jamDist > 300 || jamDuring > 5*60) {
                [self reportJamResume];
            }
        }
    }
    self.anaStat = stat;
}

- (BOOL) isJamItem:(GPSLogItem*)item
{
    CGFloat curSpeed = ([item.speed floatValue] < 0 ? 0 : [item.speed floatValue]);
    return (curSpeed < cInsTrafficJamSpeed);
}

- (eJamAnalyzeStat) checkJamStat:(TSPair*)jamPair
{
    GPSLogItem * jamStart = jamPair.first;
    GPSLogItem * jamEnd = jamPair.second;
    CGFloat thisDuring = [jamEnd.timestamp timeIntervalSinceDate:jamStart.timestamp];

    if (thisDuring > 60*5) {
        return eJamAnalyzeStatConfirmed;
    } else if (thisDuring > 60*2) {
        return eJamAnalyzeStatMaybe;
    } else if (self.trafficJamArr.count > 0) {
        return eJamAnalyzeStatPendding;
    }
    return eJamAnalyzeStatNone;
}

- (CTInstReportModel*) modelWithStartItem:(GPSLogItem*)item
{
    CTInstReportModel * curModel = [CTInstReportModel new];
    [curModel updateWithStartItem:item];
    [curModel updateWithUserLocation:[self.lastItem coordinate]];

    return curModel;
}

- (BOOL) nearParkingLoc:(NSInteger)parkCnt
{
    if (self.lastItem) {
        ParkingRegionDetail * detail = [[AnaDbManager sharedInst] parkingDetailForCoordinate:[self.lastItem coordinate] minDist:cRegionRadiusThreshold];
        return (detail.parkingCnt < parkCnt);
    }
    return NO;
}

- (void) reportJamStart
{
    DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamStart");

    if (![self nearParkingLoc:5]) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamStart canceled");
        return;
    }

    CTInstReportModel * curModel = [self modelWithStartItem:self.penddingJam.first];
    self.reportModel = curModel;

    CTInstReportFacade * facade = [CTInstReportFacade new];
    facade.reportModel = curModel;
    [facade requestWithSuccess:^(NSDictionary * dict) {
        NSString * jamId = dict[@"jam_id"];
        curModel.jam_id = jamId;
        self.lastReportItem = self.penddingJam.first;
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamStart Success");
    } failure:^(NSError * err) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamStart Fail: %@", err);
    }];
}

- (void) reportJamResume
{
    DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamResume");

    if (![self nearParkingLoc:5]) {
        [self reportJamIgnore];
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamResume canceled");
        return;
    }

    if (nil == self.reportModel) {
        self.reportModel = [self modelWithStartItem:self.penddingJam.first];
    }
    GPSLogItem * reportItem = self.lastItem;
    [self.reportModel updateWithUserLocation:[self.lastItem coordinate]];

    CTInstReportFacade * facade = [CTInstReportFacade new];
    facade.reportModel = self.reportModel;
    [facade requestWithSuccess:^(NSDictionary * dict) {
        self.lastReportItem = reportItem;
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamResume Success");
    } failure:^(NSError * err) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamResume Fail: %@", err);
    }];
}

- (void) reportJamEnded
{
    DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded");

    if (![self nearParkingLoc:5]) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded canceled");
        [self reportJamIgnore];
        return;
    }

    TSPair * pair = self.penddingJam;
    NSArray * jamArr = [self.trafficJamArr copy];
    NSArray * waypoint = [GPSOffTimeFilter keyRouteFromGPS:jamArr autoFilter:YES];
    NSString * wayptStr = [GPSOffTimeFilter routeToString:waypoint withTimeStamp:YES];

    if (nil == self.reportModel) {
        self.reportModel = [self modelWithStartItem:pair.first];
    }
    [self.reportModel updateWithUserLocation:[self.lastItem coordinate]];
    [self.reportModel updateWithEndItem:pair.second];
    self.reportModel.waypoints = wayptStr;

    CTInstReportModel * curModel = self.reportModel;
    CTInstReportFacade * facade = [CTInstReportFacade new];
    facade.reportModel = curModel;
    facade.retryCnt = 1;
    [facade requestWithSuccess:^(NSDictionary * dict) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded Success");
    } failure:^(NSError * err) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded Fail");
    }];

    [self reset];
}

- (void) reportJamIgnore
{
    if (nil == self.reportModel.jam_id) {
        return;
    }
    DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamIgnore");

    CTInstReportModel * curModel = [CTInstReportModel new];
    curModel.jam_id = self.reportModel.jam_id;
    CTInstReportFacade * facade = [CTInstReportFacade new];
    facade.reportModel = curModel;
    facade.ignore = YES;
    [facade requestWithSuccess:^(NSDictionary * dict) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded Success");
    } failure:^(NSError * err) {
        DDLogWarn(@"&&&&&&&&&&&&&&&&&&& reportJamEnded Fail");
    }];

    [self reset];
}

- (void) reset
{
    self.penddingJam = nil;
    [self.trafficJamArr removeAllObjects];
    self.reportModel = nil;
    self.lastReportItem = nil;
}

- (void) driveEndAt:(GPSLogItem*)item
{
    // 说明程序判断驾驶停止,但是reportJamEnded并没有上报,因此丢弃
    if (self.reportModel.jam_id && self.reportModel.st_date) {
        [self reportJamIgnore];
    } else {
        [self reset];
    }
}

@end


text:
.. takumi-config documentation master file, created by
   sphinx-quickstart on Wed Apr  5 17:12:30 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

.. automodule:: takumi_config
.. autodata:: config
    :annotation:
.. autoclass:: takumi_config._config.Config
    :members:


text:
var fs = require('fs');
var generateDict = require('./dict-generator');

// 1. generate a dictionary for five
var dict = generateDict('earth');
// 2. save our dictionary to a file
var data = "var dictionary = "
    + JSON.stringify(dict);
fs.writeFileSync('dictionary.js', data);


text:
<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Test Case Management</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="icon" type="image/x-icon" href="/img/favicon.ico">

    <base href="/">
  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>


text:
package _package_;

import _SERVICE_FULL_;

import org.osgi.service.component.annotations.Component;

@Component(
	immediate = true,
	property = {
	},
	service = _SERVICE_SHORT_.class
)
public class _CLASSNAME_ implements _SERVICE_SHORT_ {

}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Test\Product\Types;

use DTS\eBaySDK\Product\Types\CompatibilityDetails;

class CompatibilityDetailsTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new CompatibilityDetails();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Product\Types\CompatibilityDetails', $this->obj);
    }

    public function testExtendsBaseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
    }
}


text:
package org.apache.beam.runners.dataflow.worker.windmill;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.beam.vendor.grpc.v1p48p1.io.grpc.stub.CallStreamObserver;
import org.apache.beam.vendor.grpc.v1p48p1.io.grpc.stub.StreamObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A {@link StreamObserver} which uses synchronization on the underlying {@link CallStreamObserver}
 * to provide thread safety.
 *
 * <p>Flow control with the underlying {@link CallStreamObserver} is handled with a {@link Phaser}
 * which waits for advancement of the phase if the {@link CallStreamObserver} is not ready. Creator
 * is expected to advance the {@link Phaser} whenever the underlying {@link CallStreamObserver}
 * becomes ready.
 */
@ThreadSafe
public final class DirectStreamObserver<T> implements StreamObserver<T> {
  private static final Logger LOG = LoggerFactory.getLogger(DirectStreamObserver.class);
  private final Phaser phaser;

  @GuardedBy("outboundObserver")
  private final CallStreamObserver<T> outboundObserver;

  private final long deadlineSeconds;

  @GuardedBy("outboundObserver")
  private boolean firstMessage = true;

  public DirectStreamObserver(
      Phaser phaser, CallStreamObserver<T> outboundObserver, long deadlineSeconds) {
    this.phaser = phaser;
    this.outboundObserver = outboundObserver;
    this.deadlineSeconds = deadlineSeconds;
  }

  @Override
  public void onNext(T value) {
    final int phase = phaser.getPhase();
    long totalSecondsWaited = 0;
    long waitSeconds = 1;
    while (true) {
      try {
        synchronized (outboundObserver) {
          // We let the first message passthrough without blocking because it is performed under the
          // StreamPool synchronized block and single message isn't going to cause memory issues due
          // to excessive buffering within grpc.
          if (firstMessage || outboundObserver.isReady()) {
            firstMessage = false;
            outboundObserver.onNext(value);
            return;
          }
        }
        // A callback has been registered to advance the phaser whenever the observer transitions to
        // is ready. Since we are waiting for a phase observed before the outboundObserver.isReady()
        // returned false, we expect it to advance after the channel has become ready.  This doesn't
        // always seem to be the case (despite documentation stating otherwise) so we poll
        // periodically and enforce an overall timeout related to the stream deadline.
        phaser.awaitAdvanceInterruptibly(phase, waitSeconds, TimeUnit.SECONDS);
        synchronized (outboundObserver) {
          outboundObserver.onNext(value);
          return;
        }
      } catch (TimeoutException e) {
        totalSecondsWaited += waitSeconds;
        if (totalSecondsWaited > deadlineSeconds) {
          LOG.error(
              "Exceeded timeout waiting for the outboundObserver to become ready meaning "
                  + "that the streamdeadline was not respected.");
          throw new RuntimeException(e);
        }
        waitSeconds = waitSeconds * 2;
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
      }
      if (totalSecondsWaited > 30) {
        LOG.info(
            "Output channel stalled for {}s, outbound thread {}.",
            totalSecondsWaited,
            Thread.currentThread().getName());
      }
    }
  }

  @Override
  public void onError(Throwable t) {
    synchronized (outboundObserver) {
      outboundObserver.onError(t);
    }
  }

  @Override
  public void onCompleted() {
    synchronized (outboundObserver) {
      outboundObserver.onCompleted();
    }
  }
}


text:
#region File Header and License
//
#endregion
using System;
using System.Linq;
using Agent.EntityFramework.Test.Entities;
using Gibraltar.Agent;
using Gibraltar.Agent.EntityFramework;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Agent.EntityFramework.Test
{
    [TestClass]
    public class QueryDataFromModel
    {
        private const string LogCategory = "Unit Tests.Query Data";

        [TestInitialize]
        public void RegisterInterceptor()
        {
            LoupeCommandInterceptor.Register();
        }

        [TestMethod]
        public void SimpleQuery()
        {
            using (var ctx = new NorthwindEntities())
            {
                var results = from c in ctx.Customers select c;

                results.Count();
            }
        }

    }
}


text:
<?php
// Saving the Custom Data
add_action('save_post', 'save_event_infos');

function save_event_infos(){
    global $post;

    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
		return $post_id;
	}else{
		$eventstartDate=$_POST["eventstartDate"];
		$eventendDate=($_POST["eventendDate"]==false ? $eventstartDate : $_POST["eventendDate"]);

    	update_post_meta($post->ID, "eventstartDate", $eventstartDate);
    	update_post_meta($post->ID, "eventendDate", $eventendDate);
    	update_post_meta($post->ID, "eventlieuId", $_POST["eventlieuId"]);
    	update_post_meta($post->ID, "sitewebEvent", $_POST["sitewebEvent"]);
    	update_post_meta($post->ID, "telephoneEvent", $_POST["telephoneEvent"]);
    	update_post_meta($post->ID, "gratuitEvent", $_POST["gratuitEvent"]);
    	update_post_meta($post->ID, "tarifsEvent", $_POST["tarifsEvent"]);
    	update_post_meta($post->ID, "horairesEvent", $_POST["horairesEvent"]);
    }
}

?>


text:
/*
 * tpTime.h - cert related time functions
 *
 */

#ifndef	_TP_TIME_H_
#define _TP_TIME_H_

#include <time.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Security/cssmtype.h>

#ifdef	__cplusplus
extern "C" {
#endif

/* lengths of time strings without trailing NULL */
#define UTC_TIME_NOSEC_LEN			11
#define UTC_TIME_STRLEN				13
#define CSSM_TIME_STRLEN			14		/* no trailing 'Z' */
#define GENERALIZED_TIME_STRLEN		15
#define LOCALIZED_UTC_TIME_STRLEN	17
#define LOCALIZED_TIME_STRLEN		19

/*
 * Given a string containing either a UTC-style or "generalized time"
 * time string, convert to a CFDateRef. Returns nonzero on
 * error.
 */
extern int timeStringToCfDate(
	const char			*str,
	unsigned			len,
	CFDateRef			*cfDate);

/*
 * Compare two times. Assumes they're both in GMT. Returns:
 * -1 if t1 <  t2
 *  0 if t1 == t2
 *  1 if t1 >  t2
 */
extern int compareTimes(
	CFDateRef 	t1,
	CFDateRef 	t2);

/*
 * Create a time string, in either UTC (2-digit) or or Generalized (4-digit)
 * year format. Caller mallocs the output string whose length is at least
 * (UTC_TIME_STRLEN+1), (GENERALIZED_TIME_STRLEN+1), or (CSSM_TIME_STRLEN+1)
 * respectively. Caller must hold tpTimeLock.
 */
typedef enum {
	TIME_UTC,
	TIME_GEN,
	TIME_CSSM
} TpTimeSpec;

void timeAtNowPlus(unsigned secFromNow,
	TpTimeSpec timeSpec,
	char *outStr);

/*
 * Convert a time string, which can be in any of three forms (UTC,
 * generalized, or CSSM_TIMESTRING) into a CSSM_TIMESTRING. Caller
 * mallocs the result, which must be at least (CSSM_TIME_STRLEN+1) bytes.
 * Returns nonzero if incoming time string is badly formed.
 */
int tpTimeToCssmTimestring(
	const char 	*inStr,			// not necessarily NULL terminated
	unsigned	inStrLen,		// not including possible NULL
	char 		*outTime);		// caller mallocs

#ifdef	__cplusplus
}
#endif

#endif	/* _TP_TIME_H_*/


text:
<?xml version="1.0" encoding="UTF-8"?>

		<item value="581" key="DIALOG_WIDTH"/>
		<item value="false" key="TOGGLE_SELECTED"/>
		<item value="423" key="DIALOG_HEIGHT"/>
		<item value="670" key="DIALOG_X_ORIGIN"/>
		<item value="234" key="DIALOG_Y_ORIGIN"/>

		<item value="com.android.ide.eclipse.adt.project.ImportProjectWizard.NewPrj" key="NewWizardSelectionPage.STORE_SELECTED_ID"/>
		<list key="NewWizardSelectionPage.STORE_EXPANDED_CATEGORIES_ID">
			<item value="com.android.ide.eclipse.wizards.category"/>
		</list>


text:
package io.grpc.xds;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.truth.Truth.assertThat;
import static io.grpc.ConnectivityState.CONNECTING;
import static io.grpc.ConnectivityState.IDLE;
import static io.grpc.ConnectivityState.READY;
import static io.grpc.ConnectivityState.SHUTDOWN;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import com.github.udpa.udpa.data.orca.v1.OrcaLoadReport;
import com.github.udpa.udpa.service.orca.v1.OpenRcaServiceGrpc;
import com.github.udpa.udpa.service.orca.v1.OrcaLoadReportRequest;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.util.Durations;
import io.grpc.Attributes;
import io.grpc.Channel;
import io.grpc.ChannelLogger;
import io.grpc.ConnectivityState;
import io.grpc.ConnectivityStateInfo;
import io.grpc.Context;
import io.grpc.Context.CancellationListener;
import io.grpc.EquivalentAddressGroup;
import io.grpc.LoadBalancer.CreateSubchannelArgs;
import io.grpc.LoadBalancer.Helper;
import io.grpc.LoadBalancer.Subchannel;
import io.grpc.LoadBalancer.SubchannelPicker;
import io.grpc.LoadBalancer.SubchannelStateListener;
import io.grpc.ManagedChannel;
import io.grpc.NameResolver;
import io.grpc.Status;
import io.grpc.SynchronizationContext;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.internal.BackoffPolicy;
import io.grpc.internal.FakeClock;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.GrpcCleanupRule;
import io.grpc.xds.OrcaOobUtil.OrcaOobReportListener;
import io.grpc.xds.OrcaOobUtil.OrcaReportingConfig;
import io.grpc.xds.OrcaOobUtil.OrcaReportingHelperWrapper;
import io.grpc.xds.OrcaOobUtil.SubchannelImpl;
import java.net.SocketAddress;
import java.text.MessageFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/**
 * Unit tests for {@link OrcaOobUtil} class.
 */
@RunWith(JUnit4.class)
public class OrcaOobUtilTest {

  private static final int NUM_SUBCHANNELS = 2;
  private static final Attributes.Key<String> SUBCHANNEL_ATTR_KEY =
      Attributes.Key.create("subchannel-attr-for-test");
  private static final OrcaReportingConfig SHORT_INTERVAL_CONFIG =
      OrcaReportingConfig.newBuilder().setReportInterval(5L, TimeUnit.NANOSECONDS).build();
  private static final OrcaReportingConfig MEDIUM_INTERVAL_CONFIG =
      OrcaReportingConfig.newBuilder().setReportInterval(543L, TimeUnit.MICROSECONDS).build();
  private static final OrcaReportingConfig LONG_INTERVAL_CONFIG =
      OrcaReportingConfig.newBuilder().setReportInterval(1232L, TimeUnit.MILLISECONDS).build();
  @Rule public final GrpcCleanupRule cleanupRule = new GrpcCleanupRule();

  @SuppressWarnings({"rawtypes", "unchecked"})
  private final List<EquivalentAddressGroup>[] eagLists = new List[NUM_SUBCHANNELS];
  private final SubchannelStateListener[] mockStateListeners =
      new SubchannelStateListener[NUM_SUBCHANNELS];
  private final ManagedChannel[] channels = new ManagedChannel[NUM_SUBCHANNELS];
  private final OpenRcaServiceImp[] orcaServiceImps = new OpenRcaServiceImp[NUM_SUBCHANNELS];
  private final SynchronizationContext syncContext = new SynchronizationContext(
      new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
          throw new AssertionError(e);
        }
      });

  private final FakeClock fakeClock = new FakeClock();
  private final Helper origHelper = mock(Helper.class, delegatesTo(new FakeHelper()));
  @Mock
  private OrcaOobReportListener mockOrcaListener0;
  @Mock
  private OrcaOobReportListener mockOrcaListener1;
  @Mock
  private OrcaOobReportListener mockOrcaListener2;
  @Mock private BackoffPolicy.Provider backoffPolicyProvider;
  @Mock private BackoffPolicy backoffPolicy1;
  @Mock private BackoffPolicy backoffPolicy2;
  private FakeSubchannel[] subchannels = new FakeSubchannel[NUM_SUBCHANNELS];
  private OrcaReportingHelperWrapper orcaHelperWrapper;
  private OrcaReportingHelperWrapper parentHelperWrapper;
  private OrcaReportingHelperWrapper childHelperWrapper;

  private static FakeSubchannel unwrap(Subchannel s) {
    return (FakeSubchannel) ((SubchannelImpl) s).delegate();
  }

  private static OrcaLoadReportRequest buildOrcaRequestFromConfig(
      OrcaReportingConfig config) {
    return OrcaLoadReportRequest.newBuilder()
        .setReportInterval(Durations.fromNanos(config.getReportIntervalNanos()))
        .build();
  }

  private static void assertLog(List<String> logs, String expectedLog) {
    assertThat(logs).containsExactly(expectedLog);
    logs.clear();
  }

  @After
  public void tearDown() {
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      if (subchannels[i] != null) {
        subchannels[i].shutdown();
      }
    }
  }

  @Test
  public void orcaReportingConfig_construct() {
    int interval = new Random().nextInt(Integer.MAX_VALUE);
    OrcaReportingConfig config =
        OrcaReportingConfig.newBuilder()
            .setReportInterval(interval, TimeUnit.MICROSECONDS)
            .build();
    assertThat(config.getReportIntervalNanos()).isEqualTo(TimeUnit.MICROSECONDS.toNanos(interval));
    String str = config.toString();
    assertThat(str).contains("reportIntervalNanos=");
    OrcaReportingConfig rebuildedConfig = config.toBuilder().build();
    assertThat(rebuildedConfig.getReportIntervalNanos())
        .isEqualTo(TimeUnit.MICROSECONDS.toNanos(interval));
  }

  @Before
  @SuppressWarnings("unchecked")
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      orcaServiceImps[i] = new OpenRcaServiceImp();
      cleanupRule.register(
          InProcessServerBuilder.forName("orca-reporting-test-" + i)
              .addService(orcaServiceImps[i])
              .directExecutor()
              .build()
              .start());
      ManagedChannel channel =
          cleanupRule.register(
              InProcessChannelBuilder.forName("orca-reporting-test-" + i).directExecutor().build());
      channels[i] = channel;
      EquivalentAddressGroup eag =
          new EquivalentAddressGroup(new FakeSocketAddress("address-" + i));
      List<EquivalentAddressGroup> eagList = Arrays.asList(eag);
      eagLists[i] = eagList;
      mockStateListeners[i] = mock(SubchannelStateListener.class);
    }

    when(backoffPolicyProvider.get()).thenReturn(backoffPolicy1, backoffPolicy2);
    when(backoffPolicy1.nextBackoffNanos()).thenReturn(11L, 21L);
    when(backoffPolicy2.nextBackoffNanos()).thenReturn(12L, 22L);

    orcaHelperWrapper =
        OrcaOobUtil.newOrcaReportingHelperWrapper(
            origHelper,
            mockOrcaListener0,
            backoffPolicyProvider,
            fakeClock.getStopwatchSupplier());
    parentHelperWrapper =
        OrcaOobUtil.newOrcaReportingHelperWrapper(
            origHelper,
            mockOrcaListener1,
            backoffPolicyProvider,
            fakeClock.getStopwatchSupplier());
    childHelperWrapper =
        OrcaOobUtil.newOrcaReportingHelperWrapper(
            parentHelperWrapper.asHelper(),
            mockOrcaListener2,
            backoffPolicyProvider,
            fakeClock.getStopwatchSupplier());
  }

  @Test
  @SuppressWarnings("unchecked")
  public void singlePolicyTypicalWorkflow() {
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    verify(origHelper, atLeast(0)).getSynchronizationContext();
    verifyNoMoreInteractions(origHelper);

    // Calling createSubchannel() on orcaHelper correctly passes augmented CreateSubchannelArgs
    // to origHelper.
    ArgumentCaptor<CreateSubchannelArgs> createArgsCaptor = ArgumentCaptor.forClass(null);
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      String subchannelAttrValue = "eag attr " + i;
      Attributes attrs =
          Attributes.newBuilder().set(SUBCHANNEL_ATTR_KEY, subchannelAttrValue).build();
      assertThat(unwrap(createSubchannel(orcaHelperWrapper.asHelper(), i, attrs)))
          .isSameInstanceAs(subchannels[i]);
      verify(origHelper, times(i + 1)).createSubchannel(createArgsCaptor.capture());
      assertThat(createArgsCaptor.getValue().getAddresses()).isEqualTo(eagLists[i]);
      assertThat(createArgsCaptor.getValue().getAttributes().get(SUBCHANNEL_ATTR_KEY))
          .isEqualTo(subchannelAttrValue);
    }

    // ORCA reporting does not start until underlying Subchannel is READY.
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      FakeSubchannel subchannel = subchannels[i];
      OpenRcaServiceImp orcaServiceImp = orcaServiceImps[i];
      SubchannelStateListener mockStateListener = mockStateListeners[i];
      InOrder inOrder = inOrder(mockStateListener);
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(IDLE));
      deliverSubchannelState(i, ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE));
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(CONNECTING));

      inOrder.verify(mockStateListener)
          .onSubchannelState(eq(ConnectivityStateInfo.forNonError(IDLE)));
      inOrder.verify(mockStateListener)
          .onSubchannelState(eq(ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE)));
      inOrder.verify(mockStateListener)
          .onSubchannelState(eq(ConnectivityStateInfo.forNonError(CONNECTING)));
      verifyNoMoreInteractions(mockStateListener);

      assertThat(subchannel.logs).isEmpty();
      assertThat(orcaServiceImp.calls).isEmpty();
      verifyNoMoreInteractions(mockOrcaListener0);
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(READY));
      verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
      assertThat(orcaServiceImp.calls).hasSize(1);
      ServerSideCall serverCall = orcaServiceImp.calls.peek();
      assertThat(serverCall.request).isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
      assertLog(subchannel.logs,
          "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

      // Simulate an ORCA service response. Registered listener will receive an ORCA report for
      // each backend.
      OrcaLoadReport report = OrcaLoadReport.getDefaultInstance();
      serverCall.responseObserver.onNext(report);
      assertLog(subchannel.logs, "DEBUG: Received an ORCA report: " + report);
      verify(mockOrcaListener0, times(i + 1)).onLoadReport(eq(report));
    }

    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      FakeSubchannel subchannel = subchannels[i];
      SubchannelStateListener mockStateListener = mockStateListeners[i];

      ServerSideCall serverCall = orcaServiceImps[i].calls.peek();
      assertThat(serverCall.cancelled).isFalse();
      verifyNoMoreInteractions(mockStateListener);

      // Shutting down the subchannel will cancel the ORCA reporting RPC.
      subchannel.shutdown();
      verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(SHUTDOWN)));
      assertThat(serverCall.cancelled).isTrue();
      assertThat(subchannel.logs).isEmpty();
      verifyNoMoreInteractions(mockOrcaListener0);
    }

    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      assertThat(orcaServiceImps[i].calls).hasSize(1);
    }

    verifyZeroInteractions(backoffPolicyProvider);
  }

  @Test
  public void twoLevelPoliciesTypicalWorkflow() {
    setOrcaReportConfig(childHelperWrapper, SHORT_INTERVAL_CONFIG);
    setOrcaReportConfig(parentHelperWrapper, SHORT_INTERVAL_CONFIG);
    verify(origHelper, atLeast(0)).getSynchronizationContext();
    verifyNoMoreInteractions(origHelper);

    // Calling createSubchannel() on child helper correctly passes augmented CreateSubchannelArgs
    // to origHelper.
    ArgumentCaptor<CreateSubchannelArgs> createArgsCaptor = ArgumentCaptor.forClass(null);
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      String subchannelAttrValue = "eag attr " + i;
      Attributes attrs =
          Attributes.newBuilder().set(SUBCHANNEL_ATTR_KEY, subchannelAttrValue).build();
      assertThat(unwrap(createSubchannel(childHelperWrapper.asHelper(), i, attrs)))
          .isSameInstanceAs(subchannels[i]);
      verify(origHelper, times(i + 1)).createSubchannel(createArgsCaptor.capture());
      assertThat(createArgsCaptor.getValue().getAddresses()).isEqualTo(eagLists[i]);
      assertThat(createArgsCaptor.getValue().getAttributes().get(SUBCHANNEL_ATTR_KEY))
          .isEqualTo(subchannelAttrValue);
    }

    // ORCA reporting does not start until underlying Subchannel is READY.
    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      FakeSubchannel subchannel = subchannels[i];
      OpenRcaServiceImp orcaServiceImp = orcaServiceImps[i];
      SubchannelStateListener mockStateListener = mockStateListeners[i];
      InOrder inOrder = inOrder(mockStateListener);
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(IDLE));
      deliverSubchannelState(i, ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE));
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(CONNECTING));

      inOrder
          .verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(IDLE)));
      inOrder
          .verify(mockStateListener)
          .onSubchannelState(eq(ConnectivityStateInfo.forTransientFailure(Status.UNAVAILABLE)));
      inOrder
          .verify(mockStateListener)
          .onSubchannelState(eq(ConnectivityStateInfo.forNonError(CONNECTING)));
      verifyNoMoreInteractions(mockStateListener);

      assertThat(subchannel.logs).isEmpty();
      assertThat(orcaServiceImp.calls).isEmpty();
      verifyNoMoreInteractions(mockOrcaListener1);
      verifyNoMoreInteractions(mockOrcaListener2);
      deliverSubchannelState(i, ConnectivityStateInfo.forNonError(READY));
      verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
      assertThat(orcaServiceImp.calls).hasSize(1);
      ServerSideCall serverCall = orcaServiceImp.calls.peek();
      assertThat(serverCall.request).isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
      assertLog(subchannel.logs,
          "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

      // Simulate an ORCA service response. Registered listener will receive an ORCA report for
      // each backend.
      OrcaLoadReport report = OrcaLoadReport.getDefaultInstance();
      serverCall.responseObserver.onNext(report);
      assertLog(subchannel.logs, "DEBUG: Received an ORCA report: " + report);
      verify(mockOrcaListener1, times(i + 1)).onLoadReport(eq(report));
      verify(mockOrcaListener2, times(i + 1)).onLoadReport(eq(report));
    }

    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      FakeSubchannel subchannel = subchannels[i];
      SubchannelStateListener mockStateListener = mockStateListeners[i];

      ServerSideCall serverCall = orcaServiceImps[i].calls.peek();
      assertThat(serverCall.cancelled).isFalse();
      verifyNoMoreInteractions(mockStateListener);

      // Shutting down the subchannel will cancel the ORCA reporting RPC.
      subchannel.shutdown();
      verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(SHUTDOWN)));
      assertThat(serverCall.cancelled).isTrue();
      assertThat(subchannel.logs).isEmpty();
      verifyNoMoreInteractions(mockOrcaListener1, mockOrcaListener2);
    }

    for (int i = 0; i < NUM_SUBCHANNELS; i++) {
      assertThat(orcaServiceImps[i].calls).hasSize(1);
    }

    verifyZeroInteractions(backoffPolicyProvider);
  }

  @Test
  @SuppressWarnings("unchecked")
  public void orcReportingDisabledWhenServiceNotImplemented() {
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    FakeSubchannel subchannel = subchannels[0];
    OpenRcaServiceImp orcaServiceImp = orcaServiceImps[0];
    SubchannelStateListener mockStateListener = mockStateListeners[0];
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
    assertThat(orcaServiceImp.calls).hasSize(1);

    ServerSideCall serverCall = orcaServiceImp.calls.poll();
    assertThat(serverCall.request).isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
    subchannel.logs.clear();
    serverCall.responseObserver.onError(Status.UNIMPLEMENTED.asException());
    assertLog(subchannel.logs,
        "ERROR: OpenRcaService disabled: " + Status.UNIMPLEMENTED);
    verifyNoMoreInteractions(mockOrcaListener0);

    // Re-connecting on Subchannel will reset the "disabled" flag and restart ORCA reporting.
    assertThat(orcaServiceImp.calls).hasSize(0);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(IDLE));
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    assertLog(subchannel.logs,
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());
    assertThat(orcaServiceImp.calls).hasSize(1);
    serverCall = orcaServiceImp.calls.poll();
    OrcaLoadReport report = OrcaLoadReport.getDefaultInstance();
    serverCall.responseObserver.onNext(report);
    assertLog(subchannel.logs, "DEBUG: Received an ORCA report: " + report);
    verify(mockOrcaListener0).onLoadReport(eq(report));

    verifyZeroInteractions(backoffPolicyProvider);
  }

  @Test
  public void orcaReportingStreamClosedAndRetried() {
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    FakeSubchannel subchannel = subchannels[0];
    OpenRcaServiceImp orcaServiceImp = orcaServiceImps[0];
    SubchannelStateListener mockStateListener = mockStateListeners[0];
    InOrder inOrder = inOrder(mockStateListener, mockOrcaListener0, backoffPolicyProvider,
        backoffPolicy1, backoffPolicy2);

    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    inOrder
        .verify(mockStateListener).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
    assertLog(subchannel.logs,
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

    // Server closes the ORCA reporting RPC without any response, will start backoff
    // sequence 1 (11ns).
    orcaServiceImp.calls.poll().responseObserver.onCompleted();
    assertLog(subchannel.logs,
        "DEBUG: ORCA reporting stream closed with " + Status.OK + ", backoff in 11" + " ns");
    inOrder.verify(backoffPolicyProvider).get();
    inOrder.verify(backoffPolicy1).nextBackoffNanos();
    verifyRetryAfterNanos(inOrder, orcaServiceImp, 11);
    assertLog(subchannel.logs,
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

    // Server closes the ORCA reporting RPC with an error, will continue backoff sequence 1 (21ns).
    orcaServiceImp.calls.poll().responseObserver.onError(Status.UNAVAILABLE.asException());
    assertLog(subchannel.logs,
        "DEBUG: ORCA reporting stream closed with " + Status.UNAVAILABLE + ", backoff in 21"
            + " ns");
    inOrder.verify(backoffPolicy1).nextBackoffNanos();
    verifyRetryAfterNanos(inOrder, orcaServiceImp, 21);
    assertLog(subchannel.logs,
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

    // Server responds normally.
    OrcaLoadReport report = OrcaLoadReport.getDefaultInstance();
    orcaServiceImp.calls.peek().responseObserver.onNext(report);
    assertLog(subchannel.logs, "DEBUG: Received an ORCA report: " + report);
    inOrder.verify(mockOrcaListener0).onLoadReport(eq(report));

    // Server closes the ORCA reporting RPC after a response, will restart immediately.
    orcaServiceImp.calls.poll().responseObserver.onCompleted();
    assertThat(subchannel.logs).containsExactly(
        "DEBUG: ORCA reporting stream closed with " + Status.OK + ", backoff in 0" + " ns",
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());
    subchannel.logs.clear();

    // Backoff policy is set to sequence 2 in previous retry.
    // Server closes the ORCA reporting RPC with an error, will start backoff sequence 2 (12ns).
    orcaServiceImp.calls.poll().responseObserver.onError(Status.UNAVAILABLE.asException());
    assertLog(subchannel.logs,
        "DEBUG: ORCA reporting stream closed with " + Status.UNAVAILABLE + ", backoff in 12"
            + " ns");
    inOrder.verify(backoffPolicyProvider).get();
    inOrder.verify(backoffPolicy2).nextBackoffNanos();
    verifyRetryAfterNanos(inOrder, orcaServiceImp, 12);
    assertLog(subchannel.logs,
        "DEBUG: Starting ORCA reporting for " + subchannel.getAllAddresses());

    verifyNoMoreInteractions(mockStateListener, mockOrcaListener0, backoffPolicyProvider,
        backoffPolicy1, backoffPolicy2);
  }

  @Test
  public void reportingNotStartedUntilConfigured() {
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0])
        .onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));

    assertThat(orcaServiceImps[0].calls).isEmpty();
    assertThat(subchannels[0].logs).isEmpty();
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.peek().request)
        .isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
  }

  @Test
  public void updateReportingIntervalBeforeCreatingSubchannel() {
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));

    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.poll().request)
        .isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
  }

  @Test
  public void updateReportingIntervalBeforeSubchannelReady() {
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));

    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.poll().request)
        .isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
  }

  @Test
  public void updateReportingIntervalWhenRpcActive() {
    // Sets report interval before creating a Subchannel, reporting starts right after suchannel
    // state becomes READY.
    setOrcaReportConfig(orcaHelperWrapper, MEDIUM_INTERVAL_CONFIG);
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));

    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.peek().request)
        .isEqualTo(buildOrcaRequestFromConfig(MEDIUM_INTERVAL_CONFIG));

    // Make reporting less frequent.
    setOrcaReportConfig(orcaHelperWrapper, LONG_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls.poll().cancelled).isTrue();
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.peek().request)
        .isEqualTo(buildOrcaRequestFromConfig(LONG_INTERVAL_CONFIG));

    // Configuring with the same report interval again does not restart ORCA RPC.
    setOrcaReportConfig(orcaHelperWrapper, LONG_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls.peek().cancelled).isFalse();
    assertThat(subchannels[0].logs).isEmpty();

    // Make reporting more frequent.
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls.poll().cancelled).isTrue();
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.poll().request)
        .isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));
  }

  @Test
  public void updateReportingIntervalWhenRpcPendingRetry() {
    createSubchannel(orcaHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    setOrcaReportConfig(orcaHelperWrapper, SHORT_INTERVAL_CONFIG);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));

    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.peek().request)
        .isEqualTo(buildOrcaRequestFromConfig(SHORT_INTERVAL_CONFIG));

    // Server closes the RPC without response, client will retry with backoff.
    assertThat(fakeClock.getPendingTasks()).isEmpty();
    orcaServiceImps[0].calls.poll().responseObserver.onCompleted();
    assertLog(subchannels[0].logs,
        "DEBUG: ORCA reporting stream closed with " + Status.OK + ", backoff in 11"
            + " ns");
    assertThat(fakeClock.getPendingTasks()).hasSize(1);
    assertThat(orcaServiceImps[0].calls).isEmpty();

    // Make reporting less frequent.
    setOrcaReportConfig(orcaHelperWrapper, LONG_INTERVAL_CONFIG);
    // Retry task will be canceled and restarts new RPC immediately.
    assertThat(fakeClock.getPendingTasks()).isEmpty();
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    assertThat(orcaServiceImps[0].calls.peek().request)
        .isEqualTo(buildOrcaRequestFromConfig(LONG_INTERVAL_CONFIG));
  }

  @Test
  public void policiesReceiveSameReportIndependently() {
    createSubchannel(childHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));

    // No helper sets ORCA reporting interval, so load reporting is not started.
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
    assertThat(orcaServiceImps[0].calls).isEmpty();
    assertThat(subchannels[0].logs).isEmpty();

    // Parent helper requests ORCA reports with a certain interval, load reporting starts.
    setOrcaReportConfig(parentHelperWrapper, SHORT_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());

    OrcaLoadReport report = OrcaLoadReport.getDefaultInstance();
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    orcaServiceImps[0].calls.peek().responseObserver.onNext(report);
    assertLog(subchannels[0].logs, "DEBUG: Received an ORCA report: " + report);
    // Only parent helper's listener receives the report.
    ArgumentCaptor<OrcaLoadReport> parentReportCaptor = ArgumentCaptor.forClass(null);
    verify(mockOrcaListener1).onLoadReport(parentReportCaptor.capture());
    assertThat(parentReportCaptor.getValue()).isEqualTo(report);
    verifyNoMoreInteractions(mockOrcaListener2);

    // Now child helper also wants to receive reports.
    setOrcaReportConfig(childHelperWrapper, SHORT_INTERVAL_CONFIG);
    orcaServiceImps[0].calls.peek().responseObserver.onNext(report);
    assertLog(subchannels[0].logs, "DEBUG: Received an ORCA report: " + report);
    // Both helper receives the same report instance.
    ArgumentCaptor<OrcaLoadReport> childReportCaptor = ArgumentCaptor.forClass(null);
    verify(mockOrcaListener1, times(2))
        .onLoadReport(parentReportCaptor.capture());
    verify(mockOrcaListener2)
        .onLoadReport(childReportCaptor.capture());
    assertThat(childReportCaptor.getValue()).isSameInstanceAs(parentReportCaptor.getValue());
  }

  @Test
  public void reportWithMostFrequentIntervalRequested() {
    setOrcaReportConfig(parentHelperWrapper, SHORT_INTERVAL_CONFIG);
    setOrcaReportConfig(childHelperWrapper, LONG_INTERVAL_CONFIG);
    createSubchannel(childHelperWrapper.asHelper(), 0, Attributes.EMPTY);
    deliverSubchannelState(0, ConnectivityStateInfo.forNonError(READY));
    verify(mockStateListeners[0]).onSubchannelState(eq(ConnectivityStateInfo.forNonError(READY)));
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());

    // The real report interval to be requested is the minimum of intervals requested by helpers.
    assertThat(Durations.toNanos(orcaServiceImps[0].calls.peek().request.getReportInterval()))
        .isEqualTo(SHORT_INTERVAL_CONFIG.getReportIntervalNanos());

    // Child helper wants reporting to be more frequent than its current setting while it is still
    // less frequent than parent helper. Nothing should happen on existing RPC.
    setOrcaReportConfig(childHelperWrapper, MEDIUM_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls.peek().cancelled).isFalse();
    assertThat(subchannels[0].logs).isEmpty();

    // Parent helper wants reporting to be less frequent.
    setOrcaReportConfig(parentHelperWrapper, MEDIUM_INTERVAL_CONFIG);
    assertThat(orcaServiceImps[0].calls.poll().cancelled).isTrue();
    assertThat(orcaServiceImps[0].calls).hasSize(1);
    assertLog(subchannels[0].logs,
        "DEBUG: Starting ORCA reporting for " + subchannels[0].getAllAddresses());
    // ORCA reporting RPC restarts and the the real report interval is adjusted.
    assertThat(Durations.toNanos(orcaServiceImps[0].calls.poll().request.getReportInterval()))
        .isEqualTo(MEDIUM_INTERVAL_CONFIG.getReportIntervalNanos());
  }

  private void verifyRetryAfterNanos(InOrder inOrder, OpenRcaServiceImp orcaServiceImp,
      long nanos) {
    assertThat(fakeClock.getPendingTasks()).hasSize(1);
    assertThat(orcaServiceImp.calls).isEmpty();
    fakeClock.forwardNanos(nanos - 1);
    assertThat(orcaServiceImp.calls).isEmpty();
    inOrder.verifyNoMoreInteractions();
    fakeClock.forwardNanos(1);
    assertThat(orcaServiceImp.calls).hasSize(1);
    assertThat(fakeClock.getPendingTasks()).isEmpty();
  }

  private void deliverSubchannelState(final int index, final ConnectivityStateInfo newState) {
    syncContext.execute(
        new Runnable() {
          @Override
          public void run() {
            subchannels[index].stateListener.onSubchannelState(newState);
          }
        });
  }

  private Subchannel createSubchannel(final Helper helper, final int index,
      final Attributes attrs) {
    final AtomicReference<Subchannel> newSubchannel = new AtomicReference<>();
    syncContext.execute(
        new Runnable() {
          @Override
          public void run() {
            Subchannel s =
                helper.createSubchannel(
                    CreateSubchannelArgs.newBuilder()
                        .setAddresses(eagLists[index])
                        .setAttributes(attrs)
                        .build());
            s.start(mockStateListeners[index]);
            newSubchannel.set(s);
          }
        });
    return newSubchannel.get();
  }

  private void setOrcaReportConfig(
      final OrcaReportingHelperWrapper helperWrapper, final OrcaReportingConfig config) {
    syncContext.execute(new Runnable() {
      @Override
      public void run() {
        helperWrapper.setReportingConfig(config);
      }
    });
  }

  private static final class OpenRcaServiceImp extends OpenRcaServiceGrpc.OpenRcaServiceImplBase {
    final Queue<ServerSideCall> calls = new ArrayDeque<>();

    @Override
    public void streamCoreMetrics(
        OrcaLoadReportRequest request, StreamObserver<OrcaLoadReport> responseObserver) {
      final ServerSideCall call = new ServerSideCall(request, responseObserver);
      Context.current()
          .addListener(
              new CancellationListener() {
                @Override
                public void cancelled(Context ctx) {
                  call.cancelled = true;
                }
              },
              MoreExecutors.directExecutor());
      calls.add(call);
    }
  }

  private static final class ServerSideCall {
    final OrcaLoadReportRequest request;
    final StreamObserver<OrcaLoadReport> responseObserver;
    boolean cancelled;

    ServerSideCall(OrcaLoadReportRequest request, StreamObserver<OrcaLoadReport> responseObserver) {
      this.request = request;
      this.responseObserver = responseObserver;
    }
  }

  private static final class FakeSocketAddress extends SocketAddress {
    final String name;

    FakeSocketAddress(String name) {
      this.name = name;
    }

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

  private final class FakeSubchannel extends Subchannel {
    final List<EquivalentAddressGroup> eagList;
    final Attributes attrs;
    final Channel channel;
    final List<String> logs = new ArrayList<>();
    final int index;
    SubchannelStateListener stateListener;
    private final ChannelLogger logger =
        new ChannelLogger() {
          @Override
          public void log(ChannelLogLevel level, String msg) {
            logs.add(level + ": " + msg);
          }

          @Override
          public void log(ChannelLogLevel level, String template, Object... args) {
            log(level, MessageFormat.format(template, args));
          }
        };

    FakeSubchannel(int index, CreateSubchannelArgs args, Channel channel) {
      this.index = index;
      this.eagList = args.getAddresses();
      this.attrs = args.getAttributes();
      this.channel = checkNotNull(channel);
    }

    @Override
    public void start(SubchannelStateListener listener) {
      checkState(this.stateListener == null);
      this.stateListener = listener;
    }

    @Override
    public void shutdown() {
      deliverSubchannelState(index, ConnectivityStateInfo.forNonError(SHUTDOWN));
    }

    @Override
    public void requestConnection() {
      throw new AssertionError("Should not be called");
    }

    @Override
    public List<EquivalentAddressGroup> getAllAddresses() {
      return eagList;
    }

    @Override
    public Attributes getAttributes() {
      return attrs;
    }

    @Override
    public Channel asChannel() {
      return channel;
    }

    @Override
    public ChannelLogger getChannelLogger() {
      return logger;
    }
  }

  private final class FakeHelper extends Helper {
    @Override
    public Subchannel createSubchannel(CreateSubchannelArgs args) {
      int index = -1;
      for (int i = 0; i < NUM_SUBCHANNELS; i++) {
        if (eagLists[i].equals(args.getAddresses())) {
          index = i;
          break;
        }
      }
      checkState(index >= 0, "addrs " + args.getAddresses() + " not found");
      FakeSubchannel subchannel = new FakeSubchannel(index, args, channels[index]);
      checkState(subchannels[index] == null, "subchannels[" + index + "] already created");
      subchannels[index] = subchannel;
      return subchannel;
    }

    @Override
    public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) {
      throw new AssertionError("Should not be called");
    }

    @Override
    public SynchronizationContext getSynchronizationContext() {
      return syncContext;
    }

    @Override
    public ScheduledExecutorService getScheduledExecutorService() {
      return fakeClock.getScheduledExecutorService();
    }

    @Deprecated
    @Override
    public NameResolver.Factory getNameResolverFactory() {
      throw new AssertionError("Should not be called");
    }

    @Override
    public String getAuthority() {
      throw new AssertionError("Should not be called");
    }

    @Override
    public ManagedChannel createOobChannel(EquivalentAddressGroup eag, String authority) {
      throw new AssertionError("Should not be called");
    }
  }
}


text:
using System;
using System.Collections;

using Org.BouncyCastle.Bcpg.Sig;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Bcpg.OpenPgp
{
	/// <remarks>Container for a list of signature subpackets.</remarks>
    public class PgpSignatureSubpacketVector
    {
        private readonly SignatureSubpacket[] packets;

		internal PgpSignatureSubpacketVector(
            SignatureSubpacket[] packets)
        {
            this.packets = packets;
        }

		public SignatureSubpacket GetSubpacket(
            SignatureSubpacketTag type)
        {
            for (int i = 0; i != packets.Length; i++)
            {
                if (packets[i].SubpacketType == type)
                {
                    return packets[i];
                }
            }

			return null;
        }

		/**
		 * Return true if a particular subpacket type exists.
		 *
		 * @param type type to look for.
		 * @return true if present, false otherwise.
		 */
		public bool HasSubpacket(
			SignatureSubpacketTag type)
		{
			return GetSubpacket(type) != null;
		}

		/**
		 * Return all signature subpackets of the passed in type.
		 * @param type subpacket type code
		 * @return an array of zero or more matching subpackets.
		 */
		public SignatureSubpacket[] GetSubpackets(
			SignatureSubpacketTag type)
		{
            int count = 0;
            for (int i = 0; i < packets.Length; ++i)
            {
                if (packets[i].SubpacketType == type)
                {
                    ++count;
                }
            }

            SignatureSubpacket[] result = new SignatureSubpacket[count];

            int pos = 0;
            for (int i = 0; i < packets.Length; ++i)
            {
                if (packets[i].SubpacketType == type)
                {
                    result[pos++] = packets[i];
                }
            }

            return result;
        }

        public NotationData[] GetNotationDataOccurences()
		{
			SignatureSubpacket[] notations = GetSubpackets(SignatureSubpacketTag.NotationData);
			NotationData[] vals = new NotationData[notations.Length];

			for (int i = 0; i < notations.Length; i++)
			{
				vals[i] = (NotationData) notations[i];
			}

			return vals;
		}

		public long GetIssuerKeyId()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.IssuerKeyId);

            return p == null ? 0 : ((IssuerKeyId) p).KeyId;
        }

		public bool HasSignatureCreationTime()
		{
			return GetSubpacket(SignatureSubpacketTag.CreationTime) != null;
		}

		public DateTime GetSignatureCreationTime()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.CreationTime);

            if (p == null)
            {
                throw new PgpException("SignatureCreationTime not available");
            }

            return ((SignatureCreationTime)p).GetTime();
        }

		/// <summary>
		/// Return the number of seconds a signature is valid for after its creation date.
		/// A value of zero means the signature never expires.
		/// </summary>
		/// <returns>Seconds a signature is valid for.</returns>
        public long GetSignatureExpirationTime()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.ExpireTime);

			return p == null ? 0 : ((SignatureExpirationTime) p).Time;
        }

		/// <summary>
		/// Return the number of seconds a key is valid for after its creation date.
		/// A value of zero means the key never expires.
		/// </summary>
		/// <returns>Seconds a signature is valid for.</returns>
        public long GetKeyExpirationTime()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.KeyExpireTime);

			return p == null ? 0 : ((KeyExpirationTime) p).Time;
        }

		public int[] GetPreferredHashAlgorithms()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredHashAlgorithms);

			return p == null ? null : ((PreferredAlgorithms) p).GetPreferences();
        }

		public int[] GetPreferredSymmetricAlgorithms()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredSymmetricAlgorithms);

            return p == null ? null : ((PreferredAlgorithms) p).GetPreferences();
        }

		public int[] GetPreferredCompressionAlgorithms()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredCompressionAlgorithms);

            return p == null ? null : ((PreferredAlgorithms) p).GetPreferences();
        }

		public int GetKeyFlags()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.KeyFlags);

            return p == null ? 0 : ((KeyFlags) p).Flags;
        }

		public string GetSignerUserId()
        {
            SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.SignerUserId);

			return p == null ? null : ((SignerUserId) p).GetId();
        }

		public bool IsPrimaryUserId()
		{
			PrimaryUserId primaryId = (PrimaryUserId)
				this.GetSubpacket(SignatureSubpacketTag.PrimaryUserId);

			if (primaryId != null)
			{
				return primaryId.IsPrimaryUserId();
			}

			return false;
		}

		public SignatureSubpacketTag[] GetCriticalTags()
        {
            int count = 0;
            for (int i = 0; i != packets.Length; i++)
            {
                if (packets[i].IsCritical())
                {
                    count++;
                }
            }

			SignatureSubpacketTag[] list = new SignatureSubpacketTag[count];

			count = 0;

			for (int i = 0; i != packets.Length; i++)
            {
                if (packets[i].IsCritical())
                {
                    list[count++] = packets[i].SubpacketType;
                }
            }

			return list;
        }

		[Obsolete("Use 'Count' property instead")]
		public int Size
		{
			get { return packets.Length; }
		}

		/// <summary>Return the number of packets this vector contains.</summary>
		public int Count
		{
			get { return packets.Length; }
		}

		internal SignatureSubpacket[] ToSubpacketArray()
        {
            return packets;
        }
    }
}


text:
<!DOCTYPE html>

    <title>Giesserei - 404</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">

Uups! Die Seite existiert nicht.


text:
FROM mhart/alpine-node:0.12

MAINTAINER Maik Hummel <m@ikhummel.com>

WORKDIR /opt/youtransfer/

ENV YOUTRANSFER_VERSION=1.0.6

RUN apk add --no-cache git && \
    npm i -g youtransfer@${YOUTRANSFER_VERSION} && \
    youtransfer init && \
    npm i

VOLUME /opt/youtransfer/uploads
VOLUME /opt/youtransfer/config

CMD npm run dockerized

EXPOSE 5000


text:
% LBFGSB  Call the nonlinear bound-constrained solver that uses
%         limited-memory BFGS quasi-Newton updates.
%
%   The basic function call is
%
%     LBFGSB(x0,lb,ub,objfunc,gradfunc)
%
%   The first input argument x0 is either a matrix or a cell array of
%   matrices. It declares the starting point for the solver.
%
%   The second and third input arguments lb and ub must be of the exact same
%   structure as x0. They declare the lower and upper bounds on the
%   variables, respectively. Set an entry to Inf to declare no bound.
%
%   The next two input arguments must be the names of MATLAB routines
%   (M-files):
%
%     objfunc         Calculates the objective function at the current
%                     point. The routine must accept as many inputs as cell
%                     entry in x0 (or one input if x0 is a matrix). The
%                     output must be a scalar representing the objective
%                     evaluated at the current point.
%
%     gradfunc        Computes the gradient of the objective at the current
%                     point. The input is the same as objfunc, but it must
%                     return as many outputs as there are inputs, and each
%                     of the outputs have the same matrix structure as its
%                     corresponding input.
%
%   Optionally, one may choose to pass additional auxiliary data to the
%   MATLAB callback routines listed above through the function call
%   LBFGSB(...,auxdata). If auxdata is the empty matrix, no extra
%   information is passed. It is important to observe that the auxiliary
%   data MAY NOT CHANGE through the course of the L-BFGS optimization! The
%   auxiliary data keep the same values as they possessed in the initial
%   call. If you need variables that change over time, you may want to
%   consider global variables (type HELP GLOBAL).
%
%   LBFGSB(...,auxdata,iterfunc) specifies an additional callback routine
%   which is called once per algorithm iteration. The callback routine must
%   take the form ITERFUNC(T,F,X1,X2,...,AUXDATA). T is the current
%   iteration of the algorithm. F is the current value of the objective. The
%   inputs X1, X2,... are exactly the same as the ones passed to objfunc and
%   gradfunc. Finally, extra information may be passed through the input
%   AUXDATA. No outputs are expected from iterfunc. If iterfunc is the empty
%   string, no routine is called.
%
%   These inputs may be followed by parameter/value pairs to modify the
%   default algorithm options. The algorithm option 'maxiter' sets the
%   maximum number of iterations. The rest of the options 'm', 'factr' and
%   'pgtol' are described in the L-BFGS-B documentation. Note that in this
%   implementation we divide factr by the machine precision, so that the
%   convergence condition is satisfied when it is less than factr, not less
%   than factr times the machine precision.