text:
const child_process = require('child_process');
const EventEmitter = require('events');
const {Logger, isObject} = require('../../utils');
const ProcessListener = require('../../runner/process-listener.js');

let prevIndex = 0;

class ChildProcess extends EventEmitter {
  static get defaultStartDelay() {
    return 10;
  }

  static get prevIndex() {
    return prevIndex;
  }

  static set prevIndex(val) {
    prevIndex = val;
  }

  constructor(environment, index, env_output, settings, args) {
    super();

    this.settings = settings;
    this.env_output = env_output || [];
    this.mainModule = process.mainModule.filename;
    this.index = index;
    this.itemKey = this.getChildProcessEnvKey(environment);
    this.startDelay = settings.parallel_process_delay || ChildProcess.defaultStartDelay;
    this.environment = environment;
    this.child = null;
    this.globalExitCode = 0;
    this.env_label = '';
    this.args = args || [];
  }

  setLabel(label) {
    this.env_itemKey = label;
    this.env_label = this.settings.disable_colors ? ` ${label} ` : Logger.colors.yellow(` ${label} `, Logger.colors.background.black);

    return this;
  }

  getChildProcessEnvKey(env) {
    return `${env}_${this.index + 1}`;
  }

  /**
   * Returns an array of cli arguments to be passed to the child process,
   * based on the args passed to the main process
   * @returns {Array}
   */
  getArgs() {
    const args = [];

    if (isObject(this.settings.test_workers)) {
      const {node_options} = this.settings.test_workers;
      if (node_options === 'auto' || node_options === 'inherit' || node_options === true) {
        args.push.apply(args, process.execArgv);
      } else if (Array.isArray(node_options)) {
        args.push.apply(args, node_options);
      }
    }

    args.push(this.mainModule);
    args.push.apply(args, this.args);
    args.push('--parallel-mode');

    return args;
  }

  writeToStdout(data) {
    data = data.toString().trim();

    let color_pair = this.availColors[this.index%4];
    let output = '';

    if (ChildProcess.prevIndex !== this.index) {
      ChildProcess.prevIndex = this.index;
      if (this.settings.live_output) {
        output += '\n';
      }
    }

    if (this.settings.output && (this.settings.detailed_output || !this.settings.silent)) {
      let childProcessLabel;
      if (this.settings.disable_colors) {
        childProcessLabel = ' ' + this.environment + ' ';
      } else {
        childProcessLabel = Logger.colors[color_pair[1]](` ${this.environment} `, Logger.colors.background[color_pair[0]]);
      }

      let lines = data.split('\n').map(line => {
        return childProcessLabel + ' ' + line + ' ';
      });

      data = lines.join('\n');
    }

    output += data;

    if (this.settings.live_output) {
      process.stdout.write(output + '\n');
    } else {
      this.env_output.push(output);
    }
  }

  run(colors, type) {
    this.availColors = colors;

    let cliArgs = this.getArgs();
    let env = {};

    Object.keys(process.env).forEach(function(key) {
      env[key] = process.env[key];
    });

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        env.__NIGHTWATCH_PARALLEL_MODE = '1';
        env.__NIGHTWATCH_ENV = this.environment;
        env.__NIGHTWATCH_ENV_KEY = this.itemKey;
        env.__NIGHTWATCH_ENV_LABEL = this.env_itemKey;
        env.__NIGHTWATCH_PARALLEL_TYPE = type;

        this.child = child_process.spawn(process.execPath, cliArgs, {
          cwd: process.cwd(),
          encoding: 'utf8',
          env: env,
          stdio: [null, null, null, 'ipc']
        });

        Logger.info('Started child process for:' + this.env_label);

        this.child.stdout.on('data', data => {
          this.writeToStdout(data);
        });

        this.child.on('message', message => {
          this.emit('message', message);
        });

        this.child.stderr.on('data', data => {
          this.writeToStdout(data);
        });

        this.processListener = new ProcessListener(this.child);

        this.child.on('exit', code => {
          code = code || this.processListener.exitCode;
          resolve(code);
        });

      }, this.index * this.startDelay);
    });
  }
}

module.exports = ChildProcess;


text:
[Piet][piet-origin] is an esoteric programming language designed by David Morgan-Mar. Its peculiarity is the lack of readability as well as the way the source code is stored.

Images. Images are the source code. The colors in the source images are the keywords found in any other programming language. And the arrangement of the pixels is the order of events in the code.

### What is libPietVM then?

libPietVM makes it possible to analyze and execute Piet *encoded* images. And one can easily embed this.
Check out the milestones to see the realized and planned features.

### Contributors
* Joshua Behrens <code@joshua-behrens.de> / [Website][contrib-website-a]

### License

> Copyright (c) 2015 Joshua Behrens
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> The Software shall **not** be used to create products or support military actions that are intended to harm any human being
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

tl;dr: Refer to the main contributors and do not harm any people

[piet-origin]: //dangermouse.net/esoteric/piet.html "The origin of Piet"
[contrib-website-a]: //joshua-behrens.de "Website of Joshua Behrens"

redpajama_set_name: RedPajamaGithub


text:
package Service;

import java.sql.ResultSet;
import java.sql.SQLException;

import DataBase.DoDataBase;
import DataBase.DoSQL;

public class ServeLogin {
	public static int messageisTrue(String username, String password) throws SQLException {
		java.sql.Connection connection = DoDataBase.getConnection();
		java.sql.Statement statement =  connection.createStatement();
		int flag=0;
		String sqlString = "select PASSWORDS from USERS where USERNAME = '" +username+ "'";
		ResultSet resultSet = DoSQL.Query(statement, sqlString) ;
		if(resultSet.next()) {
			String psw = resultSet.getString(1);
			if(password.equals(psw))
				flag = 1;  //成功登陆
			else    //密码错误
				flag = 0;
		}
		else flag=-1; //用户名不存在

		DoDataBase.releaseConnection(connection, statement, resultSet);
		return flag;
	}

	/*public static void main(String[] args) {
		// TODO Auto-generated method stub

	}*/

}


text:
package oic.simulator.serviceprovider.view.dialogs;

import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import org.oic.simulator.server.SimulatorResource.Type;

import oic.simulator.serviceprovider.utils.Constants;

public class MainPage extends WizardPage {

    private Button simpleBtn;
    private Button simpleFromRamlBtn;
    private Text   description;

    public enum Option {
        SIMPLE, SIMPLE_FROM_RAML
    }

    private Option option;

    protected MainPage() {
        super("Main Page");
    }

    @Override
    public void createControl(Composite parent) {
        setPageComplete(false);
        setTitle(Constants.MAIN_PAGE_TITLE);
        setMessage(Constants.MAIN_PAGE_MESSAGE);
        Composite compContent = new Composite(parent, SWT.NONE);
        GridLayout gridLayout = new GridLayout();
        compContent.setLayout(gridLayout);
        GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
        compContent.setLayoutData(gd);

        simpleBtn = new Button(compContent, SWT.RADIO);
        simpleBtn.setText("Simple resource");

        simpleFromRamlBtn = new Button(compContent, SWT.RADIO);
        simpleFromRamlBtn.setText("Simple resource(From RAML)");

        Label lbl = new Label(compContent, SWT.NULL);
        lbl.setText("Details:");
        gd = new GridData();
        gd.verticalIndent = 20;
        lbl.setLayoutData(gd);

        description = new Text(compContent, SWT.MULTI | SWT.READ_ONLY
                | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
        description.setBackground(compContent.getBackground());
        description.setText("[Select an option to view more details]");
        gd = new GridData(SWT.FILL, SWT.FILL, true, true);
        description.setLayoutData(gd);

        addUIListeners();

        setControl(compContent);
    }

    private void addUIListeners() {
        simpleBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                description
                        .setText("Create a simple resource by manually entering all the details given below.\n"
                                + "\t1. Basic resource details: URI, Name, Resource Type, and Interface types.\n"
                                + "\t2. Options such as Observable and Discoverable.\n"
                                + "\t3. Adding simple attributes.");
                option = Option.SIMPLE;
                getWizard().getContainer().updateButtons();
            }
        });

        simpleFromRamlBtn.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                description
                        .setText("Create a simple resource from RAML configuration file.\n"
                                + "\t1. Resource details, attributes, and other properties will be read from RAML.\n"
                                + "\t2. Supports multi-instance creation.\n"
                                + "\t3. For single instance creation, allows editing the URI and Name of the resource.");
                option = Option.SIMPLE_FROM_RAML;
                getWizard().getContainer().updateButtons();
            }
        });
    }

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

    @Override
    public IWizardPage getPreviousPage() {
        return null;
    }

    @Override
    public IWizardPage getNextPage() {
        CreateResourceWizard createWizard = (CreateResourceWizard) getWizard();
        if (simpleBtn.getSelection()) {
            return createWizard.getSimpleResourceBasicDetailsPage();
        }
        if (simpleFromRamlBtn.getSelection()) {
            LoadRamlPage page = createWizard.getLoadRamlPage();
            page.initialSetup(Type.SINGLE);
            return page;
        }
        return null;
    }

    public Option getOption() {
        return option;
    }
}


text:
<?php

namespace GitHubTest\Adapter;

use GitHub\Adapter\AdapterFactory;

class AdapterFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testAdapterNotFound()
    {
        $this->setExpectedException('\GitHub\Adapter\Exception\AdapterNotFoundException');
        AdapterFactory::factory('foo');
    }
}


text:
import sys

# Also change some very frequent words to new ortographic rules in German
# e.g. muß -> muss
word_replace_rules = {'muß':'muss', 'daß':'dass', 'Daß':'dass', '-$':' ', '-$':' ', '$':'', '$':'', '-':'' , '  ' : ' '}

for line in sys.stdin:
    line = line.replace('Das', 'das')
    # remove ähs, ähms and unks as well as hesitations (häs)
    line = line.replace('Äh', '').replace('äh', '').replace('Ähm', '').replace('ähm', '').replace('häs', '').replace('<UNK>', '').replace('<unk>', '')
    split = line.split()
    if len(split) > 1:
        if len(split[1]) > 1:
            split[1] = split[1][0].upper() + split[1][1:]
            output = ' '.join(split)
        elif len(split[1]) == 1:
            split[1] = split[1][0].upper()
            output = ' '.join(split)
        else:
            #if we have issues just pass the line unchanged
            output = line

        for replace_rule in word_replace_rules.items():
            output = output.replace(replace_rule[0], replace_rule[1])
        print(output)

    else:
        #if we have issues just pass the line unchanged
        print(line)


text:
var express = require('express');
var path 		= require('path');

module.exports = function(app){

	// serve from client/dist
	app.use(express.static(path.join(__dirname, '../../client/dist')));

};


text:
layout: post
microblog: true
audio:
photo:
date: 2010-02-14 18:00:00 -0600
guid: http://craigmcclellan.micro.blog/2010/02/15/t9154706104.html
---
I just discovered @bajaburrito's Texas Brisket burrito today.  It is now on the list of my favorite foods.  Go get one if you haven't yet.


