text:
package org.apache.ignite.internal.processors.query.stat;

import java.util.HashMap;
import java.util.Map;

import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2ValueMessage;
import org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2ValueMessageFactory;
import org.apache.ignite.internal.processors.query.stat.config.StatisticsColumnConfiguration;
import org.apache.ignite.internal.processors.query.stat.config.StatisticsObjectConfiguration;
import org.apache.ignite.internal.processors.query.stat.messages.StatisticsColumnData;
import org.apache.ignite.internal.processors.query.stat.messages.StatisticsKeyMessage;
import org.apache.ignite.internal.processors.query.stat.messages.StatisticsObjectData;
import org.apache.ignite.internal.util.typedef.F;
import org.h2.value.Value;

/**
 * Utilities to convert statistics from/to messages, validate configurations with statistics and so on.
 */
public class StatisticsUtils {
    /**
     * Convert ColumnStatistics to StaticColumnData message.
     *
     * @param stat Column statistics to convert.
     * @return Converted stats column data message.
     * @throws IgniteCheckedException In case of errors.
     */
    public static StatisticsColumnData toMessage(ColumnStatistics stat) throws IgniteCheckedException {
        GridH2ValueMessage msgMin = stat.min() == null ? null : GridH2ValueMessageFactory.toMessage(stat.min());
        GridH2ValueMessage msgMax = stat.max() == null ? null : GridH2ValueMessageFactory.toMessage(stat.max());

        return new StatisticsColumnData(msgMin, msgMax, stat.nulls(), stat.distinct(),
            stat.total(), stat.size(), stat.raw(), stat.version(), stat.createdAt());
    }

    /**
     * Convert statistics column data message to column statistics object.
     *
     * @param ctx Kernal context.
     * @param data Statistics column data message to convert.
     * @return ColumnStatistics object.
     * @throws IgniteCheckedException In case of errors.
     */
    public static ColumnStatistics toColumnStatistics(
        GridKernalContext ctx,
        StatisticsColumnData data
    ) throws IgniteCheckedException {
        Value min = (data.min() == null) ? null : data.min().value(ctx);
        Value max = (data.max() == null) ? null : data.max().value(ctx);

        return new ColumnStatistics(min, max, data.nulls(), data.distinct(),
            data.total(), data.size(), data.rawData(), data.version(), data.createdAt());
    }

    /**
     * Build statistics object data from values.
     *
     * @param keyMsg Statistics key.
     * @param type Statistics type.
     * @param stat Object statistics to convert.
     * @return Converted StatsObjectData message.
     * @throws IgniteCheckedException In case of errors.
     */
    public static StatisticsObjectData toObjectData(
        StatisticsKeyMessage keyMsg,
        StatisticsType type,
        ObjectStatisticsImpl stat
    ) throws IgniteCheckedException {
        Map<String, StatisticsColumnData> colData = new HashMap<>(stat.columnsStatistics().size());

        for (Map.Entry<String, ColumnStatistics> ts : stat.columnsStatistics().entrySet())
            colData.put(ts.getKey(), toMessage(ts.getValue()));

        StatisticsObjectData data;

        if (stat instanceof ObjectPartitionStatisticsImpl) {
            ObjectPartitionStatisticsImpl partStats = (ObjectPartitionStatisticsImpl)stat;

            data = new StatisticsObjectData(keyMsg, stat.rowCount(), type, partStats.partId(),
                partStats.updCnt(), colData);
        }
        else
            data = new StatisticsObjectData(keyMsg, stat.rowCount(), type, 0, 0, colData);
        return data;
    }

    /**
     * Build stats key message.
     *
     * @param schema Schema name.
     * @param obj Object name.
     * @param colNames Column names or {@code null}.
     * @return Statistics key message.
     */
    public static StatisticsKeyMessage toMessage(String schema, String obj, String... colNames) {
        return new StatisticsKeyMessage(schema, obj, F.asList(colNames));
    }

    /**
     * Convert StatsObjectData message to ObjectPartitionStatistics.
     *
     * @param ctx Kernal context to use during conversion.
     * @param objData StatsObjectData to convert.
     * @return Converted ObjectPartitionStatistics.
     * @throws IgniteCheckedException In case of errors.
     */
    public static ObjectPartitionStatisticsImpl toObjectPartitionStatistics(
        GridKernalContext ctx,
        StatisticsObjectData objData
    ) throws IgniteCheckedException {
        if (objData == null)
            return null;

        assert objData.type() == StatisticsType.PARTITION;

        Map<String, ColumnStatistics> colNameToStat = new HashMap<>(objData.data().size());

        for (Map.Entry<String, StatisticsColumnData> cs : objData.data().entrySet())
            colNameToStat.put(cs.getKey(), toColumnStatistics(ctx, cs.getValue()));

        return new ObjectPartitionStatisticsImpl(
            objData.partId(),
            objData.rowsCnt(),
            objData.updCnt(),
            colNameToStat
        );
    }

