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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Generic Inliner: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Generic Inliner
    1.0.0.0

A base for making inliners for .NET deobfuscation

ClientPlugin

Providers

Identifier

ClientPlugin.Providers.Identifier Member List

This is the complete list of members for ClientPlugin.Providers.Identifier, including all inherited members.

FindWhereAttributes(string attribRegex)	ClientPlugin.Providers.Identifier

FindWhereOpCodes(params string[] opRegexes)	ClientPlugin.Providers.Identifier

FindWhereOpCodes(string opCodeRegex)	ClientPlugin.Providers.Identifier

FindWhereOperands(params string[] opRegexes)	ClientPlugin.Providers.Identifier

FindWhereOperands(string operandRegex)	ClientPlugin.Providers.Identifier

Identifier(TypeDef targetType)	ClientPlugin.Providers.Identifier

<address class="footer">
Generated by

 1.8.13
</address>

redpajama_set_name: RedPajamaGithub


text:
/*
 * (c) 2007-2010 Anastasia Gornostaeva
 */

#include <caml/alloc.h>
#include <caml/mlvalues.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/custom.h>
#include <caml/signals.h>
#include <caml/callback.h>

#include "wrapper.h"

#include <openssl/ssl.h>
#include <openssl/err.h>

#define SSL_val(v)             (*((SSL **) Data_custom_val(v)))
#define SSL_CTX_val(v)         (*((SSL_CTX**)Data_custom_val(v)))
#define BIO_val(v)             (*((BIO **) Data_custom_val(v)))

#define X509_val(v)            (*((X509 **) &Field(v, 0)))
#define RSA_val(v)             (*((RSA **) &Field(v, 0)))

#define X509_STORE_CTX_val(v)  (*((X509_STORE_CTX **) &Field(v, 0)))

static void finalize_ssl(value block) {
  SSL* ssl = SSL_val(block);
  SSL_free(ssl);
}

static struct custom_operations ssl_ops = {
  "caml_ssl",
  finalize_ssl,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default
};

static void finalize_ssl_ctx(value block) {
  SSL_CTX* ssl_ctx = SSL_CTX_val(block);
  SSL_CTX_free(ssl_ctx);
}

static struct custom_operations ssl_ctx_ops = {
  "caml_ssl_ctx",
  finalize_ssl_ctx,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default
};

static void finalize_bio(value block) {
  BIO* bio = BIO_val(block);
  BIO_free(bio);
}

static struct custom_operations bio_ops = {
  "caml_bio",
  finalize_bio,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default
};

static value *mltls_error_exn = NULL;

/* SSL_library_init() always returns "1", so it is safe to discard the
   return value.
*/
CAMLprim value ml_init(value unit) {
  SSL_library_init();
  OpenSSL_add_ssl_algorithms();
  ERR_load_crypto_strings();
  SSL_load_error_strings();

  mltls_error_exn = caml_named_value("Mltls_Error");
  if (mltls_error_exn == NULL)
    caml_invalid_argument("Exception Mltls_Error is not initialized");

  return Val_unit;
}

static void mltls_error(char* fn, char* msg) {
  CAMLparam0();
  CAMLlocalN(vargs, 2);
  if (mltls_error_exn == NULL)
    caml_invalid_argument("Exception Mltls_Error is not initialized");
  if (msg == NULL)
    msg = "";
  vargs[0] = caml_copy_string(fn);
  vargs[1] = caml_copy_string(msg);
  caml_raise_with_args(*mltls_error_exn, 2, vargs);
  CAMLreturn0;
}

CAMLprim value ml_ERR_load_crypto_strings(value unit) {
  ERR_load_crypto_strings();
  return(Val_unit);
}

CAMLprim value ml_ERR_get_error(value unit) {
  CAMLparam1(unit);
  CAMLreturn(caml_copy_int32(ERR_get_error()));
}

CAMLprim value ml_ERR_error_string(value ve) {
  CAMLparam1(ve);
  char* err = ERR_error_string(Unsigned_long_val(ve), NULL);
  CAMLreturn(caml_copy_string(err));
}

CAMLprim value ml_ERR_error_string_n(value ve) {
  CAMLparam1(ve);
  char err[200];
  ERR_error_string_n(Unsigned_long_val(ve), err, sizeof(err));
  CAMLreturn(caml_copy_string(err));
}

CAMLprim value ml_ERR_lib_error_string(value ve) {
  CAMLparam1(ve);
  CAMLlocal1(vres);
  const char* err = ERR_lib_error_string(Unsigned_long_val(ve));
  if(err == NULL)
    vres = caml_copy_string("");
  else
    vres = caml_copy_string(err);
  CAMLreturn(vres);
}

CAMLprim value ml_ERR_func_error_string(value ve) {
  CAMLparam1(ve);
  CAMLlocal1(vres);
  const char* err = ERR_func_error_string(Unsigned_long_val(ve));
  if(err == NULL)
    vres = caml_copy_string("");
  else
    vres = caml_copy_string(err);
  CAMLreturn(vres);
}

CAMLprim value ml_ERR_reason_error_string(value ve) {
  CAMLparam1(ve);
  CAMLlocal1(vres);
  const char* err = ERR_reason_error_string(Unsigned_long_val(ve));
  if(err == NULL)
    vres = caml_copy_string("");
  else
    vres = caml_copy_string(err);
  CAMLreturn(vres);
}

#define tls_SSLv3_method           0
#define tls_SSLv3_server_method    1
#define tls_SSLv3_client_method    2
#define tls_TLSv1_method           3
#define tls_TLSv1_server_method    4
#define tls_TLSv1_client_method    5
#define tls_SSLv23_method          6
#define tls_SSLv23_server_method   7
#define tls_SSLv23_client_method   8

static SSL_METHOD* get_method(int method) {
  switch(method) {
  case tls_SSLv3_method:         return SSLv3_method();
  case tls_SSLv3_server_method:  return SSLv3_server_method();
  case tls_SSLv3_client_method:  return SSLv3_client_method();
  case tls_TLSv1_method:         return TLSv1_method();
  case tls_TLSv1_server_method:  return TLSv1_server_method();
  case tls_TLSv1_client_method:  return TLSv1_client_method();
  case tls_SSLv23_method:        return SSLv23_method();
  case tls_SSLv23_server_method: return SSLv23_server_method();
  case tls_SSLv23_client_method: return SSLv23_client_method();
  default: caml_invalid_argument("Unknown method");
  }
}

CAMLprim value ml_SSL_CTX_new(value vmethod) {
  CAMLparam1(vmethod);
  CAMLlocal1(vres);
  SSL_CTX* ssl_ctx = SSL_CTX_new(get_method(Int_val(vmethod)));
  if(ssl_ctx == NULL) {
    mltls_error("SSL_CTX_new", "Unable to create SSL_CTX structure");
  }
  vres = caml_alloc_custom(&ssl_ctx_ops, sizeof(SSL_CTX*), 0, 1);
  SSL_CTX_val(vres) = ssl_ctx;
  CAMLreturn(vres);
}

static int get_file_type(int type) {
  switch(type) {
  case 0: return SSL_FILETYPE_PEM;
  case 1: return SSL_FILETYPE_ASN1;
  default: caml_invalid_argument("Unknown file type");
  }
}

CAMLprim value ml_SSL_CTX_use_certificate_file(value vctx,
                                                    value vfile, value vtype) {
  int ret = SSL_CTX_use_certificate_file(SSL_CTX_val(vctx),
                                         String_val(vfile),
                                         get_file_type(Int_val(vtype)));
  return Val_int(ret);
}

CAMLprim value ml_SSL_CTX_use_PrivateKey_file(value vctx,
                                                   value vfile, value vtype) {
  int ret = SSL_CTX_use_PrivateKey_file(SSL_CTX_val(vctx),
                                        String_val(vfile),
                                        get_file_type(Int_val(vtype)));
  return Val_int(ret);
}

CAMLprim value ml_SSL_new(value vctx) {
  CAMLparam1(vctx);
  CAMLlocal1(vres);
  SSL* ssl = SSL_new(SSL_CTX_val(vctx));
  if(ssl == NULL) {
    mltls_error("SSL_new", "Unable to create SSL structure");
  }
  vres = caml_alloc_custom(&ssl_ops, sizeof(SSL*), 0, 1);
  SSL_val(vres) = ssl;
  CAMLreturn(vres);
}

ML_1(SSL_set_accept_state, SSL_val, Unit)
ML_1(SSL_set_connect_state, SSL_val, Unit)
ML_1(SSL_is_init_finished, SSL_val, Val_bool)

ML_2(SSL_set_fd, SSL_val, Int_val, Val_int)
ML_2(SSL_set_rfd, SSL_val, Int_val, Val_int)
ML_2(SSL_set_wfd, SSL_val, Int_val, Val_int)

CAMLprim value ml_SSL_accept(value vssl) {
  int ret;

  caml_enter_blocking_section();
  ret = SSL_accept(SSL_val(vssl));
  caml_leave_blocking_section();
  return Val_int(ret);
}

CAMLprim value ml_SSL_connect(value vssl) {
  int ret;

  caml_enter_blocking_section();
  ret = SSL_connect(SSL_val(vssl));
  caml_leave_blocking_section();
  return Val_int(ret);
}

CAMLprim value ml_SSL_do_handshake(value vssl) {
  int ret;

  caml_enter_blocking_section();
  ret = SSL_do_handshake(SSL_val(vssl));
  caml_leave_blocking_section();
  return Val_int(ret);
}

ML_2(SSL_get_error, SSL_val, Int_val, Val_int)

CAMLprim value ml_SSL_read(value vssl,
                           value vbuf, value voffs, value vnum) {
  CAMLparam4(vssl, vbuf, voffs, vnum);
  long offs = Long_val(voffs);
  long len = Long_val(vnum);
  char* tmpbuf;
  int ret;
  if(offs + len > caml_string_length(vbuf))
    caml_invalid_argument("Buffer too short");
  tmpbuf = (char*) caml_stat_alloc(len);
  caml_enter_blocking_section();
  ret = SSL_read(SSL_val(vssl), tmpbuf, len);
  caml_leave_blocking_section();
  memcpy(&Byte(vbuf, offs), tmpbuf, ret);
  caml_stat_free(tmpbuf);
  CAMLreturn(Val_int(ret));
}