text:
    <app-player
      [videos]="videos"
      [currentVideo]="currentVideo">
    </app-player>
    <app-video-details class="main-box"
      [currentVideo]="currentVideo">
    </app-video-details>

    <app-videos-sidebar
      [videos]="videos"
      [currentVideo]="currentVideo">
    </app-videos-sidebar>


text:
/**
 * Returns settings for plupload with default
 *
 * @param {Object} settings
 * @return {Object}
 */
function pluploadHelpersSettings(settings) {
    var defaults = {
        runtimes:            pluploadHelpersRuntimes(),
        max_file_size:       '10mb',
        multi_selection:     false,
        multipart_params:    {},
        flash_swf_url:       app.baseUrl + '/lib/plupload-2.0.0-beta/js/Moxie.swf',
        silverlight_xap_url: app.baseUrl + '/lib/plupload-2.0.0-beta/js/Moxie.xap'
    };
    return $.extend({}, defaults, settings);
}

/**
 * Define plupload runtimes relying on browser
 *
 * @return {String}
 */
function pluploadHelpersRuntimes() {
    var runtimes;
    if ($.browser.msie) {
        runtimes = 'html5,silverlight,gears,browserplus';
    } else {
        runtimes = 'html5,silverlight,flash,gears,browserplus';
    }
    return runtimes;
}


text:
<mat-form-field>
  <mat-select placeholder="Tooltip position" [formControl]="position">
    <mat-option *ngFor="let positionOption of positionOptions" [value]="positionOption">
      {{positionOption}}
    </mat-option>
  </mat-select>
</mat-form-field>

<div class="example-container" cdk-scrollable>
  <button mat-raised-button #tooltip="matTooltip"
          matTooltip="Info about the action"
          [matTooltipPosition]="position.value"
          matTooltipHideDelay="100000"
          aria-label="Button that displays a tooltip that hides when scrolled out of the container"
          class="example-button">
    Action
  </button>
</div>


text:
package org.apache.tez.dag.api.client;

import org.apache.tez.dag.api.records.DAGProtos;
import org.apache.tez.dag.app.dag.VertexState;
import org.junit.Assert;
import org.junit.Test;

public class TestVertexStatusBuilder {

  @Test
  public void testVertexStateConversion() {
    for (VertexState state : VertexState.values()) {
      DAGProtos.VertexStatusStateProto stateProto =
          VertexStatusBuilder.getProtoState(state);
      VertexStatus.State clientState =
          VertexStatus.getState(stateProto);
      Assert.assertEquals(state.name(), clientState.name());
    }
  }

}


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

package com.sun.facelets.tag;

/**
 * Representation of a Tag in the Facelet definition
 *
 * @author Jacob Hookom
 * @version $Id: Tag.java,v 1.5 2008-07-13 19:01:36 rlubke Exp $
 */
public final class Tag {
    private final TagAttributes attributes;

    private final Location location;

    private final String namespace;

    private final String localName;

    private final String qName;

    public Tag(Location location, String namespace, String localName,
            String qName, TagAttributes attributes) {
        this.location = location;
        this.namespace = namespace;
        this.localName = localName;
        this.qName = qName;
        this.attributes = attributes;
    }

    public Tag(Tag orig, TagAttributes attributes) {
        this(orig.getLocation(), orig.getNamespace(), orig.getLocalName(), orig
                .getQName(), attributes);
    }

    /**
     * All TagAttributes specified
     *
     * @return all TagAttributes specified
     */
    public TagAttributes getAttributes() {
        return attributes;
    }

    /**
     * Local name of the tag <my:tag /> would be "tag"
     *
     * @return local name of the tag
     */
    public String getLocalName() {
        return localName;
    }

    /**
     * Location of the Tag in the Facelet file
     *
     * @return location of the Tag in the Facelet file
     */
    public Location getLocation() {
        return location;
    }

    /**
     * The resolved Namespace for this tag
     *
     * @return the resolved namespace for this tag
     */
    public String getNamespace() {
        return namespace;
    }