    /**
     * Convert statistics object data message to object statistics impl.
     *
     * @param ctx Kernal context to use during conversion.
     * @param data Statistics object data message to convert.
     * @return Converted object statistics.
     * @throws IgniteCheckedException  In case of errors.
     */
    public static ObjectStatisticsImpl toObjectStatistics(
        GridKernalContext ctx,
        StatisticsObjectData data
    ) throws IgniteCheckedException {
        Map<String, ColumnStatistics> colNameToStat = new HashMap<>(data.data().size());

        for (Map.Entry<String, StatisticsColumnData> cs : data.data().entrySet())
            colNameToStat.put(cs.getKey(), toColumnStatistics(ctx, cs.getValue()));

        return new ObjectStatisticsImpl(data.rowsCnt(), colNameToStat);
    }

    /**
     * Create statistics target from statistics key message.
     *
     * @param msg Source statistics key message;
     * @return StatisticsTarget.
     */
    public static StatisticsTarget statisticsTarget(StatisticsKeyMessage msg) {
        String[] cols = (msg.colNames() == null) ? null : msg.colNames().toArray(new String[0]);
        return new StatisticsTarget(msg.schema(), msg.obj(), cols);
    }

    /**
     * Test if specified statistics are fit to all required versions.
     * It means that specified statistics contains all columns with at least versions
     * from specified map.
     *
     * @param stat Statistics to check. Can be {@code null}.
     * @param versions Map of column name to required version.
     * @return positive value if statistics versions bigger than specified in versions map,
     *         negative value if statistics version smaller than specified in version map,
     *         zero it they are equals.
     */
    public static int compareVersions(
        ObjectStatisticsImpl stat,
        Map<String, Long> versions
    ) {
        if (stat == null)
            return -1;

        for (Map.Entry<String, Long> version : versions.entrySet()) {
            ColumnStatistics colStat = stat.columnsStatistics().get(version.getKey());

            if (colStat == null || colStat.version() < version.getValue())
                return -1;

            if (colStat.version() > version.getValue())
                return 1;
        }

        return 0;
    }

    /**
     * Test if secified statistics configuration is fit to all required versions.
     * It means that specified statistics configuraion contains all columns with at least versions from specified map.
     *
     * @param cfg Statistics configuraion to check. Can be {@code null}.
     * @param versions Map of column name to required version.
     * @return {@code true} if it is, {@code talse} otherwise.
     */
    public static int compareVersions(
        StatisticsObjectConfiguration cfg,
        Map<String, Long> versions
    ) {
        if (cfg == null)
            return -1;

        for (Map.Entry<String, Long> colVersion : versions.entrySet()) {
            StatisticsColumnConfiguration colCfg = cfg.columns().get(colVersion.getKey());

            if (colCfg == null || colCfg.version() < colVersion.getValue())
                return -1;

            if (colCfg.version() > colVersion.getValue())
                return 1;
        }

        return 0;
    }
}


text:
// ReSharper disable All
using static Soothsharp.Contracts.Contract;