CAMLprim value ml_SSL_write(value vssl,
                                 value vbuf, value voffs, value vnum) {
  CAMLparam4(vssl, vbuf, voffs, vnum);
  long offs = Long_val(voffs);
  long len = Long_val(vnum);
  char* tmpbuf;
  int ret;
  if(offs + len > caml_string_length(vbuf))
    caml_invalid_argument("Invalid offset for buffer");
  tmpbuf = (char*) caml_stat_alloc(len);
  memcpy(tmpbuf, &Byte(vbuf, offs), len);
  caml_enter_blocking_section();
  ret = SSL_write(SSL_val(vssl), tmpbuf, len);
  caml_leave_blocking_section();
  caml_stat_free(tmpbuf);
  CAMLreturn(Val_int(ret));
}

ML_1(SSL_shutdown, SSL_val, Val_int)

CAMLprim value ml_SSL_get_shutdown(value vssl) {
  CAMLparam1(vssl);
  CAMLlocal3(vres, recv, sent);
  SSL* ssl = SSL_val(vssl);
  int ret;
  ret = SSL_get_shutdown(ssl);
  recv = Val_bool(ret & SSL_RECEIVED_SHUTDOWN);
  sent = Val_bool(ret & SSL_SENT_SHUTDOWN);
  vres = caml_alloc_tuple(2);
  Store_field(vres, 0, recv);
  Store_field(vres, 1, sent);
  CAMLreturn(vres);
}

/*
CAMLprim value ml_SSL_set_shutdown(value vssl, value vmode) {
  CAMLparam2(vssl, vmode);
  CAMLlocal1(vres);
  SSL* ssl = SSL_val(vssl);
  int ret;
  ret = SSL_set_shutdown(ssl);
  vres = Val_int(ret);
  CAMLreturn(vres);
}
*/

ML_1(SSL_clear, SSL_val, Unit)
ML_1(SSL_CTX_check_private_key, SSL_CTX_val, Val_int)
ML_1(SSL_CTX_set_default_verify_paths, SSL_CTX_val, Val_int)

/* ML_1(SSL_get_perr_certificate, SSL_val, alloc_X509) */
CAMLprim value ml_SSL_get_peer_certificate(value vssl) {
  CAMLparam1(vssl);
  CAMLlocal1(vres);
  SSL* ssl = SSL_val(vssl);
  X509* cert;
  cert = SSL_get_peer_certificate(ssl);
  vres = caml_alloc_small(1, Abstract_tag);
  X509_val(vres) = cert;
  CAMLreturn(vres);
}

/* use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 2 options
 * are 'ored' with SSL_VERIFY_PEER if they are desired */
static int tbl_verify_mode[] = {
  SSL_VERIFY_NONE,
  SSL_VERIFY_PEER,
  SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  SSL_VERIFY_CLIENT_ONCE
};

CAMLprim value ml_SSL_CTX_set_verify(value vctx, value vmode,
                                          value vcallback) {
  CAMLparam3(vctx, vmode, vcallback);
  int mode = caml_convert_flag_list(vmode, tbl_verify_mode);
  int (*callback_verify)(int, X509_STORE_CTX*) = NULL;

  if(Is_block(vcallback))
    callback_verify = (int(*) (int, X509_STORE_CTX*))Field(vcallback, 0);
  caml_enter_blocking_section();
  SSL_CTX_set_verify(SSL_CTX_val(vctx), mode, callback_verify);
  caml_leave_blocking_section();
  CAMLreturn(Val_unit);
}

ML_1(SSL_get_verify_result, SSL_val, Val_long)

CAMLprim value ml_BIO_new(value unit) {
  CAMLparam0();
  CAMLlocal1(vres);
  BIO* bio = BIO_new(BIO_s_mem());
  if(!bio) {
    mltls_error("BIO_new", "Unable to create BIO structure");
  }
  vres = caml_alloc_custom(&bio_ops, sizeof(BIO*), 0, 1);
  BIO_val(vres) = bio;
  CAMLreturn(vres);
}

ML_3(SSL_set_bio, SSL_val, BIO_val, BIO_val, Unit)
ML_1(BIO_pending, BIO_val, Val_int)

CAMLprim value ml_BIO_write(value vbio,
                                 value vbuf, value voffs, value vlen) {
  CAMLparam4(vbio, vbuf, voffs, vlen);
  long offs = Long_val(voffs);
  long len = Long_val(vlen);
  char* tmpbuf;
  int ret;

  if(offs + len  > caml_string_length(vbuf))
    caml_invalid_argument("Invalid offset for buffer");
  tmpbuf = (char*) caml_stat_alloc(len);
  memcpy(tmpbuf, &Byte(vbuf, offs), len);
  caml_enter_blocking_section();
  ret = BIO_write(BIO_val(vbio), tmpbuf, len);
  caml_leave_blocking_section();
  caml_stat_free(tmpbuf);
  CAMLreturn(Val_int(ret));
}

CAMLprim value ml_BIO_read(value vbio,
                           value vbuf, value voffs, value vlen) {
  CAMLparam4(vbio, vbuf, voffs, vlen);
  long len = Int_val(vlen);
  long offs = Long_val(voffs);
  char* tmpbuf;
  int ret;

  if (offs + len > caml_string_length(vbuf))
    caml_invalid_argument("Buffer too short");
  tmpbuf = (char*) caml_stat_alloc(len);
  caml_enter_blocking_section();
  ret = BIO_read(BIO_val(vbio), tmpbuf, len);
  caml_leave_blocking_section();
  memcpy(&Byte(vbuf, offs), tmpbuf, ret);;
  caml_stat_free(tmpbuf);
  CAMLreturn(Val_int(ret));
}


text:
package org.jai.search.model;

public enum ProductPropertyType
{
    SIZE,
    COLOR
}


text:
(function () {
    'use strict';

    window.MINION = {};

    var YD = YAHOO.util.Dom,
        YE = YAHOO.util.Event;

    MINION.Log = function (checkId) {
        this._onlyFailures = YD.get('onlyFailures');
        this._logBody      = YD.get('logBody');
        this._checkId      = checkId;
        this._xhrLock      = false;
        this._loading      = YD.get('loading');

        // We start on page 2 because the initial data is rendered server-side
        this._page = 2;
    };

    MINION.Log.prototype.init = function () {
        YE.on(
            this._onlyFailures,
            'click',
            this._handleOnlyFailuresClick,
            this,
            true
        );

        YE.on(
            window,
            'scroll',
            this._checkScroll,
            this,
            true
        );
    };

    MINION.Log.prototype.load = function () {
        this._xhrLock = true;

        this._loading.style.display = 'block';

        YAHOO.util.Connect.asyncRequest(
            'GET',
            this._assembleDataUrl(),
            {
                scope: this,
                success: function (o) {
                    this._logBody.innerHTML += o.responseText;

                    this._page   += 1
                    this._xhrLock = false;

                    this._loading.style.display = 'none';
                }
            }
        );
    };

    MINION.Log.prototype._handleOnlyFailuresClick = function (e) {
        var url = '/log?id=' + this._checkId + '&onlyFailures=';

        if (this._onlyFailures.checked) {
            url += '1';
        } else {
            url += '0';
        }

        window.location = url;
    };

    MINION.Log.prototype._checkScroll = function (e) {
        var scroll = document.body.scrollTop + document.body.clientHeight + 50,
            limit  = document.body.scrollHeight;

        if (!this._xhrLock && scroll > limit) {
            this.load();
        }
    };

    MINION.Log.prototype._assembleDataUrl = function () {
        var url = '/log?id=' + this._checkId + '&onlyFailures=';

        if (this._onlyFailures.checked) {
            url += '1';
        } else {
            url += '0';
        }

        url += '&data=1';
        url += '&page=' + this._page;

        return url;
    };
}());


text:
package de.tu_berlin.impro3.frontend

object Models {
  // Objects need for the Locations
  case class Location(zone: String, meta: LocationMetaData, metrics: List[LocationMetric])
  case class LocationMetaData(center: LatLon, unique_hashtags: Int, hashtag_occurrences: Int)
  case class LatLon(lat: Int, lon: Int)
  case class LocationMetric(location: String, spatial_impact: Double)

  case class SpatialImpact(distribution: IndexedSeq[Int], cities : Map[String, Long])
  case class MapLocation(value: Int, lat: Double, lon: Double, loc: String)
  case class LocationDetails(spatial_impact: SpatialImpact, entropy_focus_spread: List[HashtagMetrics])

  // Objects needed for the Hashtags
  case class HashtagMetrics(tag: String, occurrences: Int, focus_zone: String, focus: Double, entropy: Double,
                            spread: Double)
  case class TemporalItem(time_interval: Long, occurrences: Int, focus_zone: String, focus: Double, entropy: Double,
                          spread: Double)
  case class Hashtag(tag: String, metrics: HashtagMetrics, temporal: List[TemporalItem], locations: List[HashtagLocation])
  case class HashtagLocation(value: Int, lat : Double, lon: Double)

  case class TopHashtag(value: Int, hashtag: String)
}


text:
Rails elasticsearch integration with no magic.

## Setup
```ruby
Supple.configure do |config|
  config.pool_size = 5
  config.pool_timeout = 1
  config.index_name = -> { table_name }
end
```


text:
// Test that header is standalone
#include <TINYSTL/vector.h>


text:
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace GraphQL.GraphiQL
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.Clear();

            var settings = new JsonSerializerSettings();
            settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Formatters.Add(new JsonMediaTypeFormatter {Indent = true, SerializerSettings = settings});

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