    /**
     * Get the qualified name for this tag <my:tag /> would be "my:tag"
     *
     * @return qualified name of the tag
     */
    public String getQName() {
        return qName;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    public String toString() {
        return this.location + " <" + this.qName + ">";
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudasset.v1p7beta1.model;

/**
 * Defines a Cloud Organization `Policy` which is used to specify `Constraints` for configurations
 * of Cloud Platform resources.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Asset API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudOrgpolicyV1Policy extends com.google.api.client.json.GenericJson {

  /**
   * For boolean `Constraints`, whether to enforce the `Constraint` or not.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudOrgpolicyV1BooleanPolicy booleanPolicy;

  /**
   * The name of the `Constraint` the `Policy` is configuring, for example,
   * `constraints/serviceuser.services`. A [list of available constraints](/resource-manager/docs
   * /organization-policy/org-policy-constraints) is available. Immutable after creation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String constraint;

  /**
   * An opaque tag indicating the current version of the `Policy`, used for concurrency control.
   * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this
   * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write
   * loop. When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be
   * unset. When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was
   * returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency
   * control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional
   * write of the `Policy`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String etag;

  /**
   * List of values either allowed or disallowed.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudOrgpolicyV1ListPolicy listPolicy;

  /**
   * Restores the default behavior of the constraint; independent of `Constraint` type.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudOrgpolicyV1RestoreDefault restoreDefault;

  /**
   * The time stamp the `Policy` was previously updated. This is set by the server, not specified by
   * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`.
   * Any value set by the client will be ignored.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String updateTime;

  /**
   * Version of the `Policy`. Default version is 0;
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer version;

  /**
   * For boolean `Constraints`, whether to enforce the `Constraint` or not.
   * @return value or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1BooleanPolicy getBooleanPolicy() {
    return booleanPolicy;
  }

  /**
   * For boolean `Constraints`, whether to enforce the `Constraint` or not.
   * @param booleanPolicy booleanPolicy or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setBooleanPolicy(GoogleCloudOrgpolicyV1BooleanPolicy booleanPolicy) {
    this.booleanPolicy = booleanPolicy;
    return this;
  }

  /**
   * The name of the `Constraint` the `Policy` is configuring, for example,
   * `constraints/serviceuser.services`. A [list of available constraints](/resource-manager/docs
   * /organization-policy/org-policy-constraints) is available. Immutable after creation.
   * @return value or {@code null} for none
   */
  public java.lang.String getConstraint() {
    return constraint;
  }

  /**
   * The name of the `Constraint` the `Policy` is configuring, for example,
   * `constraints/serviceuser.services`. A [list of available constraints](/resource-manager/docs
   * /organization-policy/org-policy-constraints) is available. Immutable after creation.
   * @param constraint constraint or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setConstraint(java.lang.String constraint) {
    this.constraint = constraint;
    return this;
  }

  /**
   * An opaque tag indicating the current version of the `Policy`, used for concurrency control.
   * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this
   * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write
   * loop. When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be
   * unset. When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was
   * returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency
   * control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional
   * write of the `Policy`.
   * @see #decodeEtag()
   * @return value or {@code null} for none
   */
  public java.lang.String getEtag() {
    return etag;
  }

  /**
   * An opaque tag indicating the current version of the `Policy`, used for concurrency control.
   * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this
   * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write
   * loop. When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be
   * unset. When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was
   * returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency
   * control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional
   * write of the `Policy`.
   * @see #getEtag()
   * @return Base64 decoded value or {@code null} for none
   *
   * @since 1.14
   */
  public byte[] decodeEtag() {
    return com.google.api.client.util.Base64.decodeBase64(etag);
  }

  /**
   * An opaque tag indicating the current version of the `Policy`, used for concurrency control.
   * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this
   * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write
   * loop. When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be
   * unset. When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was
   * returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency
   * control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional
   * write of the `Policy`.
   * @see #encodeEtag()
   * @param etag etag or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setEtag(java.lang.String etag) {
    this.etag = etag;
    return this;
  }

  /**
   * An opaque tag indicating the current version of the `Policy`, used for concurrency control.
   * When the `Policy` is returned from either a `GetPolicy` or a `ListOrgPolicy` request, this
   * `etag` indicates the version of the current `Policy` to use when executing a read-modify-write
   * loop. When the `Policy` is returned from a `GetEffectivePolicy` request, the `etag` will be
   * unset. When the `Policy` is used in a `SetOrgPolicy` method, use the `etag` value that was
   * returned from a `GetOrgPolicy` request as part of a read-modify-write loop for concurrency
   * control. Not setting the `etag`in a `SetOrgPolicy` request will result in an unconditional
   * write of the `Policy`.
   * @see #setEtag()
   *
   *

   * The value is encoded Base64 or {@code null} for none.
   *

   *
   * @since 1.14
   */
  public GoogleCloudOrgpolicyV1Policy encodeEtag(byte[] etag) {
    this.etag = com.google.api.client.util.Base64.encodeBase64URLSafeString(etag);
    return this;
  }

  /**
   * List of values either allowed or disallowed.
   * @return value or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1ListPolicy getListPolicy() {
    return listPolicy;
  }

  /**
   * List of values either allowed or disallowed.
   * @param listPolicy listPolicy or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setListPolicy(GoogleCloudOrgpolicyV1ListPolicy listPolicy) {
    this.listPolicy = listPolicy;
    return this;
  }

  /**
   * Restores the default behavior of the constraint; independent of `Constraint` type.
   * @return value or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1RestoreDefault getRestoreDefault() {
    return restoreDefault;
  }

  /**
   * Restores the default behavior of the constraint; independent of `Constraint` type.
   * @param restoreDefault restoreDefault or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setRestoreDefault(GoogleCloudOrgpolicyV1RestoreDefault restoreDefault) {
    this.restoreDefault = restoreDefault;
    return this;
  }

  /**
   * The time stamp the `Policy` was previously updated. This is set by the server, not specified by
   * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`.
   * Any value set by the client will be ignored.
   * @return value or {@code null} for none
   */
  public String getUpdateTime() {
    return updateTime;
  }

  /**
   * The time stamp the `Policy` was previously updated. This is set by the server, not specified by
   * the caller, and represents the last time a call to `SetOrgPolicy` was made for that `Policy`.
   * Any value set by the client will be ignored.
   * @param updateTime updateTime or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setUpdateTime(String updateTime) {
    this.updateTime = updateTime;
    return this;
  }

  /**
   * Version of the `Policy`. Default version is 0;
   * @return value or {@code null} for none
   */
  public java.lang.Integer getVersion() {
    return version;
  }

  /**
   * Version of the `Policy`. Default version is 0;
   * @param version version or {@code null} for none
   */
  public GoogleCloudOrgpolicyV1Policy setVersion(java.lang.Integer version) {
    this.version = version;
    return this;
  }

  @Override
  public GoogleCloudOrgpolicyV1Policy set(String fieldName, Object value) {
    return (GoogleCloudOrgpolicyV1Policy) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudOrgpolicyV1Policy clone() {
    return (GoogleCloudOrgpolicyV1Policy) super.clone();
  }

}


text:
@echo off
REM This script removes the first X characters from every filename in the
REM the current directory where X is a user provided number
setlocal EnableDelayedExpansion
if errorlevel 1 (
	echo Unable to enable Delayed variable expansion
	exit /B
)
setlocal EnableExtensions
if errorlevel 1 (
	echo Unable to enable Command extensions
	exit /B
)
if not -%1-==-- goto :main

:printHelp
echo Removes num characters from all filenames in the current directory
echo.
echo fnchop [options] num
echo.
echo   num
echo       Specifies how many characters to chop off
echo.
echo   OPTIONS
echo     -e, --end
echo         Removes characters from end of filename instead of beginning
echo     -d, --directories
echo         Operate on directories in addition to files
echo     -D, --directories-only
echo         Operate on directories instead of files
echo     -h, --hold
echo         Don't rename anything, just print out the new filenames
echo     --debug
echo         "hold" flag and some more verbose output
echo     --help
echo         Print this message
exit /B

:procDir
	set a=%~1
	if !_debug!==yes (
		echo Directory  : !a!
	)

	REM Get filename and extension length
	echo !a!>x & for %%i in (x) do (
		set /A count=%%~zi - 2 & del x
	)
	set /A count=!count!-1

	if !_debug!==yes (
		echo Name length: !count!
	)

	if !qt! GEQ !count! (
		echo Cannot chop all characters or more than are present, skipping !a:~0,7!...
		echo.
		goto :eof
	)

	call set "newName=!a:~%qt%!"
	if !_debug!==yes (
		echo New name   : !newName!
		echo.
	) else if !_hold!==yes (
		echo Directory: !a!
		echo New name : !newName!
		echo.
	) else (
		rename "!a!" "!newName!"
	)
goto :eof

:rprocDir
	set a=%~1
	if !_debug!==yes (
		echo Directory  : !a!
	)

	REM Get filename and extension length
	echo !a!>x & for %%i in (x) do (
		set /A count=%%~zi - 2 & del x
	)
	set /A count=!count!-1

	if !_debug!==yes (
		echo Name length: !count!
	)

	if !qt! GEQ !count! (
		echo Cannot chop all characters or more than are present, skipping !a:~0,7!...
		echo.
		goto :eof
	)

	set /A "back_ofst=0-!qt!"
	call set "lose_this=!a:~%back_ofst%!"
	call set "newName=!a:%lose_this%=!"

	if !_debug!==yes (
		echo Removing   : !lose_this!
		echo New name   : !newName!
		echo.
	) else if !_hold!==yes (
		echo Directory: !a!
		echo New name : !newName!
		echo.
	) else (
		rename "!a!" "!newName!"
	)
goto :eof

:procFile
	set a=%~1
	if !_debug!==yes (
		echo File        : !a!
	)

	REM Get filename and extension length
	echo !a!>x & for %%i in (x) do (
		set /A count=%%~zi - 2 & del x
	)
	set /A count=!count!-1
	echo !ext!>x & for %%i in (x) do (
		set /A extcount=%%~zi - 2 & del x
	)
	set /A extcount=!extcount!-1
	set /A "fnlength=!count!-!extcount!"

	if !_debug!==yes (
		echo Name length : !fnlength!
	)

	if !qt! GEQ !fnlength! (
		echo Cannot chop all characters or more than are present, skipping !a:~0,7!...
		echo.
		goto :eof
	)

	call set "newName=!a:~%qt%!"
	if !_debug!==yes (
		echo new filename: !newName!
		echo.
	) else if !_hold!==yes (
		echo old filename: !a!
		echo new filename: !newName!
		echo.
	) else (
		rename "!a!" "!newName!"
	)
goto :eof

:rprocFile
	set a=%~1
	if !_debug!==yes (
		echo File        : !a!
	)

	REM Get filename length and extension length
	echo !a!>x & for %%i in (x) do (
		set /A count=%%~zi - 2 & del x
	)
	set /A count=!count!-1
	echo !ext!>x & for %%i in (x) do (
		set /A extcount=%%~zi - 2 & del x
	)
	set /A extcount=!extcount!-1
	set /A "fnlength=!count!-!extcount!"

	if !_debug!==yes (
		echo Name length : !fnlength!
	)

	if !qt! GEQ !fnlength! (
		echo Cannot chop all characters or more than are present, skipping !a:~0,7!...
		echo.
		goto :eof
	)

	REM Back offset -> offset to use to find the substring we want to chop off
	set /A "back_ofst=%extcount%+%qt%"
	set /A "back_ofst=0-!back_ofst!"

	call set "lose_this=!a:~%back_ofst%!"
	call set "newName=!a:%lose_this%=!"
	call set "newName=!newName!!ext!"

	if !_debug!==yes (
		echo Removing    : !lose_this!
		echo new filename: !newName!
		echo.
	) else if !_hold!==yes (
		echo old filename: !a!
		echo new filename: !newName!
		echo.
	) else (
		rename "!a!" "!newName!"
	)
goto :eof

:main
set _me=%~nx0
set _mode=beg
set qt=0
set _debug=no
set _hold=no
set _files=yes
set _directories=no

:argloop
if %1==-e (
	set _mode=end
) else if %1==--end (
	set _mode=end
) else if %1==-d (
	set _directories=yes
) else if %1==--directories (
	set _directories=yes
) else if %1==-D (
	set _directories=yes
	set _files=no
) else if %1==--directories-only (
	set _directories=yes
	set _files=no
) else if %1==-h (
	set _hold=yes
) else if %1==--hold (
	set _hold=yes
) else if %1==--debug (
	set _debug=yes
) else if %1==--help (
	goto printHelp
) else (
	set qt=%1
)
shift
if not -%1-==-- goto argloop

REM sanity checks
if -!qt!-==-- goto printHelp
REM Test to see if qt is a number
REM If not, the error level will be set to 1
echo !qt!| findstr /r "^[1-9][0-9]*$">nul
if errorlevel 1 (
	echo Please make the last argument a number
	exit /B
)

if !_debug!==yes (
	if !_mode!==end (
		echo Remove from       : End
	) else (
		echo Remove from       : Beginning
	)
	if !_files!==yes (
		echo Rename files      : YES
	) else (
		echo Rename files      : NO
	)
	if !_directories!==yes (
		echo Rename directories: YES
	) else (
		echo Rename directories: NO
	)
	if !_hold!==yes (
		echo Hold flag         : YES
	) else (
		echo Hold flag         : NO
	)
	echo Quantity          : !qt!
	echo.
)

if !_files!==yes (
	for %%i in (*) do (
		if not %%i==!_me! (
			set ext=%%~xi
			if !_mode!==beg (
				call :procFile "%%i"
			) else (
				call :rprocFile "%%i"
			)
		)
	)
)
if !_directories!==yes (
	for /D %%i in (*) do (
		if !_mode!==beg (
			call :procDir "%%i"
		) else (
			call :rprocDir "%%i"
		)
	)
)
exit /B


text:
// +build !providerless

package azure

import (
	"fmt"
	"net/http"
	"testing"

	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	cloudprovider "k8s.io/cloud-provider"
	"k8s.io/legacy-cloud-providers/azure/cache"
	"k8s.io/legacy-cloud-providers/azure/clients/interfaceclient/mockinterfaceclient"
	"k8s.io/legacy-cloud-providers/azure/clients/loadbalancerclient/mockloadbalancerclient"
	"k8s.io/legacy-cloud-providers/azure/clients/publicipclient/mockpublicipclient"
	"k8s.io/legacy-cloud-providers/azure/clients/routeclient/mockrouteclient"
	"k8s.io/legacy-cloud-providers/azure/clients/routetableclient/mockroutetableclient"
	"k8s.io/legacy-cloud-providers/azure/clients/securitygroupclient/mocksecuritygroupclient"
	"k8s.io/legacy-cloud-providers/azure/clients/vmclient/mockvmclient"
	"k8s.io/legacy-cloud-providers/azure/clients/vmssclient/mockvmssclient"
	"k8s.io/legacy-cloud-providers/azure/retry"

	"github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute"
	"github.com/Azure/azure-sdk-for-go/services/network/mgmt/2019-06-01/network"
	"github.com/Azure/go-autorest/autorest/to"
	"github.com/golang/mock/gomock"
	"github.com/stretchr/testify/assert"
)

func TestGetVirtualMachineWithRetry(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		vmClientErr *retry.Error
		expectedErr error
	}{
		{
			vmClientErr: &retry.Error{HTTPStatusCode: http.StatusNotFound},
			expectedErr: cloudprovider.InstanceNotFound,
		},
		{
			vmClientErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"),
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface)
		mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(compute.VirtualMachine{}, test.vmClientErr)

		vm, err := az.GetVirtualMachineWithRetry("vm", cache.CacheReadTypeDefault)
		assert.Empty(t, vm)
		assert.Equal(t, test.expectedErr, err)
	}
}

func TestGetPrivateIPsForMachine(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		vmClientErr        *retry.Error
		expectedPrivateIPs []string
		expectedErr        error
	}{
		{
			expectedPrivateIPs: []string{"1.2.3.4"},
		},
		{
			vmClientErr:        &retry.Error{HTTPStatusCode: http.StatusNotFound},
			expectedErr:        cloudprovider.InstanceNotFound,
			expectedPrivateIPs: []string{},
		},
		{
			vmClientErr:        &retry.Error{HTTPStatusCode: http.StatusInternalServerError},
			expectedErr:        wait.ErrWaitTimeout,
			expectedPrivateIPs: []string{},
		},
	}

	expectedVM := compute.VirtualMachine{
		VirtualMachineProperties: &compute.VirtualMachineProperties{
			AvailabilitySet: &compute.SubResource{ID: to.StringPtr("availability-set")},
			NetworkProfile: &compute.NetworkProfile{
				NetworkInterfaces: &[]compute.NetworkInterfaceReference{
					{
						NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
							Primary: to.BoolPtr(true),
						},
						ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"),
					},
				},
			},
		},
	}

	expectedInterface := network.Interface{
		InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
			IPConfigurations: &[]network.InterfaceIPConfiguration{
				{
					InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
						PrivateIPAddress: to.StringPtr("1.2.3.4"),
					},
				},
			},
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface)
		mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, test.vmClientErr)

		mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface)
		mockInterfaceClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(expectedInterface, nil).MaxTimes(1)

		privateIPs, err := az.getPrivateIPsForMachine("vm")
		assert.Equal(t, test.expectedErr, err)
		assert.Equal(t, test.expectedPrivateIPs, privateIPs)
	}
}