namespace Soothsharp.Examples
{
    class A
    {
        public static int Maximum(int a, int b)
        {
            Ensures(a > b ? IntegerResult == a : IntegerResult == b);
            return a;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
var express = require('express')
 ,  app = express()
 ,  path = require('path')
 ,  request = require('request');

 app.use(express.static(__dirname + '/public'));
 app.use('/bower_components',  express.static(__dirname + '/bower_components'));

app.get('/', function(req, res) {
	res.sendFile(path.join(__dirname, 'index.html'));
});

var users = {
	get: function(result) {
		return new Promise(function(resolve, reject) {
			request("http://api.randomuser.me/?format=json&results="+result, function(error, response, body) {
				if (!error && response.statusCode == 200) {
					resolve(response);
				} else {
					reject(error.message);
				}
			});
		});
	}
}

function handleFulfilled(data, delay) {
	console.log('got data from external API! Promise fulfilled.');

	setTimeout(function() {
		res.json(data);
	}, delay);
}

function handleRejected(error) {
	console.log('Promise rejected.');
	console.log(error.message);
	res.json(error);
}

app.get('/users', function(req, res) {
	if (Promise) {
		console.log('Promise found');

		// Async code here
		var promise1 = users.get(2)
		  , promise2 = users.get(3)
			, promise3 = users.get(1);

		promise1.then( handleFulfilled(data, 3000), handleRejected(error) );
		promise2.then( handleFulfilled(data, 1000), handleRejected(error) );
		promise3.then( handleFulfilled(data, 500), handleRejected(error) );

});

var server = app.listen(3000, function() {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});


text:
import {
  SCOPE_ARROW,
  SCOPE_DIRECT_SUPER,
  SCOPE_FUNCTION,
  SCOPE_SIMPLE_CATCH,
  SCOPE_SUPER,
  SCOPE_PROGRAM,
  SCOPE_VAR,
  SCOPE_CLASS,
  SCOPE_STATIC_BLOCK,
  BIND_SCOPE_FUNCTION,
  BIND_SCOPE_VAR,
  BIND_SCOPE_LEXICAL,
  BIND_KIND_VALUE,
  type ScopeFlags,
  type BindingTypes,
} from "./scopeflags";
import type { Position } from "./location";
import type * as N from "../types";
import { Errors } from "../parse-error";
import type Tokenizer from "../tokenizer";

// Start an AST node, attaching a start offset.
export class Scope {
  declare flags: ScopeFlags;
  // A set of var-declared names in the current lexical scope
  var: Set<string> = new Set();
  // A set of lexically-declared names in the current lexical scope
  lexical: Set<string> = new Set();
  // A set of lexically-declared FunctionDeclaration names in the current lexical scope
  functions: Set<string> = new Set();

  constructor(flags: ScopeFlags) {
    this.flags = flags;
  }
}

// The functions in this module keep track of declared variables in the
// current scope in order to detect duplicate variable names.
export default class ScopeHandler<IScope extends Scope = Scope> {
  parser: Tokenizer;
  scopeStack: Array<IScope> = [];
  inModule: boolean;
  undefinedExports: Map<string, Position> = new Map();

  constructor(parser: Tokenizer, inModule: boolean) {
    this.parser = parser;
    this.inModule = inModule;
  }

  get inTopLevel() {
    return (this.currentScope().flags & SCOPE_PROGRAM) > 0;
  }
  get inFunction() {
    return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  }
  get allowSuper() {
    return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  }
  get allowDirectSuper() {
    return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  }
  get inClass() {
    return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  }
  get inClassAndNotInNonArrowFunction() {
    const flags = this.currentThisScopeFlags();
    return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  }
  get inStaticBlock() {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const { flags } = this.scopeStack[i];
      if (flags & SCOPE_STATIC_BLOCK) {
        return true;
      }
      if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
        // function body, module body, class property initializers
        return false;
      }
    }
  }
  get inNonArrowFunction() {
    return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  }
  get treatFunctionsAsVar() {
    return this.treatFunctionsAsVarInScope(this.currentScope());
  }

  createScope(flags: ScopeFlags): Scope {
    return new Scope(flags);
  }

  enter(flags: ScopeFlags) {
    /*:: +createScope: (flags: ScopeFlags) => IScope; */
    // @ts-expect-error This method will be overwritten by subclasses
    this.scopeStack.push(this.createScope(flags));
  }

  exit(): ScopeFlags {
    const scope = this.scopeStack.pop();
    return scope.flags;
  }

  // The spec says:
  // > At the top level of a function, or script, function declarations are
  // > treated like var declarations rather than like lexical declarations.
  treatFunctionsAsVarInScope(scope: IScope): boolean {
    return !!(
      scope.flags & (SCOPE_FUNCTION | SCOPE_STATIC_BLOCK) ||
      (!this.parser.inModule && scope.flags & SCOPE_PROGRAM)
    );
  }

  declareName(name: string, bindingType: BindingTypes, loc: Position) {
    let scope = this.currentScope();
    if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
      this.checkRedeclarationInScope(scope, name, bindingType, loc);

      if (bindingType & BIND_SCOPE_FUNCTION) {
        scope.functions.add(name);
      } else {
        scope.lexical.add(name);
      }

      if (bindingType & BIND_SCOPE_LEXICAL) {
        this.maybeExportDefined(scope, name);
      }
    } else if (bindingType & BIND_SCOPE_VAR) {
      for (let i = this.scopeStack.length - 1; i >= 0; --i) {
        scope = this.scopeStack[i];
        this.checkRedeclarationInScope(scope, name, bindingType, loc);
        scope.var.add(name);
        this.maybeExportDefined(scope, name);

        if (scope.flags & SCOPE_VAR) break;
      }
    }
    if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
      this.undefinedExports.delete(name);
    }
  }

  maybeExportDefined(scope: IScope, name: string) {
    if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
      this.undefinedExports.delete(name);
    }
  }

  checkRedeclarationInScope(
    scope: IScope,
    name: string,
    bindingType: BindingTypes,
    loc: Position,
  ) {
    if (this.isRedeclaredInScope(scope, name, bindingType)) {
      this.parser.raise(Errors.VarRedeclaration, {
        at: loc,
        identifierName: name,
      });
    }
  }

  isRedeclaredInScope(
    scope: IScope,
    name: string,
    bindingType: BindingTypes,
  ): boolean {
    if (!(bindingType & BIND_KIND_VALUE)) return false;

    if (bindingType & BIND_SCOPE_LEXICAL) {
      return (
        scope.lexical.has(name) ||
        scope.functions.has(name) ||
        scope.var.has(name)
      );
    }

    if (bindingType & BIND_SCOPE_FUNCTION) {
      return (
        scope.lexical.has(name) ||
        (!this.treatFunctionsAsVarInScope(scope) && scope.var.has(name))
      );
    }

    return (
      (scope.lexical.has(name) &&
        !(
          scope.flags & SCOPE_SIMPLE_CATCH &&
          scope.lexical.values().next().value === name
        )) ||
      (!this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name))
    );
  }

  checkLocalExport(id: N.Identifier) {
    const { name } = id;
    const topLevelScope = this.scopeStack[0];
    if (
      !topLevelScope.lexical.has(name) &&
      !topLevelScope.var.has(name) &&
      // In strict mode, scope.functions will always be empty.
      // Modules are strict by default, but the `scriptMode` option
      // can overwrite this behavior.
      !topLevelScope.functions.has(name)
    ) {
      this.undefinedExports.set(name, id.loc.start);
    }
  }

  currentScope(): IScope {
    return this.scopeStack[this.scopeStack.length - 1];
  }

  currentVarScopeFlags(): ScopeFlags {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const { flags } = this.scopeStack[i];
      if (flags & SCOPE_VAR) {
        return flags;
      }
    }
  }

  // Could be useful for `arguments`, `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  currentThisScopeFlags(): ScopeFlags {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const { flags } = this.scopeStack[i];
      if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
        return flags;
      }
    }
  }
}