text:
module.exports = function (grunt) {
  require('load-grunt-tasks')(grunt);

  grunt.initConfig({
    concat: require('./tasks/concat'),
    connect: require('./tasks/connect'),
    clean: require('./tasks/clean'),
    sass: require('./tasks/sass'),
    cssmin: require('./tasks/cssmin'),
    copy: require('./tasks/copy'),
    shell: require('./tasks/shell'),
    watch: require('./tasks/watch'),
    'gh-pages': require('./tasks/gh-pages')
  });

  var baseTasks = [
    'clean',
    'shell:generateFont',
    'sass',
    'concat',
    'cssmin',
    'copy',
    'shell'
  ];

  var generateFontTask = baseTasks.concat([
    'shell:generateFont'
  ]);

  var devTasks = baseTasks.concat([
    'connect',
    'watch:scss'
  ]);

  grunt.event.on('watch', function (action, filepath) {
    grunt.task.run('shell:style');
  });

  grunt.registerTask('dev', devTasks);
  grunt.registerTask('generate-font', generateFontTask);
  grunt.registerTask('build', baseTasks);
  grunt.registerTask('default', baseTasks);
  grunt.registerTask('publish', ['build', 'gh-pages']);
};


text:
package test.methodselectors;

import org.testng.annotations.Test;

import test.BaseTest;

public class BeanShellTest extends BaseTest {

  @Test
  public void onlyGroup1() {
    addClass("test.methodselectors.SampleTest");
    setBeanShellExpression("groups.\n     containsKey   \t    (\"test1\")");
    run();
    String[] passed = {
        "test1",
    };
    String[] failed = {
    };
    verifyTests("Passed", passed, getPassedTests());
    verifyTests("Failed", failed, getFailedTests());
  }

  private static void ppp(String s) {
    System.out.println("[MethodSelectorTest] " + s);
  }
}


text:
TOOLS=$(cd `dirname $0` && pwd)

# enyo location
ENYO="$TOOLS/../enyo"

# deploy script location
DEPLOY="$ENYO/tools/deploy.js"

# check for node, but quietly
if command -v node >/dev/null 2>&1; then
	# use node to invoke deploy with imported parameters
	echo "enyo/tools/minify.sh args: " $@
	node $DEPLOY $@
else
	echo "No node found in path"
	exit 1
fi

# create a zip and upload to build.phonegap.com
echo "create zip"
cd /home/micha/stopandgo/Enyo2/mySongs/deploy/mySongs
zip -rq /home/micha/stopandgo/Enyo2/mySongs/deploy/mySongs.zip *
echo "upload to build.phonegap.com"
curl -X PUT -F file=@/home/micha/stopandgo/Enyo2/mySongs/deploy/mySongs.zip https://build.phonegap.com/api/v1/apps/302264?auth_token=dFZDtwNV7MF3DJ5RZHx2
# copy a build to Dropbox public folder
echo "copy a build to Dropbox public folder"
cp -rf /home/micha/stopandgo/Enyo2/mySongs/deploy/mySongs/* /home/micha/Dropbox/Public/mySongs/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using OrchardCore.Data.Migration.Records;
using OrchardCore.Environment.Extensions;
using OrchardCore.Modules;
using YesSql;
using YesSql.Sql;

namespace OrchardCore.Data.Migration
{
    /// <summary>
    /// Represents a class that manages the database migrations.
    /// </summary>
    public class DataMigrationManager : IDataMigrationManager
    {
        private readonly IEnumerable<IDataMigration> _dataMigrations;
        private readonly ISession _session;
        private readonly IStore _store;
        private readonly IExtensionManager _extensionManager;
        private readonly ILogger _logger;
        private readonly ITypeFeatureProvider _typeFeatureProvider;
        private readonly List<string> _processedFeatures;

        private DataMigrationRecord _dataMigrationRecord;

        /// <summary>
        /// Creates a new instance of the <see cref="DataMigrationManager"/>.
        /// </summary>
        /// <param name="typeFeatureProvider">The <see cref="ITypeFeatureProvider"/>.</param>
        /// <param name="dataMigrations">A list of <see cref="IDataMigration"/>.</param>
        /// <param name="session">The <see cref="ISession"/>.</param>
        /// <param name="store">The <see cref="IStore"/>.</param>
        /// <param name="extensionManager">The <see cref="IExtensionManager"/>.</param>
        /// <param name="logger">The <see cref="ILogger"/>.</param>
        public DataMigrationManager(
            ITypeFeatureProvider typeFeatureProvider,
            IEnumerable<IDataMigration> dataMigrations,
            ISession session,
            IStore store,
            IExtensionManager extensionManager,
            ILogger<DataMigrationManager> logger)
        {
            _typeFeatureProvider = typeFeatureProvider;
            _dataMigrations = dataMigrations;
            _session = session;
            _store = store;
            _extensionManager = extensionManager;
            _logger = logger;
            _processedFeatures = new List<string>();
        }

        /// <inheritdocs />
        public async Task<DataMigrationRecord> GetDataMigrationRecordAsync()
        {
            if (_dataMigrationRecord == null)
            {
                _dataMigrationRecord = await _session.Query<DataMigrationRecord>().FirstOrDefaultAsync();

                if (_dataMigrationRecord == null)
                {
                    _dataMigrationRecord = new DataMigrationRecord();
                    _session.Save(_dataMigrationRecord);
                }
            }

            return _dataMigrationRecord;
        }

        public async Task<IEnumerable<string>> GetFeaturesThatNeedUpdateAsync()
        {
            var currentVersions = (await GetDataMigrationRecordAsync()).DataMigrations
                .ToDictionary(r => r.DataMigrationClass);

            var outOfDateMigrations = _dataMigrations.Where(dataMigration =>
            {
                Records.DataMigration record;
                if (currentVersions.TryGetValue(dataMigration.GetType().FullName, out record) && record.Version.HasValue)
                {
                    return CreateUpgradeLookupTable(dataMigration).ContainsKey(record.Version.Value);
                }

                return ((GetCreateMethod(dataMigration) ?? GetCreateAsyncMethod(dataMigration)) != null);
            });

            return outOfDateMigrations.Select(m => _typeFeatureProvider.GetFeatureForDependency(m.GetType()).Id).ToList();
        }

        public async Task Uninstall(string feature)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Uninstalling feature '{FeatureName}'.", feature);
            }
            var migrations = GetDataMigrations(feature);

            // apply update methods to each migration class for the module
            foreach (var migration in migrations)
            {
                // copy the object for the Linq query
                var tempMigration = migration;

                // get current version for this migration
                var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration);

                var uninstallMethod = GetUninstallMethod(migration);
                if (uninstallMethod != null)
                {
                    uninstallMethod.Invoke(migration, new object[0]);
                }

                var uninstallAsyncMethod = GetUninstallAsyncMethod(migration);
                if (uninstallAsyncMethod != null)
                {
                    await (Task)uninstallAsyncMethod.Invoke(migration, new object[0]);
                }

                if (dataMigrationRecord == null)
                {
                    continue;
                }

                (await GetDataMigrationRecordAsync()).DataMigrations.Remove(dataMigrationRecord);
            }
        }

        public async Task UpdateAsync(IEnumerable<string> featureIds)
        {
            foreach (var featureId in featureIds)
            {
                if (!_processedFeatures.Contains(featureId))
                {
                    await UpdateAsync(featureId);
                }
            }
        }

        public async Task UpdateAsync(string featureId)
        {
            if (_processedFeatures.Contains(featureId))
            {
                return;
            }

            _processedFeatures.Add(featureId);

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Updating feature '{FeatureName}'", featureId);
            }

            // proceed with dependent features first, whatever the module it's in
            var dependencies = _extensionManager
                .GetFeatureDependencies(
                    featureId)
                .Where(x => x.Id != featureId)
                .Select(x => x.Id);

            await UpdateAsync(dependencies);

            var migrations = GetDataMigrations(featureId);

            // apply update methods to each migration class for the module
            foreach (var migration in migrations)
            {
                var schemaBuilder = new SchemaBuilder(_store.Configuration, await _session.BeginTransactionAsync());
                migration.SchemaBuilder = schemaBuilder;

                // copy the object for the Linq query
                var tempMigration = migration;

                // get current version for this migration
                var dataMigrationRecord = await GetDataMigrationRecordAsync(tempMigration);

                var current = 0;
                if (dataMigrationRecord != null)
                {
                    // This can be null if a failed create migration has occurred and the data migration record was saved.
                    current = dataMigrationRecord.Version.HasValue ? dataMigrationRecord.Version.Value : current;
                }
                else
                {
                    dataMigrationRecord = new Records.DataMigration { DataMigrationClass = migration.GetType().FullName };
                    _dataMigrationRecord.DataMigrations.Add(dataMigrationRecord);
                }

                try
                {
                    // do we need to call Create() ?
                    if (current == 0)
                    {
                        // try to resolve a Create method

                        var createMethod = GetCreateMethod(migration);
                        if (createMethod != null)
                        {
                            current = (int)createMethod.Invoke(migration, new object[0]);
                        }

                        // try to resolve a CreateAsync method

                        var createAsyncMethod = GetCreateAsyncMethod(migration);
                        if (createAsyncMethod != null)
                        {
                            current = await (Task<int>)createAsyncMethod.Invoke(migration, new object[0]);
                        }
                    }

                    var lookupTable = CreateUpgradeLookupTable(migration);

                    while (lookupTable.TryGetValue(current, out var methodInfo))
                    {
                        if (_logger.IsEnabled(LogLevel.Information))
                        {
                            _logger.LogInformation("Applying migration for '{FeatureName}' from version {Version}.", featureId, current);
                        }

                        var isAwaitable = methodInfo.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null;
                        if (isAwaitable)
                        {
                            current = await (Task<int>)methodInfo.Invoke(migration, new object[0]);
                        }
                        else
                        {
                            current = (int)methodInfo.Invoke(migration, new object[0]);
                        }
                    }

                    // if current is 0, it means no upgrade/create method was found or succeeded
                    if (current == 0)
                    {
                        return;
                    }

                    dataMigrationRecord.Version = current;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error while running migration version {Version} for '{FeatureName}'.", current, featureId);

                    await _session.CancelAsync();
                }
                finally
                {
                    // Persist data migrations
                    _session.Save(_dataMigrationRecord);
                }
            }
        }

        private async Task<Records.DataMigration> GetDataMigrationRecordAsync(IDataMigration tempMigration)
        {
            var dataMigrationRecord = await GetDataMigrationRecordAsync();
            return dataMigrationRecord
                .DataMigrations
                .FirstOrDefault(dm => dm.DataMigrationClass == tempMigration.GetType().FullName);
        }

        /// <summary>
        /// Returns all the available IDataMigration instances for a specific module, and inject necessary builders
        /// </summary>
        private IEnumerable<IDataMigration> GetDataMigrations(string featureId)
        {
            var migrations = _dataMigrations
                    .Where(dm => _typeFeatureProvider.GetFeatureForDependency(dm.GetType()).Id == featureId)
                    .ToList();

            return migrations;
        }

        /// <summary>
        /// Create a list of all available Update methods from a data migration class, indexed by the version number
        /// </summary>
        private static Dictionary<int, MethodInfo> CreateUpgradeLookupTable(IDataMigration dataMigration)
        {
            return dataMigration
                .GetType()
                .GetMethods(BindingFlags.Public | BindingFlags.Instance)
                .Select(GetUpdateMethod)
                .Where(tuple => tuple != null)
                .ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2);
        }

        private static Tuple<int, MethodInfo> GetUpdateMethod(MethodInfo methodInfo)
        {
            const string updateFromPrefix = "UpdateFrom";
            const string asyncSuffix = "Async";

            if (methodInfo.Name.StartsWith(updateFromPrefix, StringComparison.Ordinal) && (methodInfo.ReturnType == typeof(int) || methodInfo.ReturnType == typeof(Task<int>)))
            {
                var version = methodInfo.Name.EndsWith(asyncSuffix, StringComparison.Ordinal)
                    ? methodInfo.Name.Substring(updateFromPrefix.Length, methodInfo.Name.Length - updateFromPrefix.Length - asyncSuffix.Length)
                    : methodInfo.Name.Substring(updateFromPrefix.Length);

                if (Int32.TryParse(version, out var versionValue))
                {
                    return new Tuple<int, MethodInfo>(versionValue, methodInfo);
                }
            }

            return null;
        }

        /// <summary>
        /// Returns the Create method from a data migration class if it's found
        /// </summary>
        private static MethodInfo GetCreateMethod(IDataMigration dataMigration)
        {
            var methodInfo = dataMigration.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Instance);
            if (methodInfo != null && methodInfo.ReturnType == typeof(int))
            {
                return methodInfo;
            }

            return null;
        }

        /// <summary>
        /// Returns the CreateAsync method from a data migration class if it's found
        /// </summary>
        private static MethodInfo GetCreateAsyncMethod(IDataMigration dataMigration)
        {
            var methodInfo = dataMigration.GetType().GetMethod("CreateAsync", BindingFlags.Public | BindingFlags.Instance);
            if (methodInfo != null && methodInfo.ReturnType == typeof(Task<int>))
            {
                return methodInfo;
            }

            return null;
        }

        /// <summary>
        /// Returns the Uninstall method from a data migration class if it's found
        /// </summary>
        private static MethodInfo GetUninstallMethod(IDataMigration dataMigration)
        {
            var methodInfo = dataMigration.GetType().GetMethod("Uninstall", BindingFlags.Public | BindingFlags.Instance);
            if (methodInfo != null && methodInfo.ReturnType == typeof(void))
            {
                return methodInfo;
            }

            return null;
        }

        /// <summary>
        /// Returns the UninstallAsync method from a data migration class if it's found
        /// </summary>
        private static MethodInfo GetUninstallAsyncMethod(IDataMigration dataMigration)
        {
            var methodInfo = dataMigration.GetType().GetMethod("UninstallAsync", BindingFlags.Public | BindingFlags.Instance);
            if (methodInfo != null && methodInfo.ReturnType == typeof(Task))
            {
                return methodInfo;
            }

            return null;
        }

        public async Task UpdateAllFeaturesAsync()
        {
            var featuresThatNeedUpdate = await GetFeaturesThatNeedUpdateAsync();

            foreach (var featureId in featuresThatNeedUpdate)
            {
                try
                {
                    await UpdateAsync(featureId);
                }
                catch (Exception ex) when (!ex.IsFatal())
                {
                    _logger.LogError(ex, "Could not run migrations automatically on '{FeatureName}'", featureId);
                }
            }
        }
    }
}


text:
echo ""
echo "#[QPython] Press enter to exit ..."
echo ""

while read inputline
do
exit
done


text:
require 'rails_helper'

describe TradeTariffBackend::NumberFormatter do
  let(:number_formatter) { described_class.new }

  describe '#number_with_precision' do
    context 'with minimum_decimal_points option' do
      it 'adds leading zero decimal numbers up to specified count' do
        expect(number_formatter.number_with_precision(1.2, minimum_decimal_points: 4)).to eq '1.2000'
        expect(number_formatter.number_with_precision(1, minimum_decimal_points: 4)).to eq '1.0000'
        expect(number_formatter.number_with_precision(1.23, minimum_decimal_points: 4)).to eq '1.2300'
      end

      context 'with precision specified' do
        it 'rounds to specified precision and adds leading decimal numbers if needed' do
          expect(
            number_formatter.number_with_precision(
              1.256,
              minimum_decimal_points: 2,
              precision: 1
            )
          ).to eq '1.30'
        end
      end

      context 'with stripping of insignificant zeros enabled' do
        it 'strips insignificant zeroes up to minimum decimal points size' do
          expect(
            number_formatter.number_with_precision(
              1.256,
              minimum_decimal_points: 2,
              precision: 1,
              strip_insignificant_zeroes: true
            )
          ).to eq '1.30'

          expect(
            number_formatter.number_with_precision(
              1.25656,
              minimum_decimal_points: 4,
              precision: 3,
              strip_insignificant_zeroes: true
            )
          ).to eq '1.2570'
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <title>JavaScript Exception Handling - try, catch, finally and throws</title>


text:
package slaq.ql.core

import java.sql.Types._
import slaq.ql.TypeMapperDelegate

class SQLUtils {
  def quote(id: String): String = {
    val s = new StringBuilder(id.length + 4) append '"'
    for (c <- id) if (c == '"') s append "\"\"" else s append c
    s append '"' toString
  }

  def mapTypeName(tmd: TypeMapperDelegate[_]): String =
    tmd.sqlType match {
      case VARCHAR => "VARCHAR(254)"
      case _       => tmd.sqlTypeName
    }
}


text:
package com.ixkit.octopus.core;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ixkit.octopus.event.WebEvent;
import com.ixkit.octopus.util.RetrofitHelper;

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

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * Created by icoco on 15/01/2019.
 */