func TestGetIPForMachineWithRetry(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		clientErr         *retry.Error
		expectedPrivateIP string
		expectedPublicIP  string
		expectedErr       error
	}{
		{
			expectedPrivateIP: "1.2.3.4",
			expectedPublicIP:  "5.6.7.8",
		},
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusNotFound},
			expectedErr: wait.ErrWaitTimeout,
		},
	}

	expectedVM := compute.VirtualMachine{
		VirtualMachineProperties: &compute.VirtualMachineProperties{
			AvailabilitySet: &compute.SubResource{ID: to.StringPtr("availability-set")},
			NetworkProfile: &compute.NetworkProfile{
				NetworkInterfaces: &[]compute.NetworkInterfaceReference{
					{
						NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
							Primary: to.BoolPtr(true),
						},
						ID: to.StringPtr("/subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/networkInterfaces/nic"),
					},
				},
			},
		},
	}

	expectedInterface := network.Interface{
		InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
			IPConfigurations: &[]network.InterfaceIPConfiguration{
				{
					InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
						PrivateIPAddress: to.StringPtr("1.2.3.4"),
						PublicIPAddress: &network.PublicIPAddress{
							ID: to.StringPtr("test/pip"),
						},
					},
				},
			},
		},
	}

	expectedPIP := network.PublicIPAddress{
		PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
			IPAddress: to.StringPtr("5.6.7.8"),
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		mockVMClient := az.VirtualMachinesClient.(*mockvmclient.MockInterface)
		mockVMClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "vm", gomock.Any()).Return(expectedVM, test.clientErr)

		mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface)
		mockInterfaceClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(expectedInterface, nil).MaxTimes(1)

		mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
		mockPIPClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(expectedPIP, nil).MaxTimes(1)

		privateIP, publicIP, err := az.GetIPForMachineWithRetry("vm")
		assert.Equal(t, test.expectedErr, err)
		assert.Equal(t, test.expectedPrivateIP, privateIP)
		assert.Equal(t, test.expectedPublicIP, publicIP)
	}
}

func TestCreateOrUpdateSecurityGroupCanceled(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	az.nsgCache.Set("sg", "test")

	mockSGClient := az.SecurityGroupsClient.(*mocksecuritygroupclient.MockInterface)
	mockSGClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(&retry.Error{
		RawError: fmt.Errorf(operationCanceledErrorMessage),
	})
	mockSGClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "sg", gomock.Any()).Return(network.SecurityGroup{}, nil)

	err := az.CreateOrUpdateSecurityGroup(&v1.Service{}, network.SecurityGroup{Name: to.StringPtr("sg")})
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: canceledandsupersededduetoanotheroperation"), err)

	// security group should be removed from cache if the operation is canceled
	shouldBeEmpty, err := az.nsgCache.Get("sg", cache.CacheReadTypeDefault)
	assert.NoError(t, err)
	assert.Empty(t, shouldBeEmpty)
}

func TestCreateOrUpdateLB(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	referencedResourceNotProvisionedRawErrorString := `Code="ReferencedResourceNotProvisioned" Message="Cannot proceed with operation because resource /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/publicIPAddresses/pip used by resource /subscriptions/sub/resourceGroups/rg/providers/Microsoft.Network/loadBalancers/lb is not in Succeeded state. Resource is in Failed state and the last operation that updated/is updating the resource is PutPublicIpAddressOperation."`

	tests := []struct {
		clientErr   *retry.Error
		expectedErr error
	}{
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusPreconditionFailed},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 412, RawError: <nil>"),
		},
		{
			clientErr:   &retry.Error{RawError: fmt.Errorf(operationCanceledErrorMessage)},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: canceledandsupersededduetoanotheroperation"),
		},
		{
			clientErr:   &retry.Error{RawError: fmt.Errorf(referencedResourceNotProvisionedRawErrorString)},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: %s", referencedResourceNotProvisionedRawErrorString),
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		az.lbCache.Set("lb", "test")

		mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface)
		mockLBClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(test.clientErr)
		mockLBClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "lb", gomock.Any()).Return(network.LoadBalancer{}, nil)

		mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
		mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(nil).AnyTimes()
		mockPIPClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "pip", gomock.Any()).Return(network.PublicIPAddress{
			Name: to.StringPtr("pip"),
			PublicIPAddressPropertiesFormat: &network.PublicIPAddressPropertiesFormat{
				ProvisioningState: to.StringPtr("Succeeded"),
			},
		}, nil).AnyTimes()

		err := az.CreateOrUpdateLB(&v1.Service{}, network.LoadBalancer{
			Name: to.StringPtr("lb"),
			Etag: to.StringPtr("etag"),
		})
		assert.Equal(t, test.expectedErr, err)

		// loadbalancer should be removed from cache if the etag is mismatch or the operation is canceled
		shouldBeEmpty, err := az.lbCache.Get("lb", cache.CacheReadTypeDefault)
		assert.NoError(t, err)
		assert.Empty(t, shouldBeEmpty)
	}
}

func TestListLB(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface)
	mockLBClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(nil, &retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	pips, err := az.ListLB(&v1.Service{})
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
	assert.Empty(t, pips)
}

func TestListPIP(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
	mockPIPClient.EXPECT().List(gomock.Any(), az.ResourceGroup).Return(nil, &retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	pips, err := az.ListPIP(&v1.Service{}, az.ResourceGroup)
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
	assert.Empty(t, pips)
}

func TestCreateOrUpdatePIP(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
	mockPIPClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	err := az.CreateOrUpdatePIP(&v1.Service{}, az.ResourceGroup, network.PublicIPAddress{Name: to.StringPtr("nic")})
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
}

func TestCreateOrUpdateInterface(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockInterfaceClient := az.InterfacesClient.(*mockinterfaceclient.MockInterface)
	mockInterfaceClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "nic", gomock.Any()).Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	err := az.CreateOrUpdateInterface(&v1.Service{}, network.Interface{Name: to.StringPtr("nic")})
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
}

func TestDeletePublicIP(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockPIPClient := az.PublicIPAddressesClient.(*mockpublicipclient.MockInterface)
	mockPIPClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "pip").Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	err := az.DeletePublicIP(&v1.Service{}, az.ResourceGroup, "pip")
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
}

func TestDeleteLB(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	mockLBClient := az.LoadBalancerClient.(*mockloadbalancerclient.MockInterface)
	mockLBClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "lb").Return(&retry.Error{HTTPStatusCode: http.StatusInternalServerError})

	err := az.DeleteLB(&v1.Service{}, "lb")
	assert.Equal(t, fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"), err)
}

func TestCreateOrUpdateRouteTable(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		clientErr   *retry.Error
		expectedErr error
	}{
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusPreconditionFailed},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 412, RawError: <nil>"),
		},
		{
			clientErr:   &retry.Error{RawError: fmt.Errorf(operationCanceledErrorMessage)},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: canceledandsupersededduetoanotheroperation"),
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		az.rtCache.Set("rt", "test")

		mockRTClient := az.RouteTablesClient.(*mockroutetableclient.MockInterface)
		mockRTClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, gomock.Any(), gomock.Any(), gomock.Any()).Return(test.clientErr)
		mockRTClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil)

		err := az.CreateOrUpdateRouteTable(network.RouteTable{
			Name: to.StringPtr("rt"),
			Etag: to.StringPtr("etag"),
		})
		assert.Equal(t, test.expectedErr, err)

		// route table should be removed from cache if the etag is mismatch or the operation is canceled
		shouldBeEmpty, err := az.rtCache.Get("rt", cache.CacheReadTypeDefault)
		assert.NoError(t, err)
		assert.Empty(t, shouldBeEmpty)
	}
}

func TestCreateOrUpdateRoute(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		clientErr   *retry.Error
		expectedErr error
	}{
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusPreconditionFailed},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 412, RawError: <nil>"),
		},
		{
			clientErr:   &retry.Error{RawError: fmt.Errorf(operationCanceledErrorMessage)},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 0, RawError: canceledandsupersededduetoanotheroperation"),
		},
		{
			clientErr:   nil,
			expectedErr: nil,
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)
		az.rtCache.Set("rt", "test")

		mockRTClient := az.RoutesClient.(*mockrouteclient.MockInterface)
		mockRTClient.EXPECT().CreateOrUpdate(gomock.Any(), az.ResourceGroup, "rt", gomock.Any(), gomock.Any(), gomock.Any()).Return(test.clientErr)

		mockRTableClient := az.RouteTablesClient.(*mockroutetableclient.MockInterface)
		mockRTableClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, "rt", gomock.Any()).Return(network.RouteTable{}, nil)

		err := az.CreateOrUpdateRoute(network.Route{
			Name: to.StringPtr("rt"),
			Etag: to.StringPtr("etag"),
		})
		assert.Equal(t, test.expectedErr, err)

		shouldBeEmpty, err := az.rtCache.Get("rt", cache.CacheReadTypeDefault)
		assert.NoError(t, err)
		assert.Empty(t, shouldBeEmpty)
	}
}

func TestDeleteRouteWithName(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		clientErr   *retry.Error
		expectedErr error
	}{
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusInternalServerError},
			expectedErr: fmt.Errorf("Retriable: false, RetryAfter: 0s, HTTPStatusCode: 500, RawError: <nil>"),
		},
		{
			clientErr:   nil,
			expectedErr: nil,
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)

		mockRTClient := az.RoutesClient.(*mockrouteclient.MockInterface)
		mockRTClient.EXPECT().Delete(gomock.Any(), az.ResourceGroup, "rt", "rt").Return(test.clientErr)

		err := az.DeleteRouteWithName("rt")
		assert.Equal(t, test.expectedErr, err)
	}
}

func TestCreateOrUpdateVMSS(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	tests := []struct {
		vmss        compute.VirtualMachineScaleSet
		clientErr   *retry.Error
		expectedErr *retry.Error
	}{
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusInternalServerError},
			expectedErr: &retry.Error{HTTPStatusCode: http.StatusInternalServerError},
		},
		{
			clientErr:   &retry.Error{HTTPStatusCode: http.StatusTooManyRequests},
			expectedErr: &retry.Error{HTTPStatusCode: http.StatusTooManyRequests},
		},
		{
			clientErr:   &retry.Error{RawError: fmt.Errorf("azure cloud provider rate limited(write) for operation CreateOrUpdate")},
			expectedErr: &retry.Error{RawError: fmt.Errorf("azure cloud provider rate limited(write) for operation CreateOrUpdate")},
		},
		{
			vmss: compute.VirtualMachineScaleSet{
				VirtualMachineScaleSetProperties: &compute.VirtualMachineScaleSetProperties{
					ProvisioningState: &virtualMachineScaleSetsDeallocating,
				},
			},
		},
	}

	for _, test := range tests {
		az := GetTestCloud(ctrl)

		mockVMSSClient := az.VirtualMachineScaleSetsClient.(*mockvmssclient.MockInterface)
		mockVMSSClient.EXPECT().Get(gomock.Any(), az.ResourceGroup, testVMSSName).Return(test.vmss, test.clientErr)

		err := az.CreateOrUpdateVMSS(az.ResourceGroup, testVMSSName, compute.VirtualMachineScaleSet{})
		assert.Equal(t, test.expectedErr, err)
	}
}