text:
namespace ash {

class AssistantAlarmTimerModel;
class AssistantAlarmTimerModelObserver;
class AssistantNotificationModel;
class AssistantNotificationModelObserver;
enum class AssistantButtonId;

namespace assistant {
namespace util {
enum class DeepLinkType;
}  // namespace util
}  // namespace assistant

class COMPONENT_EXPORT(ASSISTANT_UI) AssistantViewDelegateObserver
    : public base::CheckedObserver {
 public:
  using AssistantSuggestion = chromeos::assistant::mojom::AssistantSuggestion;

  // Invoked when the dialog plate button identified by |id| is pressed.
  virtual void OnDialogPlateButtonPressed(AssistantButtonId id) {}

  // Invoked when the dialog plate contents have been committed.
  virtual void OnDialogPlateContentsCommitted(const std::string& text) {}

  // Invoked when the host view's visibility changed.
  virtual void OnHostViewVisibilityChanged(bool visible) {}

  // Invoked when the opt in button is pressed.
  virtual void OnOptInButtonPressed() {}

  // Invoked when the proactive suggestions close button is pressed.
  virtual void OnProactiveSuggestionsCloseButtonPressed() {}

  // Invoked when the hover state of the proactive suggestions view is changed.
  virtual void OnProactiveSuggestionsViewHoverChanged(bool is_hovering) {}

  // Invoked when the proactive suggestions view is pressed.
  virtual void OnProactiveSuggestionsViewPressed() {}

  // Invoked when a suggestion chip is pressed.
  virtual void OnSuggestionChipPressed(const AssistantSuggestion* suggestion) {}
};

// A delegate of views in assistant/ui that handles views related actions e.g.
// get models for the views, adding observers, closing the views, opening urls,
// etc.
class COMPONENT_EXPORT(ASSISTANT_UI) AssistantViewDelegate {
 public:
  using AssistantSuggestion = chromeos::assistant::mojom::AssistantSuggestion;

  virtual ~AssistantViewDelegate() {}

  // Gets the alarm/timer model.
  virtual const AssistantAlarmTimerModel* GetAlarmTimerModel() const = 0;

  // Gets the notification model.
  virtual const AssistantNotificationModel* GetNotificationModel() const = 0;

  // Adds/removes the specified view delegate observer.
  virtual void AddObserver(AssistantViewDelegateObserver* observer) = 0;
  virtual void RemoveObserver(AssistantViewDelegateObserver* observer) = 0;

  // Adds/removes the specified alarm/timer model observer.
  virtual void AddAlarmTimerModelObserver(
      AssistantAlarmTimerModelObserver* observer) = 0;
  virtual void RemoveAlarmTimerModelObserver(
      AssistantAlarmTimerModelObserver* observer) = 0;

  // Adds/removes the notification model observer.
  virtual void AddNotificationModelObserver(
      AssistantNotificationModelObserver* observer) = 0;
  virtual void RemoveNotificationModelObserver(
      AssistantNotificationModelObserver* observer) = 0;

  // Downloads the image found at the specified |url|. On completion, the
  // supplied |callback| will be run with the downloaded image. If the download
  // attempt is unsuccessful, a NULL image is returned.
  virtual void DownloadImage(const GURL& url,
                             ImageDownloader::DownloadCallback callback) = 0;

  // Returns the cursor_manager.
  virtual ::wm::CursorManager* GetCursorManager() = 0;

  // Returns the root window for the specified |display_id|.
  virtual aura::Window* GetRootWindowForDisplayId(int64_t display_id) = 0;

  // Returns the root window that newly created windows should be added to.
  virtual aura::Window* GetRootWindowForNewWindows() = 0;

  // Returns true if in tablet mode.
  virtual bool IsTabletMode() const = 0;

  // Invoked when the dialog plate button identified by |id| is pressed.
  virtual void OnDialogPlateButtonPressed(AssistantButtonId id) = 0;

  // Invoked when the dialog plate contents have been committed.
  virtual void OnDialogPlateContentsCommitted(const std::string& text) = 0;

  // Invoked when the host view's visibility changed.
  virtual void OnHostViewVisibilityChanged(bool visible) = 0;

  // Invoked when an in-Assistant notification button is pressed.
  virtual void OnNotificationButtonPressed(const std::string& notification_id,
                                           int notification_button_index) = 0;

  // Invoked when the opt in button is pressed.
  virtual void OnOptInButtonPressed() {}

  // Invoked when the proactive suggestions close button is pressed.
  virtual void OnProactiveSuggestionsCloseButtonPressed() {}

  // Invoked when the hover state of the proactive suggestions view is changed.
  virtual void OnProactiveSuggestionsViewHoverChanged(bool is_hovering) {}

  // Invoked when the proactive suggestions view is pressed.
  virtual void OnProactiveSuggestionsViewPressed() {}

  // Invoked when suggestion chip is pressed.
  virtual void OnSuggestionChipPressed(
      const AssistantSuggestion* suggestion) = 0;
};

}  // namespace ash