public class RequestEmitter {

    private static RequestBody toRequestBody(Object requestParameter) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonStr = gson.toJson(requestParameter);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonStr);

        return body;
    }

    public static Call emit(Retrofit master, String route, WebMethod method, BodyType bodyType, HashMap requestParameter, Class classOfResponse, final WebEvent event) {
        return emit(master, route, method, null, bodyType, requestParameter, classOfResponse, event);

    }

    private static Call upload(Retrofit master, String route, Map headers, BodyType bodyType, HashMap requestParameter, Class classOfResponse, final WebEvent event) {
        CallApi api = WebService.create(master, CallApi.class);
        Call call = null;

        HashMap params = requestParameter;

        Map<String, RequestBody> bodyMap = RetrofitHelper.Request.generateRequestBodyMap(params);

        call = api.upload(route, headers, bodyMap);
        WebService.invoke(call, event, classOfResponse);
        return call;
    }

    public static Call emit(Retrofit master, String route, WebMethod method, Map headers, BodyType bodyType, HashMap requestParameter, Class classOfResponse, final WebEvent event) {
        if (null == headers) {
            headers = new HashMap();
        }
        if (null == requestParameter) {
            requestParameter = new HashMap();
        }
        CallApi api = WebService.create(master, CallApi.class);
        Call call = null;
        do {
            if (method == WebMethod.Upload) {

                return upload(master, route, headers, bodyType, requestParameter, classOfResponse, event);
            }
            if (method == WebMethod.Post) {
                if (bodyType == BodyType.form) {
                    HashMap map = requestParameter;

                    call = api.postForm(route, map, headers);
                    break;
                }
                if (bodyType == BodyType.json) {
                    RequestBody parameterBody = toRequestBody(requestParameter);
                    call = api.post(route, parameterBody);
                    break;
                }
                break;
            }
            if (method == WebMethod.Get) {
                HashMap map = requestParameter;
                call = api.get(route, map);
                break;
            }
            if (method == WebMethod.Delete) {
                HashMap map = requestParameter;
                call = api.delete(route, map);
                break;
            }
        } while (false);

        WebService.invoke(call, event, classOfResponse);
        return call;
    }
}


text:
package net.gadgil

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith

@RunWith(classOf[JUnitRunner])
class PlainVanillaTest extends Spec with ShouldMatchers {