func TestRequestBackoff(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	az := GetTestCloud(ctrl)
	az.CloudProviderBackoff = true
	az.ResourceRequestBackoff = wait.Backoff{Steps: 3}

	backoff := az.RequestBackoff()
	assert.Equal(t, wait.Backoff{Steps: 3}, backoff)

}


text:
package service

import (
	"context"
	"encoding/json"
	"fmt"
	"regexp"
	"time"

	"go-common/app/job/main/dm2/conf"
	"go-common/app/job/main/dm2/dao"
	"go-common/app/job/main/dm2/model"
	"go-common/app/job/main/dm2/model/oplog"
	arcCli "go-common/app/service/main/archive/api/gorpc"
	filterCli "go-common/app/service/main/filter/api/grpc/v1"
	seqMdl "go-common/app/service/main/seq-server/model"
	seqCli "go-common/app/service/main/seq-server/rpc/client"
	"go-common/library/log"
	"go-common/library/log/infoc"
	"go-common/library/queue/databus"
	"go-common/library/sync/pipeline/fanout"
	"go-common/library/xstr"
)

const (
	_routineSizeDefault = 10
	_chanSize           = 10240
	_batchSize          = 1000
	_maxUpRecent        = 1000
)

// Service service struct
type Service struct {
	conf   *conf.Config
	dao    *dao.Dao
	cache  *fanout.Fanout
	arcRPC *arcCli.Service2
	// seq serer
	seqArg            *seqMdl.ArgBusiness
	seqRPC            *seqCli.Service2
	indexCsmr         *databus.Databus
	subjectCsmr       *databus.Databus
	actionCsmr        *databus.Databus
	reportCsmr        *databus.Databus
	videoupCsmr       *databus.Databus
	subtitleAuditCsmr *databus.Databus
	flushMergeChan    []chan *model.Flush
	flushSegChan      []chan *model.FlushDMSeg
	dmRecentChan      []chan *model.DM
	routineSize       int
	realname          map[int64]int64 // key:分区id,value:cid,即该分区中大于cid的视频开启实名制
	// filter service
	filterRPC         filterCli.FilterClient
	maskMid           []int64
	dmOperationLogSvc *infoc.Infoc
	opsLogCh          chan *oplog.Infoc
	// bnj
	bnjAid             int64
	bnjSubAids         map[int64]struct{}
	bnjCsmr            *databus.Databus
	bnjliveRoomID      int64
	bnjStart           time.Time
	bnjIgnoreBeginTime time.Duration
	bnjIgnoreEndTime   time.Duration
	bnjArcVideos       []*model.Video
	bnjIgnoreRate      int64
	bnjUserLevel       int32
}

// New new service.
func New(c *conf.Config) (s *Service) {
	s = &Service{
		conf:              c,
		dao:               dao.New(c),
		cache:             fanout.New("cache", fanout.Worker(1), fanout.Buffer(1024)),
		arcRPC:            arcCli.New2(c.ArchiveRPC),
		seqArg:            &seqMdl.ArgBusiness{BusinessID: c.Seq.BusinessID, Token: c.Seq.Token},
		seqRPC:            seqCli.New2(c.SeqRPC),
		subjectCsmr:       databus.New(c.Databus.SubjectCsmr),
		indexCsmr:         databus.New(c.Databus.IndexCsmr),
		actionCsmr:        databus.New(c.Databus.ActionCsmr),
		reportCsmr:        databus.New(c.Databus.ReportCsmr),
		videoupCsmr:       databus.New(c.Databus.VideoupCsmr),
		subtitleAuditCsmr: databus.New(c.Databus.SubtitleAuditCsmr),
		routineSize:       c.RoutineSize,
		realname:          make(map[int64]int64),
		dmOperationLogSvc: infoc.New(c.Infoc2),
		opsLogCh:          make(chan *oplog.Infoc, 1024),
	}
	if c.RoutineSize <= 0 {
		s.routineSize = _routineSizeDefault
	}
	s.flushMergeChan = make([]chan *model.Flush, s.routineSize)
	s.flushSegChan = make([]chan *model.FlushDMSeg, s.routineSize)
	s.dmRecentChan = make([]chan *model.DM, s.routineSize)
	filterRPC, err := filterCli.NewClient(c.FliterRPC)
	if err != nil {
		panic(err)
	}
	s.filterRPC = filterRPC
	for idStr, cid := range conf.Conf.Realname {
		ids, err := xstr.SplitInts(idStr)
		if err != nil {
			panic(err)
		}
		for _, id := range ids {
			if _, ok := s.realname[id]; !ok {
				s.realname[id] = cid
			}
		}
	}
	// laji bnj
	if s.conf.BNJ != nil {
		//bnj count
		s.initBnj()
	}
	//消费DMReport-T消息
	go s.reportCsmproc()
	// 消费DMAction-T消息
	go s.actionCsmproc()
	// 消费DMSubject-T消息
	go s.subjectCsmproc()
	// 消费DMMeta-T消息
	go s.indexCsmproc()
	// 消费 Videoup2Bvc消息
	go s.videoupCsmrproc()
	// 消费 字幕 提交 消息
	go s.subtitleAuditProc()
	// 刷新全段弹幕
	for i := 0; i < s.routineSize; i++ {
		flushChan := make(chan *model.Flush, _chanSize)
		s.flushMergeChan[i] = flushChan
		go s.flushmergeproc(flushChan)
	}
	// 刷新分段弹幕
	for i := 0; i < s.routineSize; i++ {
		flushSegChan := make(chan *model.FlushDMSeg, _chanSize)
		s.flushSegChan[i] = flushSegChan
		go s.flushSegproc(flushSegChan)
	}
	// 异步处理创作中心最新弹幕列表缓存
	for i := 0; i < s.routineSize; i++ {
		recentChan := make(chan *model.DM, _chanSize)
		s.dmRecentChan[i] = recentChan
		go s.dmRecentproc(recentChan)
	}
	go s.transferProc()
	// 处理热门二级分类视频的弹幕蒙版
	go s.maskProc()
	// 刷新开启蒙版mid
	s.maskMid, _ = s.dao.MaskMids(context.TODO())
	log.Info("update mask mid(%v)", s.maskMid)
	go s.maskMidProc()
	// dm task
	go s.taskResProc()
	go s.taskDelProc()
	// oplog
	go s.oplogproc()
	return
}

// Ping check thrid resource.
func (s *Service) Ping(c context.Context) (err error) {
	return s.dao.Ping(c)
}