#endif  // ASH_ASSISTANT_UI_ASSISTANT_VIEW_DELEGATE_H_


text:
package org.apache.skywalking.apm.plugin.feign.http.v9;

import feign.RequestTemplate;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.MethodInterceptResult;

import java.lang.reflect.Method;

/**
 * {@link PathVarInterceptor} intercept the Feign RequestTemplate args resolve ;
 */
public class PathVarInterceptor implements InstanceMethodsAroundInterceptor {

    static final ThreadLocal<FeignResolvedURL> URL_CONTEXT = new ThreadLocal<FeignResolvedURL>();

    /**
     * Get the {@link RequestTemplate#url()} before feign.ReflectiveFeign.BuildTemplateByResolvingArgs#resolve(Object[],
     * RequestTemplate, Map) put it into the {@link PathVarInterceptor#URL_CONTEXT}
     *
     * @param method intercept method
     * @param result change this result, if you want to truncate the method.
     */
    @Override
    public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        MethodInterceptResult result) {
        RequestTemplate template = (RequestTemplate) allArguments[1];
        URL_CONTEXT.set(new FeignResolvedURL(template.url()));
    }

    /**
     * Get the resolved {@link RequestTemplate#url()} after feign.ReflectiveFeign.BuildTemplateByResolvingArgs#resolve(Object[],
     * RequestTemplate, Map) put it into the {@link PathVarInterceptor#URL_CONTEXT}
     *
     * @param method intercept method
     * @param ret    the method's original return value.
     * @return result without change
     */
    @Override
    public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        Object ret) {
        RequestTemplate resolvedTemplate = (RequestTemplate) ret;
        URL_CONTEXT.get().setUrl(resolvedTemplate.url());
        return ret;
    }

    @Override
    public void handleMethodException(EnhancedInstance objInst, Method method, Object[] allArguments,
        Class<?>[] argumentsTypes, Throwable t) {
        if (URL_CONTEXT.get() != null) {
            URL_CONTEXT.remove();
        }
    }
}


text:
package org.onecmdb.facade;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.onecmdb.dto.ListFilter;
import org.onecmdb.dto.PageSearch;
import org.onecmdb.dto.RestResult;
import org.springframework.data.domain.Page;

import javax.ws.rs.*;
import java.util.List;

/**
 * Created by X on 2017/4/17.
 */
public interface DBRestService<T> {
    @POST
    @Path("/{version}/{name}/list")
    @ApiOperation("列表")
    RestResult<List<T>> list(ListFilter listFilter);

    @POST
    @Path("/{version}/{name}/page")
    @ApiOperation("分页")
    RestResult<Page<T>> page(PageSearch pageSearch);

    @GET
    @Path("/{version}/{name}/{id}")
    @ApiOperation("详细信息")
    RestResult<T> detail(@ApiParam("id") @PathParam("id") Long id);

    @POST
    @Path("/{version}/{name}")
    @ApiOperation("添加/修改")
    RestResult<T> create(T entity);

    @DELETE
    @Path("/{version}/{name}/{id}")
    @ApiOperation("删除")
    RestResult<String> delete(@ApiParam("id") @PathParam("id") Long id);

    @POST
    @Path("/{version}/{name}/{method}")
    @ApiOperation("其他接口")
    RestResult<T> method(T entity);
}


text:
package com.netflix.curator.framework.recipes.atomic;

public interface DistributedAtomicNumber<T>
{
    /**
     * Returns the current value of the counter. NOTE: if the value has never been set,
     * 0 is returned.
     *
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>     get() throws Exception;

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     * Remember to always check {@link AtomicValue#succeeded()}.
     *
     *
     * @param expectedValue the expected value
     * @param newValue the new value for the counter
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    compareAndSet(T expectedValue, T newValue) throws Exception;

    /**
     * Attempt to atomically set the value to the given value. Remember to always
     * check {@link AtomicValue#succeeded()}.
     *
     * @param newValue the value to set
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    trySet(T newValue) throws Exception;

    /**
     * Forcibly sets the value of the counter without any guarantees of atomicity.
     *
     * @param newValue the new value
     * @throws Exception ZooKeeper errors
     */
    public void              forceSet(T newValue) throws Exception;

    /**
     * Add 1 to the current value and return the new value information. Remember to always
     * check {@link AtomicValue#succeeded()}.
     *
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    increment() throws Exception;

    /**
     * Subtract 1 from the current value and return the new value information. Remember to always
     * check {@link AtomicValue#succeeded()}.
     *
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    decrement() throws Exception;

    /**
     * Add delta to the current value and return the new value information. Remember to always
     * check {@link AtomicValue#succeeded()}.
     *
     * @param delta amount to add
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    add(T delta) throws Exception;

    /**
     * Subtract delta from the current value and return the new value information. Remember to always
     * check {@link AtomicValue#succeeded()}.
     *
     * @param delta amount to subtract
     * @return value info
     * @throws Exception ZooKeeper errors
     */
    public AtomicValue<T>    subtract(T delta) throws Exception;
}


text:
/**
 * @file
 * mpeg audio declarations for both encoder and decoder.
 */

#ifndef AVCODEC_MPEGAUDIO_H
#define AVCODEC_MPEGAUDIO_H

#ifndef CONFIG_FLOAT
#   define CONFIG_FLOAT 0
#endif