  describe("Placeholder for JUnit based tests") {
    it("should run test cases") {
      "1" should equal("1")
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_checked="true">
        <shape android:shape="rectangle">
            <corners android:radius="18dp"/>
            <solid android:color="@color/colorFABMenuLabel"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="18dp"/>
            <solid android:color="#C9F7E9"/>
        </shape>
    </item>
</selector>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:orientation="vertical"
    tools:context="com.michaelmuenzer.android.scrollablenumberpicker.sample.MainActivity">

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="center_vertical"
                  android:orientation="horizontal">

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/number_picker_bg_color"
            android:paddingEnd="8dp"
            android:paddingStart="8dp"
            app:snp_buttonTouchScaleFactor="0.8"
            app:snp_maxValue="10"
            app:snp_minValue="1"
            app:snp_orientation="vertical"
            app:snp_stepSize="1"
            app:snp_value="5"/>

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_horizontal"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_margin="10dp"
            android:background="@drawable/number_picker_bg_color"
            android:paddingEnd="8dp"
            android:paddingStart="8dp"
            app:snp_maxValue="1000"
            app:snp_minValue="10"
            app:snp_orientation="horizontal"
            app:snp_stepSize="5"
            app:snp_updateInterval="100"
            app:snp_value="10"/>
    </LinearLayout>

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="center_vertical"
                  android:orientation="horizontal">

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_vertical_icons"
            android:layout_width="50dp"
            android:layout_height="95dp"
            android:layout_margin="10dp"
            android:background="@drawable/number_picker_bg_color"
            app:snp_buttonBackgroundTintSelector="@color/btn_tint_selector_main"
            app:snp_buttonIconDown="@drawable/arrow_down_bold_circle_outline"
            app:snp_buttonIconUp="@drawable/arrow_up_bold_circle_outline"
            app:snp_maxValue="10000"
            app:snp_minValue="10"
            app:snp_orientation="vertical"
            app:snp_stepSize="100"
            app:snp_updateInterval="10"
            app:snp_value="10"
            app:snp_valueMarginEnd="8dp"
            app:snp_valueMarginStart="8dp"
            app:snp_value_text_appearance="?android:attr/textAppearanceMedium"/>

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_horizontal_icons"
            android:layout_width="wrap_content"
            android:layout_height="35dp"
            android:layout_margin="10dp"
            app:snp_buttonBackgroundTintSelector="@color/btn_tint_selector_main"
            app:snp_buttonIconLeft="@drawable/btn_left_selector_main"
            app:snp_buttonIconRight="@drawable/btn_right_selector_main"
            app:snp_buttonTouchScaleFactor="0.7"
            app:snp_maxValue="90"
            app:snp_minValue="10"
            app:snp_orientation="horizontal"
            app:snp_stepSize="10"
            app:snp_updateInterval="5"
            app:snp_value="10"
            app:snp_valueMarginEnd="5dp"
            app:snp_valueMarginStart="5dp"
            app:snp_value_text_color="@color/colorPrimary"
            app:snp_value_text_size="16sp"/>
    </LinearLayout>

    <LinearLayout android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="center_vertical"
                  android:orientation="horizontal">

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_vertical_scroll"
            android:layout_width="40dp"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/number_picker_bg_color"
            android:paddingEnd="8dp"
            android:paddingStart="8dp"
            app:snp_maxValue="1000"
            app:snp_minValue="0"
            app:snp_orientation="vertical"
            app:snp_scrollEnabled="true"
            app:snp_stepSize="1"
            app:snp_value="500"
            app:snp_valueMarginEnd="30dp"
            app:snp_valueMarginStart="30dp"/>

        <com.michaelmuenzer.android.scrollablennumberpicker.ScrollableNumberPicker
            android:id="@+id/number_picker_horizontal_scroll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/number_picker_bg_color"
            android:paddingEnd="8dp"
            android:paddingStart="8dp"
            app:snp_buttonPaddingBottom="8dp"
            app:snp_buttonPaddingLeft="8dp"
            app:snp_buttonPaddingRight="8dp"
            app:snp_buttonPaddingTop="8dp"
            app:snp_maxValue="1000"
            app:snp_minValue="0"
            app:snp_orientation="horizontal"
            app:snp_scrollEnabled="true"
            app:snp_stepSize="1"
            app:snp_updateInterval="25"
            app:snp_value="500"
            app:snp_valueMarginEnd="30dp"
            app:snp_valueMarginStart="30dp"/>
    </LinearLayout>
</LinearLayout>


text:
/**
 * Created by 二更 on 2017/2/13.
 */
// 积分兑换
$('.mask_layer').height(document.body.scrollHeight+1000);
$('.integral_button').bind('click',function(){
    $('.exchange_modal').css('display','block');
    disableScroll();
});
// 积分兑换成功弹框js
$('.confirm_exchange').bind('click',function(){
    $('.exchangeSucceed_modal').css('display','block');
    $('.exchange_modal').css('display','none');
    disableScroll();
});
// 积分兑换失败弹框js
//        $('.confirm_exchange').bind('click',function(){
//            $('.exchangeFailure_modal').css('display','block');
//            $('.exchange_modal').css('display','none');
//            disableScroll();
//        });

$('.close,.cancel,.confirm').bind('click',function(){
    $('.exchangeFailure_modal,.exchangeSucceed_modal,.exchange_modal').css('display','none');
    enableScroll();
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:camunda="http://camunda.org/schema/1.0/bpmn"
  targetNamespace="Examples">

  <process id="twoJobsProcess">

    <startEvent id="theStart" />

    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="asyncServiceTask" />

    <serviceTask id="asyncServiceTask" camunda:asyncBefore="true" camunda:asyncAfter="true"
      camunda:class="org.camunda.bpm.engine.test.db.ConfigurableFailureDelegate"/>

    <sequenceFlow id="flow3" sourceRef="asyncServiceTask" targetRef="theEnd" />

    <endEvent id="theEnd" />

  </process>

</definitions>


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-155.js
 * @description Object.defineProperty - 'writable' property in 'Attributes' is an inherited data property  (8.10.5 step 6.a)
 */

function testcase() {
        var obj = { };

        var proto = {
            writable: true
        };

        var ConstructFun = function () { };
        ConstructFun.prototype = proto;

        var child = new ConstructFun();

        Object.defineProperty(obj, "property", child);

        var beforeWrite = obj.hasOwnProperty("property");

        obj.property = "isWritable";

        var afterWrite = (obj.property === "isWritable");

        return beforeWrite === true && afterWrite === true;
    }
runTestCase(testcase);


text:
import datetime, time

import requests

from SpiderKeeper.app.proxy.spiderctrl import SpiderServiceProxy
from SpiderKeeper.app.spider.model import SpiderStatus, Project, SpiderInstance
from SpiderKeeper.app.util.http import request

class ScrapydProxy(SpiderServiceProxy):
    def __init__(self, server):
        self.spider_status_name_dict = {
            SpiderStatus.PENDING: 'pending',
            SpiderStatus.RUNNING: 'running',
            SpiderStatus.FINISHED: 'finished'
        }
        super(ScrapydProxy, self).__init__(server)

    def _scrapyd_url(self):
        return self.server

    def get_project_list(self):
        data = request("get", self._scrapyd_url() + "/listprojects.json", return_type="json")
        result = []
        if data:
            for project_name in data['projects']:
                project = Project()
                project.project_name = project_name
                result.append(project)
        return result

    def delete_project(self, project_name):
        post_data = dict(project=project_name)
        data = request("post", self._scrapyd_url() + "/delproject.json", data=post_data, return_type="json")
        return True if data and data['status'] == 'ok' else False

    def get_spider_list(self, project_name):
        data = request("get", self._scrapyd_url() + "/listspiders.json?project=%s" % project_name,
                       return_type="json")
        result = []
        if data and data['status'] == 'ok':
            for spider_name in data['spiders']:
                spider_instance = SpiderInstance()
                spider_instance.spider_name = spider_name
                result.append(spider_instance)
        return result

    def get_daemon_status(self):
        pass

    def get_job_list(self, project_name, spider_status=None):
        data = request("get", self._scrapyd_url() + "/listjobs.json?project=%s" % project_name,
                       return_type="json")
        result = {SpiderStatus.PENDING: [], SpiderStatus.RUNNING: [], SpiderStatus.FINISHED: []}
        if data and data['status'] == 'ok':
            for _status in self.spider_status_name_dict.keys():
                for item in data[self.spider_status_name_dict[_status]]:
                    start_time, end_time = None, None
                    if item.get('start_time'):
                        start_time = datetime.datetime.strptime(item['start_time'], '%Y-%m-%d %H:%M:%S.%f')
                    if item.get('end_time'):
                        end_time = datetime.datetime.strptime(item['end_time'], '%Y-%m-%d %H:%M:%S.%f')
                    result[_status].append(dict(id=item['id'], start_time=start_time, end_time=end_time))
        return result if not spider_status else result[spider_status]

    def start_spider(self, project_name, spider_name, arguments):
        post_data = dict(project=project_name, spider=spider_name)
        post_data.update(arguments)
        data = request("post", self._scrapyd_url() + "/schedule.json", data=post_data, return_type="json")
        return data['jobid'] if data and data['status'] == 'ok' else None

    def cancel_spider(self, project_name, job_id):
        post_data = dict(project=project_name, job=job_id)
        data = request("post", self._scrapyd_url() + "/cancel.json", data=post_data, return_type="json")
        return data != None

    def deploy(self, project_name, file_path):
        with open(file_path, 'rb') as f:
            eggdata = f.read()
        res = requests.post(self._scrapyd_url() + '/addversion.json', data={
            'project': project_name,
            'version': int(time.time()),
            'egg': eggdata,
        })
        return res.text if res.status_code == 200 else None

    def log_url(self, project_name, spider_name, job_id):
        return self._scrapyd_url() + '/logs/%s/%s/%s.log' % (project_name, spider_name, job_id)


text:
use std::path::{PathBuf, Path};
use std::fs;
use std::error::Error;
use std::fmt;

#[cfg(feature = "cache")]
use time::{self, Timespec};
#[cfg(feature = "cache")]
use std::time::Duration;

use iron::prelude::*;
use iron::{Handler, status};
#[cfg(feature = "cache")]
use iron::modifier::Modifier;
use iron::modifiers::Redirect;
use mount::OriginalUrl;
use logfile_server::requested_path::RequestedPath;

/// The static file-serving `Handler`.
///
/// This handler serves files from a single filesystem path, which may be absolute or relative.
/// Incoming requests are mapped onto the filesystem by appending their URL path to the handler's
/// root path. If the filesystem path corresponds to a regular file, the handler will attempt to
/// serve it. Otherwise, if the path corresponds to a directory containing an `index.html`,
/// the handler will attempt to serve that instead.
///
/// ## Errors
///
/// If the path doesn't match any real object in the filesystem, the handler will return
/// a Response with `status::NotFound`. If an IO error occurs whilst attempting to serve
/// a file, `FileError(IoError)` will be returned.
#[derive(Clone)]
pub struct Static {
    /// The path this handler is serving files from.
    pub root: PathBuf,
    #[cfg(feature = "cache")]
    cache: Option<Cache>,
}

impl Static {
    /// Create a new instance of `Static` with a given root path.
    ///
    /// If `Path::new("")` is given, files will be served from the current directory.
    #[cfg(feature = "cache")]
    pub fn new<P: Into<PathBuf>>(root: P) -> Static {
        Static {
            root: root.into(),
            cache: None
        }
    }

    /// Create a new instance of `Static` with a given root path.
    ///
    /// If `Path::new("")` is given, files will be served from the current directory.
    #[cfg(not(feature = "cache"))]
    pub fn new<P: Into<PathBuf>>(root: P) -> Static {
        Static {
            root: root.into(),
        }
    }

    /// Specify the response's `cache-control` header with a given duration. Internally, this is
    /// a helper function to set a `Cache` on an instance of `Static`.
    ///
    /// ## Example
    ///
    /// ```ignore
    /// let cached_static_handler = Static::new(path).cache(Duration::from_secs(30*24*60*60));
    /// ```
    #[cfg(feature = "cache")]
    pub fn cache(self, duration: Duration) -> Static {
        self.set(Cache::new(duration))
    }

    #[cfg(feature = "cache")]
    fn try_cache<P: AsRef<Path>>(&self, req: &mut Request, path: P) -> IronResult<Response> {
        match self.cache {
            None => Ok(Response::with((status::Ok, path.as_ref()))),
            Some(ref cache) => cache.handle(req, path.as_ref()),
        }
    }
}

impl Handler for Static {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        use std::io;

        let requested_path = RequestedPath::new(&self.root, req);

        let metadata = match fs::metadata(&requested_path.path) {
            Ok(meta) => meta,
            Err(e) => {
                let status = match e.kind() {
                    io::ErrorKind::NotFound => status::NotFound,
                    io::ErrorKind::PermissionDenied => status::Forbidden,
                    _ => status::InternalServerError,
                };

                return Err(IronError::new(e, status))
            },
        };

        // If the URL ends in a slash, serve the file directly.
        // Otherwise, redirect to the directory equivalent of the URL.
        if requested_path.should_redirect(&metadata, req) {
            // Perform an HTTP 301 Redirect.
            let mut redirect_path = match req.extensions.get::<OriginalUrl>() {
                None => &req.url,
                Some(original_url) => original_url,
            }.clone();

            // Append the trailing slash
            //
            // rust-url automatically turns an empty string in the last
            // slot in the path into a trailing slash.
            redirect_path.path.push("".to_string());

            return Ok(Response::with((status::MovedPermanently,
                                      format!("Redirecting to {}", redirect_path),
                                      Redirect(redirect_path))));
        }

        match requested_path.get_file(&metadata) {
            // If no file is found, return a 404 response.
            None => Err(IronError::new(NoFile, status::NotFound)),
            // Won't panic because we know the file exists from get_file.
            #[cfg(feature = "cache")]
            Some(path) => self.try_cache(req, path),
            #[cfg(not(feature = "cache"))]
            Some(path) => {
                let path: &Path = &path;
                Ok(Response::with((status::Ok, path)))
            },
        }
    }
}

impl Set for Static {}

/// A modifier for `Static` to specify a response's `cache-control`.
#[cfg(feature = "cache")]
#[derive(Clone)]
pub struct Cache {
    /// The length of time the file should be cached for.
    pub duration: Duration,
}

#[cfg(feature = "cache")]
impl Cache {
    /// Create a new instance of `Cache` with a given duration.
    pub fn new(duration: Duration) -> Cache {
        Cache { duration: duration }
    }

    fn handle<P: AsRef<Path>>(&self, req: &mut Request, path: P) -> IronResult<Response> {
        use iron::headers::{IfModifiedSince, HttpDate};

        let path = path.as_ref();

        let last_modified_time = match fs::metadata(path) {
            Err(error) => return Err(IronError::new(error, status::InternalServerError)),
            Ok(metadata) => {
                use filetime::FileTime;

                let time = FileTime::from_last_modification_time(&metadata);
                Timespec::new(time.seconds() as i64, time.nanoseconds() as i32)
            },
        };

        let if_modified_since = match req.headers.get::<IfModifiedSince>().cloned() {
            None => return Ok(self.response_with_cache(path, last_modified_time)),
            Some(IfModifiedSince(HttpDate(time))) => time.to_timespec(),
        };

        if last_modified_time <= if_modified_since {
            Ok(Response::with(status::NotModified))
        } else {
            Ok(self.response_with_cache(path, last_modified_time))
        }
    }

    fn response_with_cache<P: AsRef<Path>>(&self, path: P, modified: Timespec) -> Response {
        use iron::headers::{CacheControl, LastModified, CacheDirective, HttpDate};

        let mut response = Response::with((status::Ok, path.as_ref()));
        let seconds = self.duration.as_secs() as u32;
        let cache = vec![CacheDirective::Public, CacheDirective::MaxAge(seconds)];
        response.headers.set(CacheControl(cache));
        response.headers.set(LastModified(HttpDate(time::at(modified))));
        response
    }
}

#[cfg(feature = "cache")]
impl Modifier<Static> for Cache {
    fn modify(self, static_handler: &mut Static) {
        static_handler.cache = Some(self);
    }
}

/// Thrown if no file is found. It is always accompanied by a NotFound response.
#[derive(Debug)]
pub struct NoFile;

impl Error for NoFile {
    fn description(&self) -> &str { "File not found" }
}

impl fmt::Display for NoFile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.description())
    }
}


text:
package com.google.javascript.jscomp;

import com.google.common.annotations.VisibleForTesting;
import com.google.javascript.jscomp.PolyfillUsageFinder.Polyfill;
import com.google.javascript.jscomp.PolyfillUsageFinder.PolyfillUsage;
import com.google.javascript.jscomp.PolyfillUsageFinder.Polyfills;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.resources.ResourceLoader;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Injects polyfill libraries to ensure that ES6+ library functions are available.
 *
 *
Also runs if polyfill isolation is enabled, even if polyfill injection is disabled, in order
 * to prevent deletion of a required library function by dead code elimination.
 *
 *
TODO(b/120486392): consider merging this pass with {@link InjectRuntimeLibraries} and {@link
 * InjectTranspilationRuntimeLibraries}.
 */
public class RewritePolyfills implements HotSwapCompilerPass {