func (s *Service) subjectCsmproc() {
	var (
		err          error
		c            = context.TODO()
		regexSubject = regexp.MustCompile("dm_subject_[0-9]+")
	)
	for {
		msg, ok := <-s.subjectCsmr.Messages()
		if !ok {
			log.Error("subject binlog consumer exit")
			return
		}
		m := &model.BinlogMsg{}
		if err = json.Unmarshal(msg.Value, &m); err != nil {
			log.Error("json.Unmarshal(%s) error(%v)", msg.Value, err)
			continue
		}
		log.Info("%s", m)
		if regexSubject.MatchString(m.Table) {
			if err = s.trackSubject(c, m); err != nil {
				log.Error("s.trackSubject(%s) error(%v)", m, err)
				continue
			}
		}
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}

func (s *Service) indexCsmproc() {
	var (
		err        error
		c          = context.TODO()
		regexIndex = regexp.MustCompile("dm_index_[0-9]+")
	)
	for {
		msg, ok := <-s.indexCsmr.Messages()
		if !ok {
			log.Error("index binlog consumer exit")
			return
		}
		m := &model.BinlogMsg{}
		if err = json.Unmarshal(msg.Value, &m); err != nil {
			log.Error("json.Unmarshal(%s) error(%v)", msg.Value, err)
			continue
		}
		log.Info("%s", m)
		if regexIndex.MatchString(m.Table) {
			if err = s.trackIndex(c, m); err != nil {
				log.Error("s.traceIndex(%s) error(%v)", m, err)
				continue
			}
		}
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}

func (s *Service) flushmergeproc(flushChan chan *model.Flush) {
	var (
		flushs = make(map[int64]*model.Flush)
		ticker = time.NewTicker(60 * time.Second)
		err    error
	)
	for {
		select {
		case flush, ok := <-flushChan:
			if !ok {
				log.Error("action channel closed")
				return
			}
			if _, ok := flushs[flush.Oid]; !ok || flush.Force { // key不存在或者需要强制刷新的
				flushs[flush.Oid] = flush
			}
			if len(flushs) < _batchSize {
				continue
			}
		case <-ticker.C:
		}
		if len(flushs) > 0 {
			for _, flush := range flushs {
				if err = s.flushDmCache(context.TODO(), flush); err != nil {
					log.Error("action:flushmergeproc,flush:%+v,error(%v)", flush, err)
				}
			}
			flushs = make(map[int64]*model.Flush)
		}
	}
}

func keySegFlush(tp int32, oid, total, num int64) string {
	return fmt.Sprintf("f_%d_%d_%d_%d", tp, oid, total, num)
}

func (s *Service) flushSegproc(ch chan *model.FlushDMSeg) {
	var (
		key    string
		merge  = make(map[string]*model.FlushDMSeg)
		ticker = time.NewTicker(60 * time.Second)
		err    error
	)
	for {
		select {
		case msg, ok := <-ch:
			if !ok {
				log.Error("action channel closed")
				return
			}
			key = keySegFlush(msg.Type, msg.Oid, msg.Page.Total, msg.Page.Num)
			if _, ok := merge[key]; !ok || msg.Force { // key不存在或者需要强制刷新的
				merge[key] = msg
			}
			if len(merge) < _batchSize {
				continue
			}
		case <-ticker.C:
		}
		if len(merge) > 0 {
			for _, v := range merge {
				if err = s.flushDmSegCache(context.TODO(), v); err != nil {
					log.Error("action:flushSegproc,data:%+v,error(%v)", v, err)
					continue
				}
			}
			merge = make(map[string]*model.FlushDMSeg)
		}
	}
}

func (s *Service) actionCsmproc() {
	for {
		msg, ok := <-s.actionCsmr.Messages()
		if !ok {
			log.Error("action consumer exit")
			return
		}
		act := &model.Action{}
		err := json.Unmarshal(msg.Value, &act)
		if err != nil {
			log.Error("json.Unmarshal(%s) error(%v)", msg.Value, err)
			continue
		}
		start := time.Now()
		if err = s.actionAct(context.TODO(), act); err != nil {
			log.Error("action:%s,data:%s,error(%v)", act.Action, act.Data, err)
			continue
		}
		log.Info("partition:%d,offset:%d,key:%s,value:%s costing:%+v", msg.Partition, msg.Offset, msg.Key, msg.Value, time.Since(start))
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}

// add recent dm
func (s *Service) dmRecentproc(dmChan chan *model.DM) {
	var (
		count int64
		c     = context.TODO()
	)
	for {
		dm, ok := <-dmChan
		if !ok {
			log.Error("recent dm channel is closed")
			return
		}
		sub, err := s.subject(c, dm.Type, dm.Oid)
		if err != nil {
			continue
		}
		if dm.State != model.StateNormal && dm.State != model.StateHide && dm.State != model.StateMonitorAfter {
			if err = s.dao.ZRemRecentDM(c, sub.Mid, dm.ID); err != nil {
				continue
			}
		} else {
			if dm.Content == nil {
				if dm.Content, err = s.dao.Content(c, dm.Oid, dm.ID); err != nil {
					continue
				}
			}
			if dm.Pool == model.PoolSpecial && dm.ContentSpe == nil {
				if dm.ContentSpe, err = s.dao.ContentSpecial(c, dm.ID); err != nil {
					continue
				}
			}
			if count, err = s.dao.AddRecentDM(c, sub.Mid, dm); err != nil {
				continue
			}
			if trimCnt := count - _maxUpRecent; trimCnt > 0 {
				if err = s.dao.TrimRecentDM(c, sub.Mid, trimCnt); err != nil {
					continue
				}
			}
		}
	}
}

func (s *Service) asyncAddRecent(c context.Context, dm *model.DM) {
	select {
	case s.dmRecentChan[dm.Oid%int64(s.routineSize)] <- dm:
	default:
		log.Warn("dm recent channel is full,dm(%+v)", dm)
	}
}

func (s *Service) reportCsmproc() {
	for {
		msg, ok := <-s.reportCsmr.Messages()
		if !ok {
			log.Error("report consumer exit")
			return
		}
		log.Info("partition:%d,offset:%d,value:%s", msg.Partition, msg.Offset, msg.Value)
		act := &model.ReportAction{}
		err := json.Unmarshal(msg.Value, &act)
		if err != nil {
			log.Error("json.Unmarshal(%s) error(%v)", msg.Value, err)
			continue
		}
		if diff := act.HideTime - time.Now().Unix(); diff > 0 {
			log.Info("action:%+v will be processed after %d seconds", act, diff)
			time.Sleep(time.Duration(diff) * time.Second)
		}
		if _, err = s.dao.DelDMHideState(context.TODO(), 1, act.Cid, act.Did); err != nil {
			log.Error("DelDMHideState(%+v) error(%v)", act, err)
		} else {
			log.Info("DelDMHideState(%+v) success ", act)
		}
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}

func (s *Service) videoupCsmrproc() {
	var (
		err error
		c   = context.TODO()
	)
	for {
		msg, ok := <-s.videoupCsmr.Messages()
		if !ok {
			log.Error("videoup consumer exit")
			return
		}
		log.Info("partition:%d,offset:%d,key:%s,value:%s", msg.Partition, msg.Offset, msg.Key, msg.Value)
		m := &model.VideoupMsg{}
		if err = json.Unmarshal(msg.Value, m); err != nil {
			log.Error("json.Unmarshal(%v) error(%v)", string(msg.Value), err)
			continue
		}
		if m.Route == model.RouteSecondRound || m.Route == model.RouteAutoOpen ||
			m.Route == model.RouteForceSync || m.Route == model.RouteDelayOpen {
			if err = s.trackVideoup(c, m.Aid); err != nil {
				continue
			}
		}
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}

func (s *Service) subtitleAuditProc() {
	var (
		err error
		c   = context.Background()
	)
	for {
		msg, ok := <-s.subtitleAuditCsmr.Messages()
		if !ok {
			log.Error("subtitle_audit consumer exit")
			return
		}
		log.Info("partition:%d,offset:%d,key:%s,value:%s", msg.Partition, msg.Offset, msg.Key, msg.Value)
		m := &model.SubtitleAuditMsg{}
		if err = json.Unmarshal(msg.Value, m); err != nil {
			log.Error("json.Unmarshal(%v) error(%v)", string(msg.Value), err)
			continue
		}
		if err = s.SubtitleFilter(c, m.Oid, m.SubtitleID); err != nil {
			log.Error("SubtitleFilter(oid:%v,subtitleID:%v),error(%v)", m.Oid, m.SubtitleID, err)
			continue
		}
		if err = msg.Commit(); err != nil {
			log.Error("commit offset(%v) error(%v)", msg, err)
		}
	}
}


text:
//
//  ViewController.m
//  Decorator
//
//  Created by SkyHarute on 2017/5/21.
//  Copyright © 2017年 SkyHarute. All rights reserved.
//

#import "ViewController.h"
#import "DarkRoast.h"
#import "Milk.h"
#import "Mocha.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self test1];
}

/**
 获取到一杯普通的深焙咖啡
 */
- (void)test1{

        //获取到一杯普通的深焙咖啡
        DarkRoast *darkRoast = [[DarkRoast alloc] init];
        NSLog(@"饮品名称:%@,价格:%ld",darkRoast.beverageDesc,[darkRoast cost]);

        //加入一杯牛奶后的深焙咖啡
        Beverage *oneMilkDarkRoast = [[Milk alloc] initWithBeverage:darkRoast];
        NSLog(@"饮品名称:%@,价格:%ld",oneMilkDarkRoast.beverageDesc,[oneMilkDarkRoast cost]);

        //向加入一杯牛奶后的深焙咖啡再次加入摩卡
        Beverage *oneMilkAndOneMochaDarkRoast = [[Mocha alloc] initWithBeverage:oneMilkDarkRoast];
        NSLog(@"饮品名称:%@,价格:%ld",oneMilkAndOneMochaDarkRoast.beverageDesc,[oneMilkAndOneMochaDarkRoast cost]);
}

@end


text:
<spark-mailed-invitations :invitations="invitations" inline-template>

 0">

Mailed Invitations

                        E-Mail Address

                                    @{{ invitation.email }}

                                <button class="btn btn-danger-outline" @click="cancel(invitation)">

                                </button>

</spark-mailed-invitations>


text:
<TITLE>Review for Lock, Stock and Two Smoking Barrels (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Lock, Stock and Two Smoking Barrels (1998)

reviewed by
Dennis Schwartz

LOCK, STOCK AND TWO SMOKING BARRELS (director: Guy Ritchie; cast: Jason
Flemyng (Tom), Dexter Fletcher (Soap), Nick Moran (Eddy), Jason Statham
(Bacon), Vinnie Jones (Big Chris), Peter McNicholl (Son ), P.H. Moriarty
(Hatchet Harry), Lenny McLean (Barry the Baptist), Sting (J.D.), Steven
Mackintosh (Drug Dealer), Dog (Frank Harper),Vas Blackwood (Samoan Crime
Boss), Suzy Ratner (Stoned Girl), Stephen Marcus (Nick the Greek),
1998-UK)

No heroes and no story are the main attributes for this futile attempt
at a Trainspotting, Performance, The long Good Friday, and a
Tarantino-like gangster/comedy, all rolled into one film, served up with
an Eastender's sense of vile English humor, as this is writer/director
Guy Ritchie's first feature film, formerly known for his video
commercials. He tries every bit he could muster from the lore of
gangster and screwball comedies, to make this film work, but still
misses by a city mile.This is just a bad film. A Laurel and Hardy film
would have looked like deep sardonic humor compared with this sophomoric
effort.

Every character in the film tries to be a character, succeeding only in
being a one-dimensional one, while women do not play a significant part
in this unoriginal film, as they are reduced to being go-go girls or
unnoticeable druggies.

Ritchie's aim for the film, is to keep the audience guessing at what is
happening.

It all starts when four lame-brained Eastenders (Tom (Jason Flemying),
Bacon (Jason Statham), Eddy (Nick) and Soap (Dexter Fletcher)) pool
their life savings together to put one of them, Eddy, into a card game
with a notorious crime boss and porn king and antique gun collector by
nefarious means, Hatchet Harry (P.H.). Eddy who never loses an honest
game, loses this crooked game, and has a week to pay off the half a
million pounds debt or else his fingers and his friends' fingers will be
taken off by Harry's thug, one day-at-a time. The thug is a Lionel
Stander clone, but not even close to him in getting laughs, Barry the
Baptist (Lenny). Lenny McLean was a former bare knuckle champion, who
died shortly after the film was released.

Then the film gets slapstick happy and four gangs are going after a
bundle of money, ripped-off a non-violent drug dealer and marijuana
grower (Steven Mackintosh), who works for a Samoan crime boss, who looks
like Little Richard, (Vas), as mix-ups, treachery, confusion and
attitude become the thing, but with no group holding our attention for
long, as the pace quickens, and each group goes for their little bit of
violence and comedy, and we never stay focused on any one group, which
was a major blunder in artistic direction; after all, this is supposed
to be a movie, not a video commercial.

The gang ripping-off the drug dealer is led by a vicious thug, Dog
(Harper), who is the neighbor of the four boys, as they overhear him
planning the drug robbery, and they plan to rob him after he robs the
drug dealer, which is the way they see themselves getting out of the jam
they are in.

The film gets carried away with trying to be too clever, as one
character is always trying to top the other in craziness.

Some of the many characters in the film who caught my eye were: Chris
(Vinny Jones, who is the English bad-boy of soccer), who plays his hit
man part with a killer's deadpan face, as he works with his equally
business-like young son, (Peter McNicholl), as they both work for Harry.
Thrown into the picture are a couple of inept burglars, a greedy middle
man named Nick the Greek, a constantly stoned girl, a befuddled traffic
cop, and Sting, as a bar owner and disapproving father of Eddy. As
Eddy's dad, he can cancel the debt by handing over his bar, lock, stock
and barrel to his old adversary, Harry, but chooses not to.

The plot has its twists and turns, and it would serve no purpose telling
you about it, since the heart of the film, is about the surprises and
corpses it delivers. Since the film's humor didn't suit me and I grew
tired of seeing so many characters try to fit into such a small movie,
with all of them being a composite of a boring and motley crew of
stereotypes; and, the violence didn't particularly appeal to me, either,
leaving me squirming in my seat with displeasure.

If you take my advise, you'd avoid this one. I think you would get more
satisfaction, if you are hooked on this type of film, in seeing
something like Reservoir Dogs, even if you must see it again, it is
better than seeing this poor imitation once.

REVIEWED ON 5/28/99     GRADE: D

Dennis Schwartz: "Ozus' World Movie Reviews"

http://www.sover.net/~ozus

© ALL RIGHTS RESERVED   DENNIS SCHWARTZ

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package com.vigorous.asynchronized.network;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.vigorous.asynchronized.network.api.HttpDownloadService;
import com.vigorous.asynchronized.network.config.NetWorkDownloadConfiguration;
import com.vigorous.asynchronized.network.data.NetWorkRequestConst;
import com.vigorous.asynchronized.network.data.download.DownloadInfo;
import com.vigorous.asynchronized.network.download.AsyncDownloadObserver;
import com.vigorous.asynchronized.network.download.DownloadInterceptor;
import com.vigorous.asynchronized.network.exception.DownloadFileExistException;
import com.vigorous.asynchronized.network.exception.DownloadParamInvaildException;
import com.vigorous.asynchronized.network.exception.DownUploadWithoutWifiException;
import com.vigorous.asynchronized.network.exception.ExternalStorageWritePermissionException;
import com.vigorous.asynchronized.network.exception.HttpTimeException;
import com.vigorous.asynchronized.network.listener.AsyncDownloadProgressListener;
import com.vigorous.asynchronized.network.request.AsyncHttpManager;
import com.vigorous.asynchronized.network.util.AndroidPermissionUtil;
import com.vigorous.asynchronized.network.util.FileUtils;
import com.vigorous.asynchronized.network.util.NetworkStatusUtil;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.lang.ref.SoftReference;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Vigorous.Liang on 2017/9/19.
 */

public class AsyncDownloadManager {

    private volatile static AsyncDownloadManager INSTANCE;
    private Context mContext;
    /* 记录下载数据 */
    private ConcurrentHashMap<String, SoftReference<AsyncDownloadObserver>> downloadList;

    // 构造方法私有
    private AsyncDownloadManager(Context context) {
        mContext = context.getApplicationContext();
        downloadList = new ConcurrentHashMap<String, SoftReference<AsyncDownloadObserver>>();
    }

    // 获取单例
    public static AsyncDownloadManager getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (AsyncHttpManager.class) {
                if (INSTANCE == null && context != null) {
                    INSTANCE = new AsyncDownloadManager(context);
                }
            }
        }
        return INSTANCE;
    }

    public void startDownload(NetWorkDownloadConfiguration configuration,
            final DownloadInfo downloadInfo,
            AsyncDownloadProgressListener listener) {
        // 判断下载配置参数是否为空 TODO 判断下载url是否合法
        if (configuration == null || downloadInfo == null
                || TextUtils.isEmpty(downloadInfo.getUrl())
                || TextUtils.isEmpty(downloadInfo.getSavePath())) {
            if (listener != null) {
                listener.onError(new DownloadParamInvaildException(
                        NetWorkRequestConst.DOWNLOAD_PARAM_INVALID));
            }
            return;
        }
        // 若文件保存地址为外部存储,判断是否有外部存储的写权限
        if (downloadInfo.getSavePath().contains(
                Environment.getExternalStorageDirectory().getAbsolutePath())) {
            if (!AndroidPermissionUtil.checkPermission(mContext,
                    AndroidPermissionUtil.CODE_WRITE_EXTERNAL_STORAGE)) {
                if (listener != null) {
                    listener.onError(
                            new ExternalStorageWritePermissionException(
                                    NetWorkRequestConst.EXTERNAL_STORAGE_WRITE_PERMISSION_INVALID));
                }
                return;
            }
        }

        // 判断文件是否已存在且用户不允许覆盖
        if (FileUtils.isFileExist(downloadInfo.getSavePath())
                && !configuration.isRewriteIfFileExist()) {
            if (listener != null) {
                listener.onError(new DownloadFileExistException(
                        NetWorkRequestConst.DOWNLOAD_FILE_ALREADY_EXIST));
            }
            return;
        }
        // 若用户不允许在无wifi状态下下载且当前网络状态非wifi
        if (!configuration.isContinueIfWifiUnavailable() && NetworkStatusUtil
                .getNetworkState(mContext) != NetworkStatusUtil.NETWORK_WIFI) {
            if (listener != null) {
                listener.onError(new DownUploadWithoutWifiException(
                        NetWorkRequestConst.WIFI_UNAVAILABLE));
            }
            return;
        }
        AsyncDownloadObserver<DownloadInfo> asyncDownloadObserver = new AsyncDownloadObserver<>(
                downloadInfo, listener);
        DownloadInterceptor interceptor = new DownloadInterceptor(listener);
        okhttp3.OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(configuration.getConnectionTime(),
                        TimeUnit.SECONDS)
                .addInterceptor(interceptor);

        Retrofit retrofit = new Retrofit.Builder().client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(NetworkStatusUtil.getBasUrl(downloadInfo.getUrl()))
                .build();

        HttpDownloadService service = retrofit
                .create(HttpDownloadService.class);

        service.download("bytes=" + downloadInfo.getReadLength() + "-",
                downloadInfo.getUrl())
                /* 指定线程 */
                .subscribeOn(Schedulers.io())
                /* 读取下载写入文件 */
                .map(new Function<ResponseBody, DownloadInfo>() {
                    @Override
                    public DownloadInfo apply(ResponseBody responseBody) {
                        writeCaches(responseBody,
                                new File(downloadInfo.getSavePath()),
                                downloadInfo);
                        return downloadInfo;
                    }
                })
                /* 回调线程 */
                .observeOn(AndroidSchedulers.mainThread())
                /* 数据回调 */
                .subscribe(asyncDownloadObserver);
        downloadList.put(downloadInfo.getUrl(),
                new SoftReference<AsyncDownloadObserver>(
                        asyncDownloadObserver));
    }

    /**
     * 取消下载
     */
    public boolean stopDown(DownloadInfo info) {
        if (info == null) {
            return false;
        }
        AsyncDownloadObserver currentObserver = downloadList.get(info.getUrl())
                .get();
        if (currentObserver != null) {
            currentObserver.getDisposable().dispose();
            SoftReference listenerSoftReference = currentObserver.getCallback();
            if (listenerSoftReference != null && listenerSoftReference
                    .get() instanceof AsyncDownloadProgressListener) {
                ((AsyncDownloadProgressListener) listenerSoftReference.get())
                        .onStop();
            }
            downloadList.remove(info.getUrl());
            FileUtils.deleteFile(info.getSavePath());
            return true;
        } else {
            return false;
        }
    }

    /**
     * 取消全部下载
     */
    public void stopAllDown() {
        Iterator<SoftReference<AsyncDownloadObserver>> iterator = downloadList
                .values().iterator();
        while (iterator.hasNext()) {
            SoftReference<AsyncDownloadObserver> asyncDownloadObserverSoftReference = iterator
                    .next();
            if (asyncDownloadObserverSoftReference.get() != null) {
                asyncDownloadObserverSoftReference.get().getDisposable()
                        .dispose();
                FileUtils.deleteFile(asyncDownloadObserverSoftReference.get()
                        .getDownInfo().getSavePath());
            }
        }
        downloadList.clear();
    }

    /**
     * 写入文件
     *
     * @param file
     * @param info
     * @throws IOException
     */
    private void writeCaches(ResponseBody responseBody, File file,
            DownloadInfo info) {
        try {
            RandomAccessFile randomAccessFile = null;
            FileChannel channelOut = null;
            InputStream inputStream = null;
            try {
                if (!file.getParentFile().exists())
                    file.getParentFile().mkdirs();
                long allLength = 0 == info.getCountLength()
                        ? responseBody.contentLength()
                        : info.getReadLength() + responseBody.contentLength();

                inputStream = responseBody.byteStream();
                randomAccessFile = new RandomAccessFile(file, "rwd");
                channelOut = randomAccessFile.getChannel();
                MappedByteBuffer mappedBuffer = channelOut.map(
                        FileChannel.MapMode.READ_WRITE, info.getReadLength(),
                        allLength - info.getReadLength());
                byte[] buffer = new byte[1024 * 4];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    mappedBuffer.put(buffer, 0, len);
                }
            } catch (IOException e) {
                throw new HttpTimeException(e.getMessage());
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (channelOut != null) {
                    channelOut.close();
                }
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            }
        } catch (IOException e) {
            throw new HttpTimeException(e.getMessage());
        }
    }

}


text:
/*
 single path classifier
*/

#ifndef _SC_H_

#define _SC_H_

#define	MAXSCLASSES	100

typedef struct sclassifier *sClassifier; /* single feature-vector classifier */
typedef int		    sClassIndex; /* single feature-vector class index */
typedef struct sclassdope  *sClassDope;	 /* single feature-vector class dope */

struct sclassdope {
	char 		*name;
	sClassIndex	number;
	Vector		average;
	Matrix		sumcov;
	int		nexamples;
};

struct sclassifier {
	int		nfeatures;
	int		nclasses;
	sClassDope	*classdope;

	Vector		cnst;	/* constant term of discrimination function */
	Vector		*w;	/* array of coefficient weights */
	Matrix		invavgcov; /* inverse covariance matrix */
};

sClassifier	sNewClassifier();
sClassifier	sRead();		/* FILE *f */
void		sWrite();		/* FILE *f; sClassifier sc; */
void	 	sFreeClassifier();	/* sc */
void		sAddExample();		/* sc, char *classname; Vector y */
void		sRemoveExample();	/* sc, classname, y */
void		sDoneAdding();		/* sc */
sClassDope	sClassify();		/* sc, y */
sClassDope	sClassifyAD();		/* sc, y, double *ap; double *dp */
sClassDope	sClassNameLookup();	/* sc, classname */
double		MahalanobisDistance();	/* Vector v, u; Matrix sigma */
void		FixClassifier();
void		sDumpClassifier();
void		sDistances();

#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace CloudinaryDotNet.Actions
{
    /// <summary>
    /// Basic parameters of file upload
    /// </summary>
    public class BasicRawUploadParams : BaseParams
    {
        /// <summary>
        /// Either the actual data of the image or an HTTP URL of a public image on the Internet.
        /// </summary>
        public FileDescription File { get; set; }

        /// <summary>
        /// The identifier that is used for accessing the uploaded resource. A randomly generated ID is assigned if not specified.
        /// </summary>
        public string PublicId { get; set; }

        /// <summary>
        /// Tell Cloudinary whether to backup the uploaded file. Overrides the default backup settings of your account.
        /// </summary>
        public bool? Backup { get; set; }

        /// <summary>
        /// Gets or sets privacy mode of the file. Valid values: 'upload' and 'authenticated'. Default: 'upload'.
        /// </summary>
        public string Type { get; set; }

        public virtual ResourceType ResourceType
        {
            get { return Actions.ResourceType.Raw; }
        }
        /// <summary>
        /// Validate object model
        /// </summary>
        public override void Check()
        {
            if (File == null)
                throw new ArgumentException("File must be specified in UploadParams!");

            if (!File.IsRemote && File.Stream == null && string.IsNullOrEmpty(File.FilePath))
                throw new ArgumentException("File is not ready!");

            if (string.IsNullOrEmpty(File.FileName))
                throw new ArgumentException("File name must be specified in UploadParams!");
        }

        public override SortedDictionary<string, object> ToParamsDictionary()
        {
            SortedDictionary<string, object> dict = base.ToParamsDictionary();

            AddParam(dict, "public_id", PublicId);
            AddParam(dict, "type", Type);

            if (Backup.HasValue)
                AddParam(dict, "backup", Backup.Value);

            return dict;
        }
    }

    /// <summary>
    /// Extended Parameters of file upload
    /// </summary>
    public class RawUploadParams : BasicRawUploadParams
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RawUploadParams"/> class.
        /// </summary>
        public RawUploadParams()
        {
            Overwrite = true;
            UniqueFilename = true;
            Context = new StringDictionary();
        }

        /// <summary>
        /// A comma-separated list of tag names to assign to the uploaded image for later group reference.
        /// </summary>
        public string Tags { get; set; }

        /// <summary>
        /// Whether to invalidate CDN cache copies of a previously uploaded image that shares the same public ID. Default: false.
        /// </summary>
        /// <value>
        ///   <c>true</c> to invalidate; otherwise, <c>false</c>.
        /// </value>
        public bool? Invalidate { get; set; }

        /// <summary>
        /// An HTTP header or a list of headers lines for returning as response HTTP headers when delivering the uploaded image to your users. Supported headers: 'Link', 'X-Robots-Tag'. For example 'X-Robots-Tag: noindex'.
        /// </summary>
        public Dictionary<string, string> Headers { get; set; }

        /// <summary>
        /// Whether to use the original file name of the uploaded image if available for the public ID. The file name is normalized and random characters are appended to ensure uniqueness. Default: false.
        /// </summary>
        public bool? UseFilename { get; set; }

        /// <summary>
        /// Only relevant if <see cref="UseFilename"/> is True. When set to false, should not add random characters at the end of the filename that guarantee its uniqueness.
        /// </summary>
        public bool? UniqueFilename { get; set; }

        /// <summary>
        /// Whether to discard the name of the original uploaded file. Relevant when delivering images as attachments (setting the 'flags' transformation parameter to 'attachment'). Default: false.
        /// </summary>
        public bool? DiscardOriginalFilename { get; set; }

        /// <summary>
        /// An HTTP URL to send notification to (a webhook) when the upload is completed.
        /// </summary>
        public string NotificationUrl { get; set; }

        /// <summary>
        /// Allows the resource to behave as if it's of the authenticated 'type' while still using the default 'upload' type in delivery URLs
        /// </summary>
        public string AccessMode { get; set; }

        /// <summary>
        /// Proxy to use when Cloudinary accesses remote folders
        /// </summary>
        public string Proxy { get; set; }

        /// <summary>
        /// Base Folder to use when building the Cloudinary public_id
        /// </summary>
        public string Folder { get; set; }

        /// <summary>
        /// Whether to overwrite existing resources with the same public ID.
        /// </summary>
        public bool? Overwrite { get; set; }

        /// <summary>
        /// Set to "aspose" to automatically convert Office documents to PDF files and other image formats using the Aspose Document Conversion add-on.
        /// </summary>
        public string RawConvert { get; set; }

        /// <summary>
        /// Allows to store a set of key-value pairs together with resource.
        /// </summary>
        public StringDictionary Context { get; set; }

        /// <summary>
        /// Sets a set of allowed formats.
        /// </summary>
        public string[] AllowedFormats { get; set; }

        /// <summary>
        /// Set to "manual" to add the uploaded image to a queue of pending moderation images. Set to "webpurify" to automatically moderate the uploaded image using the WebPurify Image Moderation add-on.
        /// </summary>
        public string Moderation { get; set; }

        /// <summary>
        /// Tells Cloudinary whether to perform the upload request in the background (asynchronously).
        /// </summary>
        public string Async { get; set; }

        /// <summary>
        /// Optional. Pass a list of AccessControlRule parameters
        /// </summary>
        public List<AccessControlRule> AccessControl { get; set; }

        /// <summary>
        /// Maps object model to dictionary of parameters in cloudinary notation.
        /// </summary>
        /// <returns>Sorted dictionary of parameters.</returns>
        public override SortedDictionary<string, object> ToParamsDictionary()
        {
            SortedDictionary<string, object> dict = base.ToParamsDictionary();

            AddParam(dict, "tags", Tags);
            AddParam(dict, "use_filename", UseFilename);
            AddParam(dict, "moderation", Moderation);

            if (UseFilename.HasValue && UseFilename.Value)
                AddParam(dict, "unique_filename", UniqueFilename);

            if (AllowedFormats != null)
                AddParam(dict, "allowed_formats", String.Join(",", AllowedFormats));

            AddParam(dict, "invalidate", Invalidate);
            AddParam(dict, "discard_original_filename", DiscardOriginalFilename);
            AddParam(dict, "notification_url", NotificationUrl);
            AddParam(dict, "access_mode", AccessMode);
            AddParam(dict, "proxy", Proxy);
            AddParam(dict, "folder", Folder);
            AddParam(dict, "raw_convert", RawConvert);
            AddParam(dict, "overwrite", Overwrite);
            AddParam(dict, "async", Async);

            if (Context != null && Context.Count > 0)
            {
                AddParam(dict, Constants.CONTEXT_PARAM_NAME, Utils.SafeJoin("|", Context.SafePairs));
            }

            if (Headers != null && Headers.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in Headers)
                {
                    sb.AppendFormat("{0}: {1}\n", item.Key, item.Value);
                }

                dict.Add("headers", sb.ToString());
            }

            if (AccessControl != null && AccessControl.Count > 0)
            {
                AddParam(dict, "access_control", JsonConvert.SerializeObject(AccessControl));
            }

            return dict;
        }
    }
}