#include "avcodec.h"
#include "get_bits.h"
#include "dsputil.h"
#include "fft.h"

#define CONFIG_AUDIO_NONSHORT 0

/* max frame size, in samples */
#define MPA_FRAME_SIZE 1152

/* max compressed frame size */
#define MPA_MAX_CODED_FRAME_SIZE 1792

#define MPA_MAX_CHANNELS 2

#define SBLIMIT 32 /* number of subbands */

#define MPA_STEREO  0
#define MPA_JSTEREO 1
#define MPA_DUAL    2
#define MPA_MONO    3

/* header + layer + bitrate + freq + lsf/mpeg25 */
#define SAME_HEADER_MASK \
   (0xffe00000 | (3 << 17) | (0xf << 12) | (3 << 10) | (3 << 19))

#define MP3_MASK 0xFFFE0CCF

#if CONFIG_MPEGAUDIO_HP
#define FRAC_BITS   23   /* fractional bits for sb_samples and dct */
#define WFRAC_BITS  16   /* fractional bits for window */
#else
#define FRAC_BITS   15   /* fractional bits for sb_samples and dct */
#define WFRAC_BITS  14   /* fractional bits for window */
#endif

#define FRAC_ONE    (1 << FRAC_BITS)

#define FIX(a)   ((int)((a) * FRAC_ONE))

#if CONFIG_FLOAT
typedef float OUT_INT;
#define OUT_FMT SAMPLE_FMT_FLT
#elif CONFIG_MPEGAUDIO_HP && CONFIG_AUDIO_NONSHORT
typedef int32_t OUT_INT;
#define OUT_MAX INT32_MAX
#define OUT_MIN INT32_MIN
#define OUT_SHIFT (WFRAC_BITS + FRAC_BITS - 31)
#define OUT_FMT SAMPLE_FMT_S32
#else
typedef int16_t OUT_INT;
#define OUT_MAX INT16_MAX
#define OUT_MIN INT16_MIN
#define OUT_SHIFT (WFRAC_BITS + FRAC_BITS - 15)
#define OUT_FMT SAMPLE_FMT_S16
#endif

#if CONFIG_FLOAT
#   define INTFLOAT float
typedef float MPA_INT;
#elif FRAC_BITS <= 15
#   define INTFLOAT int
typedef int16_t MPA_INT;
#else
#   define INTFLOAT int
typedef int32_t MPA_INT;
#endif

#define BACKSTEP_SIZE 512
#define EXTRABYTES 24

/* layer 3 "granule" */
typedef struct GranuleDef {
    uint8_t scfsi;
    int part2_3_length;
    int big_values;
    int global_gain;
    int scalefac_compress;
    uint8_t block_type;
    uint8_t switch_point;
    int table_select[3];
    int subblock_gain[3];
    uint8_t scalefac_scale;
    uint8_t count1table_select;
    int region_size[3]; /* number of huffman codes in each region */
    int preflag;
    int short_start, long_end; /* long/short band indexes */
    uint8_t scale_factors[40];
    INTFLOAT sb_hybrid[SBLIMIT * 18]; /* 576 samples */
} GranuleDef;

#define MPA_DECODE_HEADER \
    int frame_size; \
    int error_protection; \
    int layer; \
    int sample_rate; \
    int sample_rate_index; /* between 0 and 8 */ \
    int bit_rate; \
    int nb_channels; \
    int mode; \
    int mode_ext; \
    int lsf;

typedef struct MPADecodeHeader {
  MPA_DECODE_HEADER
} MPADecodeHeader;

typedef struct MPADecodeContext {
    MPA_DECODE_HEADER
    uint8_t last_buf[2*BACKSTEP_SIZE + EXTRABYTES];
    int last_buf_size;
    /* next header (used in free format parsing) */
    uint32_t free_format_next_header;
    GetBitContext gb;
    GetBitContext in_gb;
    DECLARE_ALIGNED(16, MPA_INT, synth_buf)[MPA_MAX_CHANNELS][512 * 2];
    int synth_buf_offset[MPA_MAX_CHANNELS];
    DECLARE_ALIGNED(16, INTFLOAT, sb_samples)[MPA_MAX_CHANNELS][36][SBLIMIT];
    INTFLOAT mdct_buf[MPA_MAX_CHANNELS][SBLIMIT * 18]; /* previous samples, for layer 3 MDCT */
    GranuleDef granules[2][2]; /* Used in Layer 3 */
#ifdef DEBUG
    int frame_count;
#endif
    int adu_mode; ///< 0 for standard mp3, 1 for adu formatted mp3
    int dither_state;
    int error_recognition;
    AVCodecContext* avctx;
#if CONFIG_FLOAT
    DCTContext dct;
#endif
    void (*apply_window_mp3)(MPA_INT *synth_buf, MPA_INT *window,
                             int *dither_state, OUT_INT *samples, int incr);
} MPADecodeContext;

/* layer 3 huffman tables */
typedef struct HuffTable {
    int xsize;
    const uint8_t *bits;
    const uint16_t *codes;
} HuffTable;