  static final DiagnosticType INSUFFICIENT_OUTPUT_VERSION_ERROR = DiagnosticType.disabled(
      "JSC_INSUFFICIENT_OUTPUT_VERSION",
      "Built-in ''{0}'' not supported in output version {1}");

  private final AbstractCompiler compiler;
  private final Polyfills polyfills;
  private final boolean injectPolyfills;
  private final boolean isolatePolyfills;
  private Set<String> libraries;

  /**
   * @param injectPolyfills if true, injects $jscomp.polyfill initializations into the first input.
   *     if false, no polyfills are injected.
   * @param isolatePolyfills if true, adds externs for library functions used by {@link
   *     IsolatePolyfills} to prevent their deletion.
   */
  public RewritePolyfills(
      AbstractCompiler compiler, boolean injectPolyfills, boolean isolatePolyfills) {
    this(
        compiler,
        Polyfills.fromTable(
            ResourceLoader.loadTextResource(RewritePolyfills.class, "js/polyfills.txt")),
        injectPolyfills,
        isolatePolyfills);
  }

  @VisibleForTesting
  RewritePolyfills(
      AbstractCompiler compiler,
      Polyfills polyfills,
      boolean injectPolyfills,
      boolean isolatePolyfills) {
    this.compiler = compiler;
    this.polyfills = polyfills;
    this.injectPolyfills = injectPolyfills;
    this.isolatePolyfills = isolatePolyfills;
  }

  @Override
  public void hotSwapScript(Node scriptRoot, Node originalRoot) {
    if (this.isolatePolyfills) {
      // Polyfill isolation requires a pass to run near the end of optimizations. That pass may call
      // into a library method injected in this pass. Adding an externs declaration of that library
      // method prevents it from being dead-code-elimiated before polyfill isolation runs.
      Node jscompLookupMethodDecl = IR.var(IR.name("$jscomp$lookupPolyfilledValue"));
      compiler
          .getSynthesizedExternsInputAtEnd()
          .getAstRoot(compiler)
          .addChildToBack(jscompLookupMethodDecl);
      compiler.reportChangeToEnclosingScope(jscompLookupMethodDecl);
    }

    if (!this.injectPolyfills) {
      // Nothing left to do. Probably this pass only needed to run because --isolate_polyfills is
      // enabled but not --rewrite_polyfills.
      return;
    }

    this.libraries = new LinkedHashSet<>();
    new PolyfillUsageFinder(compiler, polyfills).traverseExcludingGuarded(scriptRoot, this::inject);

    if (libraries.isEmpty()) {
      return;
    }

    Node lastNode = null;
    for (String library : libraries) {
      lastNode = compiler.ensureLibraryInjected(library, false);
    }
    if (lastNode != null) {
      Node parent = lastNode.getParent();
      removeUnneededPolyfills(parent, lastNode.getNext());
      compiler.reportChangeToEnclosingScope(parent);
    }
  }

  // Remove any $jscomp.polyfill calls whose 3rd parameter (the language version
  // that already contains the library) is the same or lower than languageOut.
  private void removeUnneededPolyfills(Node parent, Node runtimeEnd) {
    Node node = parent.getFirstChild();
    while (node != null && node != runtimeEnd) {
      Node next = node.getNext();
      if (NodeUtil.isExprCall(node)) {
        Node call = node.getFirstChild();
        Node name = call.getFirstChild();
        if (name.matchesQualifiedName("$jscomp.polyfill")) {
          final String nativeVersionStr = name.getNext().getNext().getNext().getString();
          final FeatureSet outputFeatureSet = compiler.getOptions().getOutputFeatureSet();
          if (outputFeatureSet.contains(FeatureSet.valueOf(nativeVersionStr))) {
            NodeUtil.removeChild(parent, node);
            NodeUtil.markFunctionsDeleted(node, compiler);
          }
        }
      }
      node = next;
    }
  }

  @Override
  public void process(Node externs, Node root) {
    hotSwapScript(root, null);
  }

  private void inject(PolyfillUsage polyfillUsage) {
    Polyfill polyfill = polyfillUsage.polyfill();
    final FeatureSet outputFeatureSet = compiler.getOptions().getOutputFeatureSet();
    final FeatureSet featuresRequiredByPolyfill = FeatureSet.valueOf(polyfill.polyfillVersion);
    if (polyfill.kind.equals(Polyfill.Kind.STATIC)
        && !outputFeatureSet.contains(featuresRequiredByPolyfill)) {
      compiler.report(
          JSError.make(
              polyfillUsage.node(),
              INSUFFICIENT_OUTPUT_VERSION_ERROR,
              polyfillUsage.name(),
              outputFeatureSet.version()));
    }

    // The question we want to ask here is:
    // "Does the target platform already have the symbol this polyfill provides?"
    // We approximate it by asking instead:
    // "Does the target platform support all of the features that existed in the language
    // version that introduced this symbol?"
    if (!outputFeatureSet.contains(FeatureSet.valueOf(polyfill.nativeVersion))
        && !polyfill.library.isEmpty()) {
      libraries.add(polyfill.library);
    }
  }
}


text:
package org.sprintapi.api.vm.common;

public interface FlowNode extends FlowElement {