text:
package uk.co.streefland.rhys.finalyearproject.node;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Tests the KeyId class
 */
public class KeyIdTest {

    private KeyId key1 = new KeyId("sdlkfhjsd");
    private KeyId key2 = new KeyId("iuqaghjvfldfsdf");
    private KeyId key3 = new KeyId("sjkld");

    @Test
    public void testHashcode() throws Exception {
        assertEquals(key1.hashCode(), -1478346900);
        assertEquals(key2.hashCode(), -265373120);
        assertEquals(key3.hashCode(), 672281216);
    }

    @Test
    public void testEquals() throws Exception {
        assertTrue(key1.equals(key1));
        assertTrue(key2.equals(key2));
        assertTrue(key3.equals(key3));

        assertFalse(key1.equals(key2));
        assertFalse(key2.equals(key3));
        assertFalse(key3.equals(key1));
    }

    @Test
    public void testKeyIdGeneration() throws Exception {
        String key1Sha = key1.toString();
        String key2Sha = key2.toString();
        String key3Sha = key3.toString();

        assertEquals("696e88685917b4790d10352f2c2b1c28479c3143".toUpperCase(), key1Sha);
        assertEquals("0e4b3ef46e2c70fed23dc492888160b55f646c6c".toUpperCase(), key2Sha);
        assertEquals("fa8732816f63f1c66f8347a1a657959d837f7255".toUpperCase(), key3Sha);
    }