int ff_mpa_l2_select_table(int bitrate, int nb_channels, int freq, int lsf);
int ff_mpa_decode_header(AVCodecContext *avctx, uint32_t head, int *sample_rate, int *channels, int *frame_size, int *bitrate);
extern MPA_INT ff_mpa_synth_window[];
void ff_mpa_synth_init(MPA_INT *window);
void ff_mpa_synth_filter(MPA_INT *synth_buf_ptr, int *synth_buf_offset,
                         MPA_INT *window, int *dither_state,
                         OUT_INT *samples, int incr,
                         INTFLOAT sb_samples[SBLIMIT]);

void ff_mpa_synth_init_float(MPA_INT *window);
void ff_mpa_synth_filter_float(MPADecodeContext *s,
                         MPA_INT *synth_buf_ptr, int *synth_buf_offset,
                         MPA_INT *window, int *dither_state,
                         OUT_INT *samples, int incr,
                         INTFLOAT sb_samples[SBLIMIT]);

void ff_mpegaudiodec_init_mmx(MPADecodeContext *s);
void ff_mpegaudiodec_init_altivec(MPADecodeContext *s);

/* fast header check for resync */
static inline int ff_mpa_check_header(uint32_t header){
    /* header */
    if ((header & 0xffe00000) != 0xffe00000)
        return -1;
    /* layer check */
    if ((header & (3<<17)) == 0)
        return -1;
    /* bit rate */
    if ((header & (0xf<<12)) == 0xf<<12)
        return -1;
    /* frequency */
    if ((header & (3<<10)) == 3<<10)
        return -1;
    return 0;
}

#endif /* AVCODEC_MPEGAUDIO_H */


text:
import {
  DISCOVER_SUCCESS,
  DISCOVER_LOADING,
  DISCOVER_ERROR
} from "../constants";

export const discover = {
  result: [],
  isLoading: false,
  hasError: false
};

export default (state = discover, action) => {
  switch (action.type) {
    case DISCOVER_SUCCESS:
      return { ...state, isLoading: false, result: action.result };
    case DISCOVER_LOADING:
      return { ...state, isLoading: true };
    case DISCOVER_ERROR:
      return { ...state, isLoading: false, hasError: true };
    default:
      return state;
  }
};


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

public static class Messages
{
    static Dictionary<int, Message> m_Dictionary = new Dictionary<int, Message>();
    public static Message[] All
    {
        get
        {
            Message[] t_Messages = new Message[m_Dictionary.Count];
            m_Dictionary.Values.CopyTo(t_Messages, 0);
            return t_Messages;
        }
    }

    public static Message[] Unread
    {
        get
        {
            return Array.FindAll(Messages.All, m => m.Read == false);
        }
    }

    public static void MarkAllAsRead()
    {

        if (Info.Player == null)
            return;

        HTTP.Request(Settings.FormAjaxURL("mark_messages_read.php"), delegate (WWW a_Request)
        {
            if (a_Request.text == "true")
            {
                Messages.Reset();
            }
            else Error.Show(a_Request.text);
        }, false);
    }

    public static void Reset()
    {
        m_Setup = false;
        m_Dictionary.Clear();
    }

    static bool m_Setup = false;
    public static void Insert(JSONArray a_Array)
    {
        if (m_Setup)
            return;

        foreach(JSONNode t_Node in a_Array)
        {
            DateTime t_Time = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddSeconds(t_Node["time"].AsInt);
            string t_Message = t_Node["message"].Value;

            t_Message = t_Message.Replace("{CashSign}", Settings.CashSign.ToString());

            m_Dictionary.Add(t_Node["id"].AsInt, new Message(t_Node["id"].AsInt, t_Node["title"].Value, t_Message, t_Node["unread"].AsBool == false, t_Time));
        }

        m_Setup = true;
    }
}


text:
using namespace std;
using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solver;
using ceres::Solve;

struct CostFunctor {
	template<typename T> bool operator()(const T* const x,  T* residual) const {
		residual[0] = T(10) - x[0];
		return true;
	}
};

int main(int argc, char** argv) {

	google::InitGoogleLogging(argv[0]);

	double initial_x = 0.5;
	double x = initial_x;

	// BUild the problem
	Problem problem;

	// Set up the only cost function (also knowns as residual). This uses auto-diff to obtain the derivative (jacobian)
	CostFunction* cost_function = new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
	problem.AddResidualBlock(cost_function, NULL, &x);

	// Run the solver
	Solver::Options options;
	options.linear_solver_type = ceres::DENSE_QR;
	options.minimizer_progress_to_stdout = true;

	Solver::Summary summary;
	Solve(options, &problem, &summary);

	cout << summary.BriefReport() << endl;
	cout << "x: " << initial_x << " -> " << x << endl;

	system("pause");
}


text:
# Binary Tree Inorder Traversal

Given a binary tree, return the inorder traversal of its nodes' values.

**Example:**

> **Input:** `[1,null,2,3]`
>
>     1
>      \
>       2
>      /
>     3
>
> **Output:** `[1,3,2]`

**Follow up:** Recursive solution is trivial, could you do it iteratively?

## Solutions Sketch

### C++
```C++
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {

    }
};
```

### Java
```Java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {

    }
}
```

### Python
```Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
```

### C
```C
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize) {

}
```

### C#
```C#
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<int> InorderTraversal(TreeNode root) {

    }
}
```

### JavaScript
```JavaScript
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {

};
```