	SequenceFlow[] getIncoming();
	SequenceFlow[] getOutgoing();

}


text:
var AWS = require('../core');

AWS.util.update(AWS.RDSDataService.prototype, {
  /**
   * @return [Boolean] whether the error can be retried
   * @api private
   */
  retryableError: function retryableError(error) {
    if (error.code === 'BadRequestException' &&
      error.message &&
      error.message.match(/^Communications link failure/) &&
      error.statusCode === 400) {
      return true;
    } else {
      var _super = AWS.Service.prototype.retryableError;
      return _super.call(this, error);
    }
  }
});


text:
package com.iflytek.weef.controller;

import com.alibaba.fastjson.JSON;
import com.iflytek.weef.base.BaseController;
import com.iflytek.weef.dto.*;
import com.iflytek.weef.service.InfoServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 资讯相关服务
 * 1.域名 2.新闻等 3.健康知识等faq信息
 * @author czhu2
 */
@RestController
@RequestMapping(value = "info")
public class InfoController extends BaseController{
    private static final Logger logger  = LoggerFactory.getLogger(InfoController.class);

    @Resource
    private InfoServiceImpl infoService;

    /**
     * 检查域名是否可用
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/domain/check",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> checkDomain(String name, String suffix, HttpServletRequest request, HttpServletResponse response){
        ResponseEntity<BaseHttpResponse> responseResponseEntity = null;

        if(StringUtils.isEmpty(name) || StringUtils.isEmpty(suffix)){
            logger.error("请求参数不完整,name:{},suffix:{}",name,suffix);
            return   createJsonResponse(BaseHttpRespCode.PARAM_MISS);
        }

        DomainDto domainDto = infoService.queryDomain(name, suffix);

        if(domainDto != null ){
            responseResponseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),
                    BaseHttpRespCode.SUCCESS.getValue(),domainDto);
        }else{
            responseResponseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
        }
        return responseResponseEntity;
    }

    /**
     * 查询系统配置
     * 1.域名下拉列表 2.快递列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/sysconfig/query",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> getSysConfig(String type, HttpServletRequest request, HttpServletResponse response){
        ResponseEntity<BaseHttpResponse> responseResponseEntity = null;

        try {
            if(StringUtils.isEmpty(type)){
                logger.error("请求参数不完整,type:{}",type);
                return   createJsonResponse(BaseHttpRespCode.PARAM_MISS);
            }
            List<SysconfigDto> list = infoService.getSysConfig(type);

            if(list != null ){
                responseResponseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),
                        BaseHttpRespCode.SUCCESS.getValue(),list);
            }else{
                responseResponseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            }
        } catch (Exception e) {
            logger.error("请求查询系统配置,发生异常",e);
        }
        return responseResponseEntity;
    }

    /**
     * faq查询
     * @param question
     * @param type  1 faq机器人问题 2.名人名言
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/faq/query",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> queryFaq(String question,int type, HttpServletRequest request, HttpSession session){

        if(logger.isInfoEnabled()){
            logger.info("请求查询faq ,question:{}",question);
        }

        ResponseEntity<BaseHttpResponse> responseEntity = null;
        try {
            responseEntity = null;

            List<FaqAnswerDto> faqAnswerDtos = infoService.queryFaq(question, type);

            if(logger.isInfoEnabled()){
                logger.info("请求查询faq,查询到结果,{}", JSON.toJSONString(faqAnswerDtos));
            }

            if(faqAnswerDtos != null && faqAnswerDtos.size() > 0){
                responseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),BaseHttpRespCode.SUCCESS.getValue(),faqAnswerDtos);
            }else{
                responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            }

        } catch (Exception e) {
            responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            logger.error("请求查询faq,发生异常",e);
        }

        return responseEntity;

    }

    /**
     * 评估手机号、qq等号码
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/number/query",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> numberEvaluate(String number, HttpServletRequest request, HttpSession session){

        if(logger.isInfoEnabled()){
            logger.info("请求查询number:{}",number);
        }

        ResponseEntity<BaseHttpResponse> responseEntity = null;
        try {
            responseEntity = null;

            if(StringUtils.isEmpty(number)){
                logger.error("请求参数不完整,number:{}",number);
                return   createJsonResponse(BaseHttpRespCode.PARAM_MISS);
            }

            NumberDto numberDto = infoService.evaluateNumber(number);

            if(numberDto != null){
                responseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),BaseHttpRespCode.SUCCESS.getValue(),numberDto);
            }else{
                responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            }

        } catch (Exception e) {
            responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            logger.error("请求查询faq,发生异常",e);
        }

        return responseEntity;

    }
    /**
     * 问候语等励志语句
     * @param request
     * @param session
     * @return
     */

    @RequestMapping(value = "/greeting/query",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> greetingQuery(Integer number, HttpServletRequest request, HttpSession session){

        if(logger.isInfoEnabled()){
            logger.info("请求查询励志语句,number:{}",number);
        }

        ResponseEntity<BaseHttpResponse> responseEntity = null;
        try {
            if(number < 0){
                logger.error("请求参数不完整,number:{}",number);
                return   createJsonResponse(BaseHttpRespCode.PARAM_MISS);
            }

            String res = infoService.greetingQuery(String.valueOf(number));

            if(StringUtils.isNoneBlank(res)){
                responseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),BaseHttpRespCode.SUCCESS.getValue(),res);
            }else{
                responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            }

        } catch (Exception e) {
            responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            logger.error("请求查询faq,发生异常",e);
        }

        return responseEntity;

    }

    @RequestMapping(value = "/chengyu/query",method = RequestMethod.GET)
    public ResponseEntity<BaseHttpResponse> chengyuQuery(Integer type,
                                                         String keyword,
                                                         Integer pageIndex,
                                                         Integer pageSize,
                                                         HttpServletRequest request, HttpSession session){

        if(logger.isInfoEnabled()){
            logger.info("请求查询成语语句,type:{}",type);
        }

        ResponseEntity<BaseHttpResponse> responseEntity = null;
        try {

            // TODO: 2017/11/27 实现
            String res =   infoService.chengyuQuery(type,pageIndex,pageSize,keyword);

            if(StringUtils.isNoneBlank(res)){
                responseEntity = createJsonResponse(BaseHttpRespCode.SUCCESS.getKey(),BaseHttpRespCode.SUCCESS.getValue(),res);
            }else{
                responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            }

        } catch (Exception e) {
            responseEntity = createJsonResponse(BaseHttpRespCode.FAIL);
            logger.error("请求查询faq,发生异常",e);
        }

        return responseEntity;

    }

    /**
     * 请求客户会话回答,
     * 1.如果页面能满足,则直接进行业务回答
     * 2.业务不能满足,进行智能机器人回复应答
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/kefu/query",method = RequestMethod.GET)
    public String kefuQuery(HttpServletRequest request, HttpSession session){

        if(logger.isInfoEnabled()){
            logger.info("请求客服服务");
        }

        String info = request.getParameter("info");
//        String returnStr = infoService.checkSignature(request);

        String msg = StringUtils.EMPTY;
        try {

//            msg = bizReply(info);
//            /*业务逻辑回复成功,直接返回,否则进行机器人回复*/
//            if(StringUtils.isNoneBlank(msg)){
//                return msg;
//            }else{
                msg = infoService.robotReply(info);
//            }
        } catch (Exception e) {
            logger.error("请求客服服务,发生异常",e);
        }

        return msg;

    }

    /**
     * 业务逻辑客服
     * @param info
     * @return
     */
    private String bizReply(String info) {
        return "success";
    }

}


text:
import assert from "power-assert";
import Junction from "../../src/connect/junction";
describe("junction", function () {
    context("when register middlewares", function () {
        it("should connect middleware, the order is register", function (done) {
            let junction = new Junction();
            junction.use(function errorHandling(error, text, next) {
                next(error);
            });
            junction.use(function toUpper(res, next) {
                res.value = res.value.toLocaleUpperCase();
                next();
            });
            junction.use(function addDesu(res, next) {
                res.value += " suffix";
                next();
            });
            junction.process("text", (error, result) => {
                if (error) {
                    return done(error);
                }
                assert.equal(result.value, "TEXT suffix");
                done();
            });
        });
    });
    context("when occur error in middleware", function () {
        it("should call errorHandling middleware", function (done) {
            let junction = new Junction();
            junction.use(function toUpper(res) {
                throw new Error("error on " + res);
            });
            junction.use(function errorHandling(error, res, next) {
                assert(error instanceof Error);
                assert.equal(res.value, "text");
                next();
            });
            junction.process("text", (error, res) => {
                if (error) {
                    return done(error);
                }
                assert.equal(res.value, "text");
                done();
            });
        });
    });
});


text:
Harry Potter TCG (Unity)
========================

A rewrite of my forever-project in the Unity game engine, initially written in Flash Actionscript 3.0.

Introduction
------------
HPTCG is a recreation of the old Harry Potter Trading Card Game developed (and sadly discontinued) by Wizards of the Coast.
The initial focus of this project was a single player experience through AI opponents and random deck generation for replayability, the goal has since shifted to implementing a multiplayer client with random matchmaking for players to connect to each other from anywhere. This was made possible by the switch to the Unity3D game engine and the Photon Cloud service.

Once the main game is implemented the plan is to create a tutorial scene that introduces players to the game and allows them to try out many deck combinations before hopping into the matchmaking service.

Features
--------
* Multiplayer Matchmaking, pits two players with randomly generated decks against each other.
* A basic tutorial explaning how the game works. (WIP)
* A progress system to track the player's achievements and wins/losses, maybe an achievement system to track the player's various accomplishments in each game. (WIP)
* A deck editor for constructed play further down the line. (WIP)