    @Test
    public void testGenerateKeyIdUsingDistance() throws Exception {
        KeyId newKey1 = key1.generateKeyIdUsingDistance(5);
        KeyId newKey2 = key2.generateKeyIdUsingDistance(41);
        KeyId newKey3 = key3.generateKeyIdUsingDistance(89);

        assertEquals(newKey1.getDistance(key1), 5);
        assertEquals(newKey2.getDistance(key2), 41);
        assertEquals(newKey3.getDistance(key3), 89);
    }

    @Test
    public void testGetFirstSetBitLocation() throws Exception {
        assertEquals(key1.getFirstSetBitLocation(), 1);
        assertEquals(key2.getFirstSetBitLocation(), 4);
        assertEquals(key3.getFirstSetBitLocation(), 0);
    }

    @Test
    public void testGetDistance() throws Exception {
        KeyId newKey = key2.generateKeyIdUsingDistance(23);

        assertEquals(key1.getDistance(key2), 159);
        assertEquals(key2.getDistance(key3), 160);
        assertEquals(key3.getDistance(key1), 160);
        assertEquals(key2.getDistance(newKey), 23);
    }

}


text:
  Saint-Élie est
       un village
       situé dans le département de Guyane en Guyane. Elle comptait 423 habitants en 2008.

Si vous pensez demenager à Saint-Élie, vous pourrez aisément trouver une maison à vendre.

Le nombre de logements, à Saint-Élie, se décomposait en 2011 en zero appartements et 186 maisons soit
 un marché plutôt équilibré.

À proximité de Saint-Élie sont situées les communes de
 entre autres.


text:
/**
 * Create a Praesentation.baldr.yml file and insert all media assets in
 * the presentation.
 *
 * @param filePath - The file path of the new created presentation
 *   template.
 */
export declare function generatePresentation(filePath: string): Promise<void>;


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<title>Add Lecture Notes</title>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

		<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
		<link rel="stylesheet" type="text/css" href="style.css">

				<form class="form-horizontal" style="padding: 0 10px;" accept-charset="UTF-8" id="fillthesheet">

				    Subject Name

				      <select class="form-control" name="Subject" id="Subject">
					      <option>Авиационный Английский </option>
						  <option>БЖД</option>
						  <option>БИУС </option>
						  <option>Методы Современных Диагностики </option>
						  <option>Конструкция и Прочность ВС </option>
						  <option>Конструкция и Прочность АД </option>
						  <option>Теория Надежности </option>
						  <option>Теория АД </option>
						  <option>Физ-Культура </option>
						</select>

				    Class No.

				      <input type="number" class="form-control" id="ClassNo" placeholder="Class No." min="0" max="100" step="1" name="Class Number">

						Select a file a type

DOC File

Markdown File

PDF

Audio

Video

							     Link for a DOC

							      <input type="text" class="form-control" id="DOCFileInput" placeholder="http://url-to-the-file" name="Link DOC">

							     Link for MD

							      <input type="text" class="form-control" id="MDFileInput" placeholder="http://url-to-the-file" name="Link MD">

							     Link for a PDF

							      <input type="text" class="form-control" id="PDFFileInput" placeholder="http://url-to-the-file" name="Link PDF">

							     Link for Audio

							      <input type="text" class="form-control" id="AudioFileInput" placeholder="http://url-to-the-file" name="Link AUDIO">

							     Link for a Video

							      <input type="text" class="form-control" id="VideoFileInput" placeholder="http://url-to-the-file" name="Link VIDEO">

				      <button type="submit" class="btn btn-primary">Submit the Note</button>

				</form>

Form has been successfully submitted!

Proudly Hosted on GitHub.

 © 2016


text:
package jiguang.chat;

import cn.jpush.android.service.JCommonService;

public class MyService extends JCommonService {
}


text:
.user-sort:hover {
    cursor: pointer;
    color: orangered;
}