### Ruby
```Ruby
# Definition for a binary tree node.
# class TreeNode
#     attr_accessor :val, :left, :right
#     def initialize(val)
#         @val = val
#         @left, @right = nil, nil
#     end
# end

# @param {TreeNode} root
# @return {Integer[]}
def inorder_traversal(root)

end
```


text:
mixpanel_proxy
==============

A service which accepts Mixpanel stats via UDP and delivers them to Mixpanel asynchronously. No job queue necessary.

Install
-------

    $ git clone git://github.com/powdahound/mixpanel_proxy.git
    $ cd mixpanel_proxy
    $ python setup.py install

Run
---

Testing:

    $ twistd -n mixpanel_proxy --verbose

Daemon:

    $ twistd --pidfile=mixpanel_proxy.pid --logfile=mixpanel_proxy.log mixpanel_proxy

Use
---

Send a UDP datagram to the service (defaults to port 8067) containing the full JSON blob expected by the Mixpanel API. Code examples provided in the examples/ directory.


text:
/*
 * ProtoWritable.java
 *
 * Created on 1 September 2009, 11:06
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package com.eas.proto;

/**
 * Provides interface for classes to save their instances in a platypus protocl streams.
 *
 * @author pl
 */
public interface ProtoWritable
{
    void writeAsTag(int tag, ProtoWriter writer);
}


text:
require 'spec_helper'

describe VideoSegment do
  describe "#partition" do

    it "should create two segments for a single video" do
      video = Factory.create(:video_95)

      lambda{
        VideoSegment.partition(video)
      }.should change(VideoSegment, :count).by(2)
    end

    it "should create only a single segment for a 60 second video" do
      video = Factory.create(:video_60)

      lambda{
        VideoSegment.partition(video)
      }.should change(VideoSegment, :count).by(1)
    end

  end
end


text:
module IMS::LTI::Models
  module ContentItems
    require_relative 'content_items/content_item'
    require_relative 'content_items/file_item'
    require_relative 'content_items/lti_link_item'
  end
end


text:
from typing import Iterator

import pytest
from pytest_mock import MockFixture
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.session import Session

from superset.app import SupersetApp
from superset.initialization import SupersetAppInitializer

@pytest.fixture()
def session() -> Iterator[Session]:
    """
    Create an in-memory SQLite session to test models.
    """
    engine = create_engine("sqlite://")
    Session_ = sessionmaker(bind=engine)  # pylint: disable=invalid-name
    in_memory_session = Session_()

    # flask calls session.remove()
    in_memory_session.remove = lambda: None

    yield in_memory_session

@pytest.fixture
def app(mocker: MockFixture, session: Session) -> Iterator[SupersetApp]:
    """
    A fixture that generates a Superset app.
    """
    app = SupersetApp(__name__)

    app.config.from_object("superset.config")
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
    app.config["FAB_ADD_SECURITY_VIEWS"] = False

    app_initializer = app.config.get("APP_INITIALIZER", SupersetAppInitializer)(app)
    app_initializer.init_app()

    # patch session
    mocker.patch(
        "superset.security.SupersetSecurityManager.get_session", return_value=session,
    )
    mocker.patch("superset.db.session", session)

    yield app

@pytest.fixture
def app_context(app: SupersetApp) -> Iterator[None]:
    """
    A fixture that yields and application context.
    """
    with app.app_context():
        yield


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Content.Persistence;

namespace Kooboo.CMS.Content.Models
{
    /// <summary>
    /// 可持久化对象的扩展方法
    /// </summary>
    public static class IPersistableExtensions
    {
        /// <summary>
        /// 用这个方法取得完整的对象
        /// 相当于Provider.Get(id)
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <returns></returns>
        public static Repository AsActual(this Repository repository)
        {
            if (repository.IsDummy)
            {
                repository = Providers.RepositoryProvider.Get(repository);
            }
            return repository;
        }
        /// <summary>
        /// 用这个方法取得完整的对象
        /// 相当于Provider.Get(id)
        /// </summary>
        /// <param name="schema">The schema.</param>
        /// <returns></returns>
        public static Schema AsActual(this Schema schema)
        {
            if (schema.IsDummy)
            {
                schema = Providers.DefaultProviderFactory.GetProvider<ISchemaProvider>().Get(schema);
            }
            return schema;
        }
        /// <summary>
        /// 用这个方法取得完整的对象
        /// 相当于Provider.Get(id)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="folder">The folder.</param>
        /// <returns></returns>
        public static T AsActual<T>(this T folder)
            where T : Folder
        {
            if (folder.IsDummy)
            {
                if (folder is MediaFolder)
                {
                    folder.IsDummy = false;
                    return folder;
                }
                else
                {
                    folder = Providers.DefaultProviderFactory.GetProvider<ITextFolderProvider>().Get((TextFolder)(object)folder) as T;
                }

            }
            return folder;
        }

        /// <summary>
        /// 用这个方法取得完整的对象
        /// 相当于Provider.Get(id)
        /// </summary>
        /// <param name="workflow">The workflow.</param>
        /// <returns></returns>
        public static Workflow AsActual(this Workflow workflow)
        {
            return Providers.DefaultProviderFactory.GetProvider<IWorkflowProvider>().Get(workflow);
        }
    }
}