To Test the Project
-------------------
You can find a build of the project in the releases tab, read there for more details on what  the current public version entails.

I don't expect there to be a ton of people using this, as it is quite a niche project, but you can now download the game and hop into the matchmaking service without needing to compile it yourself!

If you have no one to play with, you can test the game against yourself, to do so, you can open up multiple instances of the game and hit Find Match at the same time. Once the two clients are connected the decks will appear and automatically shuffle, each player will draw 7 cards and the first turn will begin.

Basic functionality has been implemented and you should be able to complete a game against another player, you will probably notice that there aren't that many cards implemented, I have spent the past few months working on the infrastructure that will allow more complicated cards to be thrown into the random card pool, you can expect the card pool to grow substantially in the next few months as the more complicated features get built into the engine.

Thanks for reading and enjoy the game! Feel free to drop me a message if you enjoy it.


text:
namespace PH
{
    USING_NS_CC;

	struct Level
	{
        std::string id;
		std::string name;
		int cost;
		int roundCount;
        int level;
        int cleared;

        int levelLimit;
        std::vector<int> dropsHint;
        //std::string levelHint;
	};

    enum StageEvent
    {
        NoEvent = 0,
        SpiritHalf = 1,
        DropTwice = 2,
        DropOneDotFive = 3,
        CoinsTwice = 4,
    };

    struct Stage
    {
        std::string id;
        std::string name;

        StageEvent event;

        boost::posix_time::ptime visibleStart, visibleEnd;

        int startTimeStamp;
        int endTimeStamp;
        int stage;
        int dailyQuota;     // 每日刷关次数,-1无限
        //int progress; // -1 reserved for no limit symbol
        bool rewardAvailable; // 全S通关是否已经领取
        bool hasReward; // 是否有全S通关奖励配置
        int dailyInstanceProgress;

        GemUtils::GemColor stageColor;
        std::string hint;
        //std::vector<int> dropsHint;

        std::vector<Level> levelList;

        const Level* findLevelById(std::string& idd)
        {
            for(Level& l : levelList)
            {
                if(l.id == idd)
                    return &l;
            }
            return NULL;
        }

        bool isAllPass() const
        {
            for(const Level& level : levelList)
                if(level.cleared != 1)
                    return false;
            return true;
        }
    };
    typedef boost::shared_ptr<Stage> StagePtr;

    struct DailyStage
    {
        int progress;
        StagePtr stage;
    };

    struct Account
    {
        std::string type;
        std::string id;
    };

    enum LoginRewardType
    {
        Reward_Exp = 0,
        Reward_Coins,
        Reward_Gold,
        Reward_Hero,
        Reward_Soul,
        Reward_PercentExp,
        Reward_PercentCoins
    };

    struct Treasure
    {
        int type;
        int count;
        int ident;
        int level;

        Treasure(){};
        Treasure(int type, int count)
        {
            this->type = type;
            this->count = count;
        };
    };

    typedef std::vector<Treasure> LoginRewards;
    typedef std::vector<Treasure> VictoryRewards;
    typedef std::vector<Treasure> ChestRewards;
    typedef std::vector<Treasure> TaskRewards;

    struct Reward
    {
        int totalCoins, totalGolds;
        std::string html;
    };

    struct VIPPack
    {
        int pid;
        int availableAtLevel;
        int price, showPrice;

        std::vector<Treasure> items;
        bool purchased;
        bool isHeroesPack() const
        {
            if(items.empty())return false;
            for(const Treasure& t : items)
                if(t.type != LoginRewardType::Reward_Hero || HPT(t.ident).isMat())
                    return false;
            return true;
        }
    };

    enum class PlayerTaskType
    {
        NoneCond = 1,
        LevelClear = 2,
        LevelS = 3,
        UserLevel = 4,
        DailyHelperAward = 5,
        HelperAwardNum = 6,
        FriendsNum = 7,
        StorageLimit = 8,

        PayGolds = 18,
        PayStorage = 10,
        PaySpirit = 11,
        PayNiceHeroDraw = 12,
        PayExpItems = 13,
        PayTransItems = 14,
        PayRevive = 15,

        VIPLevel = 16,
        LevelSCount = 17,

        Spending = 9,
        ItemStorage = 19,

        DailyLevelClearCount = 20,
        DailyPayGoldsAmount = 21,
        Succeed3StarsInDraw10Heroes = 22,
        SucceedTransformHero = 23,
        SucceedChangeRelations = 24,

        MaxRelations = 25,

        SucceedExchangeBySoul = 26,
        SucceedPromoteEliteLevel = 27
    };

    enum class PlayerTaskCategory
    {
        Normal = 0,
        Daily = 1,
        Newbie = 2,
        Purchase = 3
    };

    // LevelClear, LevelS, LevelSCount 需要跳转到江湖
    // VIPLevel, PayGolds, PayStorage, PaySpirit, PayNiceHeroDraw, PayExpItems,
    // PayTransItems, StorageLimit 需要跳转到商店
    // 其他待定

    struct PlayerTask
    {
        int tid;
        PlayerTaskType type;
        PlayerTaskCategory category;
        std::string name, desc;
        int progress, total;
        int index, position;

        std::vector<Treasure> sample;
    };

    typedef std::vector<PlayerTask> PlayerTaskVec;

	struct Player
	{
        virtual ~Player()
        {
            for(auto& h : storage)
                if(h)
                {
                    delete h;
                    h = NULL;
                }
        }

        std::string uid;
        std::string name;

        int level;
        int exp;
        int coins;
        int golds;

        int nextLevelExp;

        int spirit, maxSpirit;
        int maxLP, maxFriends;

        int lastLoginTS;
		int spiritCheckTime;

        std::string token, referCode;

        std::vector<Account> accounts;
        std::vector<int> drawFreeTime;

        // team stores pointer to heroes in storage
		std::vector<Hero*> team;
        int activeTeam;
        int activeTeamScore, dailyJudgmentCount;

        std::vector<Hero*> storage;
        int storageLimit;

        std::vector<int> seen, owned;

        std::map<int, int> heroSouls;

        int pvpReputation;
        int pvpScore;
        int pvpRank, pvpKeys;

        double pvpWinRate;

        bool isFriend;
        int asHelperReward;

        int pendingFriendRequests;
        int vipLevel, spent;
        int drawsLeft, expDrawsLeft, transDrawsLeft;

        //
        VictoryRewards rewards;
        int availableRewardsCount;
        bool isFirstScoreAfterBattle;
        //

        Hero* findHero(const std::string& hid);
        Hero* getMainHero(){return team[activeTeam*5];};
	};
    typedef boost::shared_ptr<Player> PlayerPtr;

    struct Mail
    {
        std::string id;

        std::string sender;
        std::string message;
        std::vector<Treasure> package;
        boost::posix_time::ptime time;

        bool read, packageOpened;
    };

    struct MailBox
    {
        std::vector<Mail> mails;
        boost::posix_time::ptime mailSince;
    };

    struct VipUpgrade
    {
        int coins, golds, pvpKeys;
        int lastVIPLevel, newVIPLevel;
        std::vector<boost::shared_ptr<Stage>> stages, fbs;
        std::vector<Hero> expItems;
    };

    enum class SkillBonusChangeType
    {
        Golds = 0,
        Potions = 1
    };

    enum class RelationChangeType
    {
        Free = 0,
        Golds = 1,
        Potions = 2
    };

    struct BoolWrapper
    {
        bool ok;
    };

    struct RankingItem
    {
        std::string ident;
        std::string owner;
        int hostLevel, score;
        int flower, egg;
        std::vector<boost::shared_ptr<Hero>> team;
    };

    enum class RankingType
    {
        Team_Fire = 0,
        Team_Water = 1,
        Team_Wood = 2,
        Team_Dark = 3,
        Team_Light = 4,
        Team_All = 5,
        Team_Mix = 6,
        Player_Level = 7
    };

    struct RankingList
    {
        std::vector<RankingItem> table;
        int hostRank, rankDelta, hostScore;
    };

    typedef std::vector<RankingList> RankingListVec;

    struct PlayerRankList
    {
        ~PlayerRankList()
        {
            for (auto p : players)
                delete p;
        }

        std::vector<Player*> players;

        int myRank;
    };

    struct PvPGameLog
    {
        std::string rivalName;
        int oldRank, newRank;
        int oldRep, newRep;
        int result;

        boost::posix_time::ptime time;
        PvPGameLog(){};
        PvPGameLog(std::string n):rivalName(n){};
    };

    struct PvPGameLogList
    {
        std::vector<PvPGameLog> logs;
    };

    struct PlayerList
    {
        ~PlayerList()
        {
            for (auto p : players)
                delete p;
        }

        std::vector<Player*> players;

        int userCount;
    };

    struct StoreItem
    {
        std::string channel;
        std::string productId;
        std::string productName;
        std::string localizePrice;

        int amount;
        int price;

        int goldPerDay;

        float promotion;
    };

    enum class PvPStoreItemType : int
    {
        RelationPill = 1,
        SkillPill    = 2,
        ElitePill    = 3,
    };

    struct PvPStoreItem
    {
        int sid;
        PvPStoreItemType itemType;
        int price;
        int amount;

        std::string name, desc;
    };

    struct Control
    {
        std::string annoucement;
        std::vector<int> drawNiceHeroPrices;
        std::vector<int> vipLevelSpent;

        Reward rewards;
        LoginRewards loginRewards;
        std::vector<int> path;

        std::vector<StoreItem> store, monthly;
        std::vector<PvPStoreItem> pvpStore;
        std::vector<boost::shared_ptr<Stage>> stages, fbs;
        std::vector<DailyStage> dailystages;
        std::vector<VIPPack> vipGifts, otherVipGifts;

        int maxLevel;
        int tutorialStage;

        long long serverTime;
        int spiritRecoverSecs;

        std::string drawHeroImgURL, headVersion;
        bool forceUpgrade;

        bool pvpOptIn;
        bool showVIPDraw, showVIPTenDraw;
        int dailyFreeRelationChangeCount;
        bool isFirstScoreAfterBattle;

        std::string getRewardsString() const;

        int taskHints;

        std::string serverURL;
        bool hasPromotion;

        boost::posix_time::ptime pvpStart, pvpEnd;
    };
}