text:
set :application, "Poky"
set :repository,  "git@github.com:drsnyder/poky.git"

set :scm, :git
set :deploy_via, :copy
set :deploy_to, "/var/www/poky"
set :user, "deployer"
set :group, "deployer"
set :use_sudo, false
set :use_varnish, false

deploy_env = {}

task :setup do
  # see config/poky.defaults
  deploy_env['POKY_PORT']  = fetch(:poky_port, 9091); # if you change here, change in default.vcl
  deploy_env['JMX_PORT']   = fetch(:jmx_port, 9101)
  deploy_env["STATSD_HOST"] = fetch(:statsd_host, "utility002:8125")
  deploy_env["STATSD_KEY_BASE"] = fetch(:statsd_key_base, "poky")

  # see config/varnish.defaults
  deploy_env['VARNISHD'] = fetch(:varnishd, "/usr/local/sbin/varnishd")
  deploy_env['VARNISH_LISTEN_ADDRESS'] = fetch(:varnish_listen_address, "")
  deploy_env['VARNISH_LISTEN_PORT'] = fetch(:varnish_listen_port, 8080)

  # amount of storage to supply to varnish in bytes. use k / M / G suffix
  deploy_env['VARNISH_STORAGE_SIZE'] = fetch(:varnish_storage_size, "1024M")

  deploy_env["VARNISH_PURGE_HOST"] = fetch(:varnish_purge_host, "localhost")
  deploy_env["VARNISH_PURGE_PORT"] = deploy_env['VARNISH_LISTEN_PORT']
end

desc "Deploy to the poky development environment."
task :development do
  setup
  host = "dev.poky.huddler.com"
  role :app, host
  deploy_env["VARNISH_PURGE_HOST"] = host
  deploy_env["DATABASE_URL"] = fetch(:database_url,"postgresql://postgres@#{host}/poky_dev")
  deploy_env["STATSD_KEY_BASE"] = "poky.dev"
end

desc "Deploy to the poky qa environment."
task :qa do
  setup
  host = "qa.poky.huddler.com"
  role :app, host
  deploy_env["VARNISH_PURGE_HOST"] = host
  deploy_env["DATABASE_URL"] = fetch(:database_url,"postgresql://postgres@#{host}/poky_qa")
  deploy_env["STATSD_KEY_BASE"] = "poky.qa"
end

desc "Deploy to the poky production environment."
task :production do
  setup
  host = "prod.poky.huddler.com"
  role :app, host
  deploy_env["VARNISH_PURGE_HOST"] = host
  deploy_env["DATABASE_URL"] = fetch(:database_url,"postgresql://postgres@#{host}/poky")
  deploy_env["STATSD_HOST"] = "utility002-private:8125"
  deploy_env["VARNISH_STORAGE_SIZE"] = "8192M"
  deploy_env["VARNISH_MAX_THREADS"] = "2000"
  deploy_env["VARNISH_THREAD_POOLS"] = "8"
  deploy_env["STATSD_KEY_BASE"] = "poky.prod"
  deploy_env["NEWRELIC_AGENT"] = "-javaagent:/var/lib/newrelic/newrelic.jar"
end

namespace :poky do

  desc "Stop the poky HTTP service."
  task :stop, :roles => :app do
    run "#{current_release}/scripts/poky.init.sh stop" unless fetch(:poky_skip_stop, false) or fetch(:skip_stop, false)
  end

  desc "Start the poky HTTP service."
  task :start, :roles => :app do
    run "#{release_path}/scripts/poky.init.sh start" unless fetch(:poky_skip_start, false)
  end

  desc "Check that the poky service is up and running."
  task :check, :roles => :app do
    run "curl -s http://localhost:#{deploy_env['POKY_PORT']}/status"
  end

end

namespace :varnish do

  desc "Stop varnish."
  task :stop, :roles => :app do
    run "#{current_release}/scripts/varnish.init.sh stop" unless fetch(:varnish_skip_stop, false) or fetch(:skip_stop, false)
  end

  desc "Start varnish."
  task :start, :roles => :app do
    run "#{release_path}/scripts/varnish.init.sh start" unless fetch(:varnish_skip_start, false)
  end

  desc "Check that varnish is up and running."
  task :check, :roles => :app do
    # if VARNISH_LISTEN_ADDRESS is empty, use localhost. in this case, any
    # interface will do
    listen = deploy_env['VARNISH_LISTEN_ADDRESS'].empty? ? "localhost" : deploy_env['VARNISH_LISTEN_ADDRESS']
    run "curl -s http://#{listen}:#{deploy_env['VARNISH_LISTEN_PORT']}/status"
  end

  desc "Reload the varnish config."
  task :reload, :roles => :app do
    run "#{current_release}/scripts/varnishreload"
  end

end

namespace :deploy do

  # allow -s branch=todeploy
  set :branch, fetch(:branch, "master")

  # allow -s build_script="/path/to/lein uberjar"
  set :build_script, fetch(:build_script, "lein clean && lein uberjar")

  task :stop, :roles => :app do
    poky.stop
    varnish.stop if fetch(:use_varnish, false)
  end

  task :start, :roles => :app do
    poky.start
    varnish.start if fetch(:use_varnish, false)
  end

  task :restart, :roles => :app do
    poky.stop
    poky.start

    if fetch(:use_varnish, false)
      varnish.stop
      varnish.start
    end
  end

  task :finalize_update do
    deploy_env.keys.each do |k|
      run "echo 'export #{k}=#{deploy_env[k]}' >> #{release_path}/config/environment"
    end
  end

  task :migrate do
    # noop
  end

  desc "Set the permissions on /var/www/poky. This enables deploy:setup."
  task :set_perms do
    sudo "mkdir -p /var/www/poky > /dev/null 2>&1 || true"
    sudo "chown #{user}:#{group} /var/www/poky"
  end

  task :update_symlinks do
    run "[ ! -d #{shared_path}/run ] && mkdir #{shared_path}/run || true"
    run "mkdir #{release_path}/tmp"
    run "ln -s #{shared_path}/log #{release_path}/log"
    run "ln -s #{shared_path}/run #{release_path}/run"
  end

  task :pause do
    puts
    puts "Waiting for poky to come up..."
    puts
    sleep 5
  end

end

after  "deploy:create_symlink",  "deploy:update_symlinks"
after  "deploy:update_symlinks", "deploy:migrate"
after  "deploy",                 "deploy:pause"
after  "deploy",                 "poky:check"
after  "deploy",                 "deploy:cleanup"

before "deploy:setup",           "deploy:set_perms"
after  "poky:stop",              "deploy:pause"

if fetch(:use_varnish, false)
  after  "varnish:stop",           "deploy:pause"
  after  "deploy",                 "varnish:check"
  after  "deploy",                 "varnish:reload"
end


text:
import { ChartHistogram } from "../../";

export = ChartHistogram;

redpajama_set_name: RedPajamaGithub


text:
using IbanLib.Countries;
using IbanLib.Domain;

namespace IbanLib
{
    /// <summary>
    ///     DefaultCountryResolver class.
    /// </summary>
    public class DefaultCountryResolver : ICountryResolver
    {
        /// <summary>
        ///     The method returns the corrispondent implementation of the interface ICountry or null searched bt the Country Code.
        /// </summary>
        /// <param name="countryCode">
        ///     The Country Code requested.
        /// </param>
        /// <returns>
        ///     The implementation of ICountry that corrisponds with the requested country code.
        /// </returns>
        public ICountry GetCountry(string countryCode)
        {
            return Getter.GetCountry(countryCode);
        }
    }
}


text:
/****************************************************************************
*   PROJECT: Platform-specific prototypes and definitions for the mac
*   FILE:    sqPlatformSpecific.h
*   CONTENT:
*
*   AUTHOR:  John Maloney, John McIntosh, and others.
*   ADDRESS:
*   EMAIL:   johnmci@smalltalkconsulting.com
*   RCSID:   $Id: sqPlatformSpecific.h 1708 2007-06-10 00:40:04Z johnmci $
*
*   Jan 22nd 2002, JMM type for squeak file offset
*   May 5th, 2002, JMM added define for plugin for CW
*   May 12th, 2002, JMM added SQUEAK_BUILTIN_PLUGIN for CW Pro
*   3.2.8b1 July 24th, 2002 JMM support for os-x plugin under IE 5.x
*   3.5.1  May 28th, 2003 JMM SQUEAK_BUILTIN_PLUGIN in PB defs
*	3.8.8b2 May 23rd, 2005 JMM Undef 64bit procedure function ptrs
*	3.8.14b1 Oct	,2006 JMM browser rewrite
*
   How to use this file:
   This file is for general platform-specific macros and declarations.
   Function prototypes that are unlikely to introduce name conflicts on
   other platforms can be added directly. Macro re-definitions or conflicting
   function prototypes can be wrapped in a #ifdefs. Alternatively, a customized
   version of this file can be used on that platform. The goal is to keep all
   the other header files generic across platforms. To override a definition or
   macro from sq.h, you must first #undef it, then provide the new definition.

   Define plugin for Netscape Plugin building, needed for CodeWarrior
*/

#ifdef macintoshSqueak
#if defined(TARGET_API_MAC_CARBON)
# include <Types.h>
#endif
#define ENABLE_URL_FETCH
/* replace the image file manipulation macros with functions */
#undef sqImageFile
#undef sqImageFileClose
#undef sqImageFileOpen
#undef sqImageFilePosition
#undef sqImageFileRead
#undef sqImageFileSeek
#undef sqImageFileWrite

#undef sqAllocateMemory

//64bit function pointers undef
#undef dispatchFunctionPointer
#undef dispatchFunctionPointerOnin

#undef squeakFileOffsetType
#define squeakFileOffsetType off_t

#include <unistd.h> /* for declaration of ftruncate */

#undef sqFTruncate
/* sqFTruncate should return 0 on success, ftruncate does also */
#define sqFTruncate(f,o) ftruncate(fileno(f), o)
#define ftell ftello
#define fseek fseeko

typedef FILE *sqImageFile;

#undef sqFilenameFromStringOpen
#undef sqFilenameFromString
void		sqFilenameFromStringOpen(char *buffer,sqInt fileIndex, long fileLength);
void		sqFilenameFromString(char *buffer,sqInt fileIndex, long fileLength);
void        sqImageFileClose(sqImageFile f);
sqImageFile sqImageFileOpen(char *fileName, char *mode);
squeakFileOffsetType       sqImageFilePosition(sqImageFile f);
size_t      sqImageFileRead(void *ptr, size_t elementSize, size_t count, sqImageFile f);
void        sqImageFileSeek(sqImageFile f, squeakFileOffsetType pos);
sqInt       sqImageFileWrite(void *ptr, size_t elementSize, size_t count, sqImageFile f);

#define allocateMemoryMinimumImageFileHeaderSize(heapSize, minimumMemory, fileStream, headerSize) \
	sqAllocateMemoryMac(heapSize, minimumMemory)
usqInt	    sqAllocateMemoryMac(sqInt minHeapSize, sqInt desiredHeapSize);

#define sqAllocateMemory(x,y) sqAllocateMemoryMac(x,&y);

/* override reserveExtraCHeapBytes() macro to reduce Squeak object heap size on Mac */
#undef reserveExtraCHeapBytes
#define reserveExtraCHeapBytes(origHeapSize, bytesToReserve) (origHeapSize - bytesToReserve)

/* undefine clock macros that are implemented as functions */
#undef ioLowResMSecs
#undef ioMicroMSecs
#undef ioMSecs
#if STACKVM /* In the Cog VMs time management is in sqUnixHeartbeat.c */
#define ioLowResMSecs ioMSecs /* i.e. use ioMSecs in sqUnixHeartbeat.c */
#else
#define ioMSecs ioMicroMSecs
#endif

/* macro to return from interpret() loop in browser plugin VM */
#define ReturnFromInterpret() return 0

// CARBON

#ifdef TARGET_API_MAC_CARBON
# undef TARGET_API_MAC_CARBON
# define TARGET_API_MAC_CARBON 1
#endif

#if defined(TARGET_API_MAC_CARBON)
/* prototypes missing from CW11 headers */
#include <TextUtils.h>
void CopyPascalStringToC(ConstStr255Param src, char* dst);
void CopyCStringToPascal(const char* src, Str255 dst);
#endif

/* Macro for inlined functions.
	As of 1.7, clang elides the original, even though global.
	gcc & icc don't elide the original
*/
#if defined(__clang__)
# define inline_and_export /* nada */
#else
# define inline_and_export inline
#endif

/* undef the memory routines for our logic */
#undef sqGrowMemoryBy
#undef sqShrinkMemoryBy
#undef sqMemoryExtraBytesLeft

sqInt sqGrowMemoryBy(sqInt memoryLimit, sqInt delta);
sqInt sqShrinkMemoryBy(sqInt memoryLimit, sqInt delta);
sqInt sqMemoryExtraBytesLeft(int flag);
#if COGVM || defined(HAVE_NATIVEBOOST)
extern void sqMakeMemoryExecutableFromTo(unsigned long, unsigned long);
extern void sqMakeMemoryNotExecutableFromTo(unsigned long, unsigned long);

extern int isCFramePointerInUse(void);
extern int osCogStackPageHeadroom(void);
extern void reportMinimumUnusedHeadroom(void);
#endif

/* warnPrintf is provided (and needed) on the win32 platform.
 * But it may be mentioned elsewhere, so provide a suitable def.
 */
#define warnPrintf printf

/* Thread support for thread-safe signalSemaphoreWithIndex and/or the COGMTVM */
#if STACKVM || NewspeakVM
# define sqLowLevelYield() sched_yield()
# include <pthread.h>
# define sqOSThread pthread_t
/* these are used both in the STACKVM & the COGMTVM */
# define ioOSThreadsEqual(a,b) pthread_equal(a,b)
# define ioCurrentOSThread() pthread_self()
# if COGMTVM
/* Please read the comment for CogThreadManager in the VMMaker package for
 * documentation of this API.
 */
typedef struct {
		pthread_cond_t	cond;
		pthread_mutex_t mutex;
		int				count;
	} sqOSSemaphore;
#  define ioDestroyOSSemaphore(ptr) 0
#  if !ForCOGMTVMImplementation /* this is a read-only export */
extern const pthread_key_t tltiIndex;
#  endif
#  define ioGetThreadLocalThreadIndex() ((long)pthread_getspecific(tltiIndex))
#  define ioSetThreadLocalThreadIndex(v) (pthread_setspecific(tltiIndex,(void*)(v)))
#  define ioOSThreadIsAlive(thread) (pthread_kill(thread,0) == 0)
#  define ioTransferTimeslice() sched_yield()
#  define ioMilliSleep(ms) usleep((ms) * 1000)
# endif /* COGMTVM */
#endif /* STACKVM || NewspeakVM */

#ifdef BROWSERPLUGIN
# undef insufficientMemorySpecifiedError
# undef insufficientMemoryAvailableError
# undef unableToReadImageError
# undef browserPluginReturnIfNeeded
# undef browserPluginInitialiseIfNeeded
# define insufficientMemorySpecifiedError() plugInNotifyUser("The amount of memory specified by the 'memory' EMBED tag is not enough for the installed Squeak image file.")
# define insufficientMemoryAvailableError() plugInNotifyUser("There is not enough memory to give Squeak the amount specified by the 'memory' EMBED tag.")
# define unableToReadImageError() plugInNotifyUser("Read failed or premature end of image file")
# define browserPluginReturnIfNeeded() if (plugInTimeToReturn()) {ReturnFromInterpret();}
# define browserPluginInitialiseIfNeeded()
#endif

//exupery
#define addressOf(x) &x

// From Joshua Gargus, for XCode 3.1
#ifdef __GNUC__
# undef EXPORT
# define EXPORT(returnType) __attribute__((visibility("default"))) returnType
# if !defined(VM_LABEL)
#	define VM_LABEL(foo) asm("\n.globl L" #foo "\nL" #foo ":")
# endif
#endif

#if !defined(VM_LABEL) || COGVM
# undef VM_LABEL
# define VM_LABEL(foo) 0
#endif
#endif /* macintoshSqueak */


text:
param($installPath, $toolsPath, $package, $project)

$codeTemplatesFolder = $project.ProjectItems.Item("CodeTemplates");

# Remove the templates for other languages
if ($project.Type -eq "C#") {
	$codeTemplatesFolder.ProjectItems.Item("AddController-VisualBasic").Delete();
	$codeTemplatesFolder.ProjectItems.Item("AddController-CSharp").Name = "AddController";
} elseif ($project.Type -eq "VB.NET")  {
	$codeTemplatesFolder.ProjectItems.Item("AddController-CSharp").Delete();
	$codeTemplatesFolder.ProjectItems.Item("AddController-VisualBasic").Name = "AddController";
}

# ASP.NET MVC uses a custom Text Template Host to scaffold views and controllers so clear the built in TextTemplatingFileGenerator from the Custom Tool property.
foreach($ttFile in $codeTemplatesFolder.ProjectItems.Item("AddController").ProjectItems){
	$ttFile.Properties.Item("CustomTool").Value = "";
}

foreach($ttLanguageFolder in $codeTemplatesFolder.ProjectItems.Item("AddView").ProjectItems){
	foreach($ttFile in $ttLanguageFolder.ProjectItems){
		$ttFile.Properties.Item("CustomTool").Value = "";
	}
}


text:
|      Name       |  Type   | Description                                                                                | Required |
| :-------------: | :-----: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------: |
|   cors_rules    |  Array  | A set of origins and methods (cross-origin access that you want to allow). The elements in each set of configuration items are explained as follows.                               |   Yes    |
| allowed_origin  | String  | An origin that you want to allow cross-domain requests from. This can contain at most one * wild character.                                                                        |   Yes    |
| allowed_methods |  Array  | An HTTP method that you want to allow the origin to execute. A combination of the following values can be specified: "GET", "PUT", "POST", "DELETE", "HEAD", or use '*' to set up. |   Yes    |
| allowed_headers |  Array  | An HTTP header that you want to allow the origin to execute. This can contain at most one * wild character.                                                                        |    No    |
| expose_headers  |  Array  | One or more headers in the response that you want customers to be able to access from their applications (for example, from a JavaScript XMLHttpRequest object).                   |    No    |
| max_age_seconds | Integer | The time in seconds that your browser is to cache the preflight response for the specified resource.(seconds)                                                                      |    No    |

See [API Docs](https://docs.qingcloud.com/qingstor/api/bucket/cors/put_cors.html) for more information about request elements.

## Code Snippet

Initialize the Qingstor object with your AccessKeyID and SecretAccessKey.

```python
from qingstor.sdk.service.qingstor import QingStor
from qingstor.sdk.config import Config

config = Config('ACCESS_KEY_ID_EXAMPLE', 'SECRET_ACCESS_KEY_EXAMPLE')
qingstor = QingStor(config)
```

Initialize a Bucket object according to the bucket name you set for subsequent creation:

```python
bucket_name = "your-bucket-name"
zone_name = "pek3b"
bucket_srv = qingstor.Bucket(bucket_name, zone_name)
```

then you can PUT Bucket CORS

```python
cors_rules = [
    {
        "allowed_origin": "http://*.qingcloud.com",
        "allowed_methods": [
            "PUT", "GET", "POST", "DELETE"
        ],
        "allowed_headers": [
            "x-qs-date", "Content-Type", "Content-MD5", "Authorization"
        ],
        "max_age_seconds": 200,
        "expose_headers": [
            "x-qs-date"
        ]
    }
]
resp = bucket_srv.put_cors(cors_rules=cors_rules)
if resp.status_code != 200:
    print("Set CORS of bucket(name: %s) failed with given message: %s\n" % (
        bucket_name, str(resp.content, "utf-8")))
else:
    print("Put bucket CORS successfully.")
```


text:
/* @flow */
import React, { PureComponent } from 'react';
import { View, StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import type { Actions, Auth } from '../types';
import boundActions from '../boundActions';
import { fetchApiKey } from '../api';
import { ErrorMsg, ZulipButton, Input, WebLink } from '../common';
import { getAuth, getOwnEmail } from '../selectors';

type Props = {
  actions: Actions,
  auth: Auth,
  email: string,
};

const componentStyles = StyleSheet.create({
  container: {
    paddingBottom: 10,
  },
  linksTouchable: {
    alignItems: 'flex-end',
  },
});

class PasswordAuthView extends PureComponent {
  static contextTypes = {
    styles: () => null,
  };

  props: Props;

  state: {
    email: string,
    password: string,
    error: string,
    progress: boolean,
  };

  constructor(props: Props) {
    super(props);
    this.state = {
      progress: false,
      email: props.email,
      password: '',
      error: '',
    };
  }

  tryPasswordLogin = async () => {
    const { auth, actions } = this.props;
    const { email, password } = this.state;

    this.setState({ progress: true, error: undefined });

    try {
      const apiKey = await fetchApiKey(auth, email, password);
      this.setState({ progress: false });
      actions.loginSuccess(auth.realm, email, apiKey);
    } catch (err) {
      this.setState({
        progress: false,
        error: 'Wrong email or password. Try again.',
      });
    }
  };

  validateForm = () => {
    const { email, password } = this.state;

    if (!email || !/\S+@\S+\.\S+/.test(email)) {
      this.setState({ error: 'Enter a valid email address' });
    } else if (!password) {
      this.setState({ error: 'Enter a password' });
    } else {
      this.tryPasswordLogin();
    }
  };

  render() {
    const { styles } = this.context;
    const { email, password, progress, error } = this.state;

    return (
      <View style={componentStyles.container}>
        <Input
          style={styles.field}
          autoFocus
          autoCapitalize="none"
          autoCorrect={false}
          blurOnSubmit={false}
          keyboardType="email-address"
          placeholder="Email"
          defaultValue={email}
          onChangeText={newEmail => this.setState({ email: newEmail })}
        />
        <Input
          style={styles.field}
          placeholder="Password"
          secureTextEntry
          value={password}
          onChangeText={newPassword => this.setState({ password: newPassword })}
          blurOnSubmit={false}
          onSubmitEditing={this.validateForm}
        />
        <ZulipButton text="Sign in with password" progress={progress} onPress={this.validateForm} />
        <ErrorMsg error={error} />
        <View style={componentStyles.linksTouchable}>
          <WebLink label="Forgot password?" href="/accounts/password/reset/" />
        </View>
      </View>
    );
  }
}

export default connect(
  state => ({
    auth: getAuth(state),
    email: getOwnEmail(state),
  }),
  boundActions,
)(PasswordAuthView);


text:
"""
	将转发器每天的接口访问量入库
"""
import requests
import re,time
import os,sys
import MySQLdb as mdb

reload(sys)
sys.setdefaultencoding('utf-8')
db_conn = mdb.connect('localhost','root','abcxxx123','yjy_kouqiangzyys',unix_socket='/tmp/mysql.sock')
cursor = db_conn.cursor()

def main():
	# 插入sql值
	try:
			sql = "show tables;"
			#print sql
			cursor.execute(sql)
			data = cursor.fetchall()
			for d in data:
				sql1 = "truncate table %s;"%(d)
				print sql1
				cursor.execute(sql1)
				db_conn.commit()
				#sys.exit(1)
	except mdb.Error, e:
		print e

if __name__ == '__main__':
	main()


text:
/* global test, describe, expect, jest */

export default (unregister) => {
  describe('unregister - Wrong use cases\n  Unregister:', () => {
    describe('Logs a warn message when called', () => {
      const warn = message => `WARN! Impossible to unregister action with message "${message}".\nIt is not a registered action for this worker.`

      test('with more than one action, being only one registered', () => {
        const spy = console.warn = jest.fn()
        const unregisterMock = unregister([
          { message: 'a', func: () => 'a' },
          { message: 'b', func: () => 'a' }
        ])
        unregisterMock(['a', 'c'])
        expect(spy).toHaveBeenCalledWith(warn('c'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('with one action message that is not registered', () => {
        const spy = console.warn = jest.fn()
        const unregisterMock = unregister([{ message: 'a', func: () => 'a' }])
        unregisterMock('b')
        expect(spy).toHaveBeenCalledWith(warn('b'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('with more than one action, being none registered', () => {
        const spy = console.warn = jest.fn()
        const unregisterMock = unregister([
          { message: 'a', func: () => 'a' },
          { message: 'b', func: () => 'a' }
        ])
        unregisterMock(['d', 'c'])
        expect(spy).toHaveBeenCalledWith(warn('d'))
        expect(spy).toHaveBeenCalledWith(warn('c'))
        expect(spy).toHaveBeenCalledTimes(2)
        return spy.mockRestore()
      })
    })

    describe('Returns the length of [actions] when called', () => {
      test('with more than one action, being only one registered', () => {
        const actions = [
          { message: 'a', func: () => 'a' },
          { message: 'b', func: () => 'a' }
        ]
        const unregisterMock = unregister(actions)
        const expected = 1
        const actual = unregisterMock(['a', 'c'])
        expect(actions.length).toBe(expected)
        expect(actual).toBe(expected)
      })

      test('with one action message that is not registered', () => {
        const actions = [{ message: 'a', func: () => 'a' }]
        const unregisterMock = unregister(actions)
        const expected = 1
        const actual = unregisterMock('b')
        expect(actions.length).toBe(expected)
        expect(actual).toBe(expected)
      })

      test('with more than one action, being none registered', () => {
        const actions = [
          { message: 'a', func: () => 'a' },
          { message: 'b', func: () => 'a' }
        ]
        const unregisterMock = unregister(actions)
        const expected = 2
        const actual = unregisterMock(['d', 'c'])
        expect(actions.length).toBe(expected)
        expect(actual).toBe(expected)
      })
    })

    describe('Logs an error when message is', () => {
      const error = received => new TypeError(`You should provide an array of strings or a string\n\nReceived: ${received}`)

      test('an object', () => {
        const spy = console.error = jest.fn()
        unregister([{ message: 'a', func: () => 'a' }])({an: 'object'})
        expect(spy).toHaveBeenCalledWith(error('{"an":"object"}'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('a number', () => {
        const spy = console.error = jest.fn()
        unregister([{ message: 'a', func: () => 'a' }])(1)
        expect(spy).toHaveBeenCalledWith(error('1'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('undefined', () => {
        const spy = console.error = jest.fn()
        unregister([{ message: 'a', func: () => 'a' }])()
        expect(spy).toHaveBeenCalledWith(error('null'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('null', () => {
        const spy = console.error = jest.fn()
        unregister([{ message: 'a', func: () => 'a' }])(null)
        expect(spy).toHaveBeenCalledWith(error('null'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

      test('an array with something beside strings', () => {
        const spy = console.error = jest.fn()
        unregister([{ message: 'a', func: () => 'a' }])(['an', 'array', {with: 'object'}])
        expect(spy).toHaveBeenCalledWith(error('["an","array",{"with":"object"}]'))
        expect(spy).toHaveBeenCalledTimes(1)
        return spy.mockRestore()
      })

    })

    describe('Returns null when message is', () => {
      test('an object', () => expect(unregister([])({an: 'object'})).toBeNull())

      test('a number', () => expect(unregister([])(1)).toBeNull())

      test('undefined', () => expect(unregister([])()).toBeNull())

      test('null', () => expect(unregister([])(null)).toBeNull())

      test('an array with something beside strings', () => expect(unregister([])(['an', 'array', {with: 'object'}])).toBeNull())
    })
  })
}


text:
namespace chromeos {

namespace secure_channel {

// Advertises to the device with the given ID. Due to issues in the Bluetooth
// stack, it is possible that registering or unregistering an advertisement can
// fail. If this class encounters an error, it retries until it succeeds. Once
// Stop() is called, the advertisement should not be considered unregistered
// until the stop callback is invoked.
class ErrorTolerantBleAdvertisement {
 public:
  virtual ~ErrorTolerantBleAdvertisement();

  // Stops advertising. Because BLE advertisements start and stop
  // asynchronously, clients must use this function to stop advertising instead
  // of simply deleting an ErrorTolerantBleAdvertisement object. Clients should
  // not assume that advertising has actually stopped until |callback| has been
  // invoked.
  virtual void Stop(const base::Closure& callback) = 0;

  // Returns whether Stop() has been called.
  virtual bool HasBeenStopped() = 0;

  const DeviceIdPair& device_id_pair() const { return device_id_pair_; }

 protected:
  ErrorTolerantBleAdvertisement(const DeviceIdPair& device_id_pair);

 private:
  const DeviceIdPair device_id_pair_;

  DISALLOW_COPY_AND_ASSIGN(ErrorTolerantBleAdvertisement);
};

}  // namespace secure_channel

}  // namespace chromeos

#endif  // CHROMEOS_SERVICES_SECURE_CHANNEL_ERROR_TOLERANT_BLE_ADVERTISEMENT_H_


text:
#!/usr/bin/env node

// Licensed under the Apache License. See footer for details.

require("../lib/node/cli").run()


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.4"/>
<title>tbb::queuing_mutex::scoped_lock Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Class List

Class Hierarchy

Class Members

tbb

queuing_mutex

scoped_lock

Public Member Functions |
List of all members

tbb::queuing_mutex::scoped_lock Class Reference

The scoped locking pattern.
 More...

#include <queuing_mutex.h>

Inheritance diagram for tbb::queuing_mutex::scoped_lock:

  <map id="tbb::queuing_mutex::scoped_lock_map" name="tbb::queuing_mutex::scoped_lock_map">
</map>

Public Member Functions

 	scoped_lock ()

 	Construct lock that has not acquired a mutex.  More...

 	scoped_lock (queuing_mutex &m)

 	Acquire lock on given mutex.

 	~scoped_lock ()

 	Release lock (if lock is held).

void __TBB_EXPORTED_METHOD 	acquire (queuing_mutex &m)

 	Acquire lock on given mutex.

bool __TBB_EXPORTED_METHOD 	try_acquire (queuing_mutex &m)

 	Acquire lock on given mutex if free (i.e. non-blocking)

void __TBB_EXPORTED_METHOD 	release ()

 	Release lock.

Detailed Description

The scoped locking pattern.

It helps to avoid the common problem of forgetting to release lock. It also nicely provides the "node" for queuing locks.

Constructor & Destructor Documentation

          tbb::queuing_mutex::scoped_lock::scoped_lock
          (
          )

inline

Construct lock that has not acquired a mutex.

Equivalent to zero-initialization of *this.

The documentation for this class was generated from the following file:

queuing_mutex.h

Copyright © 2005-2017 Intel Corporation.  All Rights Reserved.

Intel, Pentium, Intel Xeon, Itanium, Intel XScale and VTune are
registered trademarks or trademarks of Intel Corporation or its
subsidiaries in the United States and other countries.

* Other names and brands may be claimed as the property of others.


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.example" version="1.0.0" versionCode="10" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>PhoneGap Example</name>
    <description>
        An example for phonegap build docs.
    </description>
    <author email="support@phonegap.com" href="https://build.phonegap.com">
        Hardeep Shoker
    </author>
    <engine name="android" spec="~4.1.1" />
</widget>


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.elkoserver.objdb.store.QueryDesc (neohabitat 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-01-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.elkoserver.objdb.store.QueryDesc

Packages that use QueryDesc

Package
Description

org.elkoserver.objdb.store

Classes for implementing various Elko object store types.

org.elkoserver.objdb.store.filestore

A simple ObjectStore implementation based on
a directory full of small text files.

org.elkoserver.objdb.store.mongostore

An ObjectStore implementation based on the
MongoDB NoSQL object database.

Uses of QueryDesc in org.elkoserver.objdb.store

Methods in org.elkoserver.objdb.store with parameters of type QueryDesc

Modifier and Type
Method and Description

void
ObjectStore.queryObjects(QueryDesc[] what,
            GetResultHandler handler)

Service a 'query' request.

Uses of QueryDesc in org.elkoserver.objdb.store.filestore

Methods in org.elkoserver.objdb.store.filestore with parameters of type QueryDesc

Modifier and Type
Method and Description

void
FileObjectStore.queryObjects(QueryDesc[] what,
            GetResultHandler handler)

Service a 'query' request.

Uses of QueryDesc in org.elkoserver.objdb.store.mongostore

Methods in org.elkoserver.objdb.store.mongostore with parameters of type QueryDesc

Modifier and Type
Method and Description

void
MongoObjectStore.queryObjects(QueryDesc[] what,
            GetResultHandler handler)

Service a 'query' request.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2017. All rights reserved.


text:
import Joi from "@hapi/joi";
import { format, parseISO } from "date-fns";
import { logger } from "../logs/log";

import { User } from "../models/User";
import { Note } from "../models/Note";

const noteSchema = Joi.object({
  id: Joi.number().integer(),
  userId: Joi.number().integer().required(),
  title: Joi.string().required(),
  content: Joi.string().required(),
  ipAddress: Joi.string(),
  updatedAt: Joi.date().optional(),
  createdAt: Joi.date().optional()
});

export const index = async (ctx) => {
  const { query } = ctx;

  // Attach logged in user
  const user = new User(ctx.state.user);
  query.userId = user.id;

  // Init a new note object
  const note = new Note();

  // Let's check that the sort options were set. Sort can be empty
  if (!query.order || !query.page || !query.limit) {
    ctx.throw(400, "INVALID_ROUTE_OPTIONS");
  }

  // Get paginated list of notes
  try {
    const result = await note.all(query);
    ctx.body = { data: { notes: result } };
  } catch (error) {
    logger.error(error);
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });
  }
};

export const show = async (ctx) => {
  const { params } = ctx;
  if (!params.id)
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Initialize note
  const note = new Note();

  try {
    // Find and show note
    await note.find(params.id);
    ctx.body = { data: { note } };
  } catch (error) {
    logger.error(error);
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });
  }
};

export const create = async (ctx) => {
  const request = ctx.request.body;

  // Attach logged in user
  const user = new User(ctx.state.user);
  request.userId = user.id;

  // Add ip
  request.ipAddress = ctx.ip;

  // Create a new note object using the request params
  const note = new Note(request);

  // Validate the newly created note
  const validator = noteSchema.validate(note);
  if (validator.error) ctx.throw(400, validator.error.details[0].message);

  try {
    const [resultId] = await note.store();
    note.id = resultId;
    ctx.body = { data: { note } };
  } catch (error) {
    logger.error(error);
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });
  }
};

export const update = async (ctx) => {
  const { params } = ctx;
  const request = ctx.request.body;

  // Make sure they've specified a note
  if (!params.id)
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Find and set that note
  const note = new Note();
  await note.find(params.id);
  if (!note) ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Grab the user, if it's not their note - error out
  const user = new User(ctx.state.user);
  if (note.userId !== user.id)
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Add the updated date value
  request.updatedAt = parseISO(format(new Date(), "yyyy-MM-dd HH:mm:ss"));

  // Add the ip
  request.ipAddress = ctx.ip;

  // Replace the note data with the new updated note data
  Object.keys(ctx.request.body).forEach((parameter) => {
    note[parameter] = request[parameter];
  });

  try {
    await note.save();
    ctx.body = { data: { note } };
  } catch (error) {
    logger.error(error);
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });
  }
};

export const del = async (ctx) => {
  const { params } = ctx;
  if (!params.id)
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Find that note
  const note = new Note();
  await note.find(params.id);
  if (!note) ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  // Grab the user //If it's not their note - error out
  const user = new User(ctx.state.user);
  if (note.userId !== user.id)
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });

  try {
    await note.destroy();
    ctx.body = { data: {} };
  } catch (error) {
    logger.error(error);
    ctx.throw(400, { error: { code: 400, message: "INVALID_DATA" } });
  }
};


text:
namespace v8 {
namespace internal {

template <typename T>
class Handle;

template <typename T>
class MaybeHandle;

namespace wasm {
namespace testing {

// Returns a MaybeHandle to the JsToWasm wrapper of the wasm function exported
// with the given name by the provided instance.
MaybeHandle<WasmExportedFunction> GetExportedFunction(
    Isolate* isolate, Handle<WasmInstanceObject> instance, const char* name);

// Call an exported wasm function by name. Returns -1 if the export does not
// exist or throws an error. Errors are cleared from the isolate before
// returning. {exception} is set to to true if an exception happened during
// execution of the wasm function.
int32_t CallWasmFunctionForTesting(Isolate* isolate,
                                   Handle<WasmInstanceObject> instance,
                                   const char* name, int argc,
                                   Handle<Object> argv[],
                                   bool* exception = nullptr);

// Decode, verify, and run the function labeled "main" in the
// given encoded module. The module should have no imports.
int32_t CompileAndRunWasmModule(Isolate* isolate, const byte* module_start,
                                const byte* module_end);

// Decode and compile the given module with no imports.
MaybeHandle<WasmModuleObject> CompileForTesting(Isolate* isolate,
                                                ErrorThrower* thrower,
                                                const ModuleWireBytes& bytes);

// Decode, compile, and instantiate the given module with no imports.
MaybeHandle<WasmInstanceObject> CompileAndInstantiateForTesting(
    Isolate* isolate, ErrorThrower* thrower, const ModuleWireBytes& bytes);

class WasmInterpretationResult {
 public:
  static WasmInterpretationResult Failed() { return {kFailed, 0, false}; }
  static WasmInterpretationResult Trapped(bool possible_nondeterminism) {
    return {kTrapped, 0, possible_nondeterminism};
  }
  static WasmInterpretationResult Finished(int32_t result,
                                           bool possible_nondeterminism) {
    return {kFinished, result, possible_nondeterminism};
  }

  // {failed()} captures different reasons: The module was invalid, no function
  // to call was found in the module, the function did not termine within a
  // limited number of steps, or a stack overflow happened.
  bool failed() const { return status_ == kFailed; }
  bool trapped() const { return status_ == kTrapped; }
  bool finished() const { return status_ == kFinished; }

  int32_t result() const {
    DCHECK_EQ(status_, kFinished);
    return result_;
  }

  bool possible_nondeterminism() const { return possible_nondeterminism_; }

 private:
  enum Status { kFinished, kTrapped, kFailed };

  const Status status_;
  const int32_t result_;
  const bool possible_nondeterminism_;

  WasmInterpretationResult(Status status, int32_t result,
                           bool possible_nondeterminism)
      : status_(status),
        result_(result),
        possible_nondeterminism_(possible_nondeterminism) {}
};

// Interprets the given module, starting at the function specified by
// {function_index}. The return type of the function has to be int32. The module
// should not have any imports or exports
WasmInterpretationResult InterpretWasmModule(
    Isolate* isolate, Handle<WasmInstanceObject> instance,
    int32_t function_index, WasmValue* args);

// Generate an array of default arguments for the given signature, to be used in
// the interpreter.
OwnedVector<WasmValue> MakeDefaultInterpreterArguments(Isolate* isolate,
                                                       const FunctionSig* sig);

// Generate an array of default arguments for the given signature, to be used
// when calling compiled code. Make sure that the arguments match the ones
// returned by {MakeDefaultInterpreterArguments}, otherwise fuzzers will report
// differences between interpreter and compiled code.
OwnedVector<Handle<Object>> MakeDefaultArguments(Isolate* isolate,
                                                 const FunctionSig* sig);

// Install function map, module symbol for testing
void SetupIsolateForWasmModule(Isolate* isolate);

}  // namespace testing
}  // namespace wasm
}  // namespace internal
}  // namespace v8

#endif  // V8_WASM_MODULE_RUNNER_H_


text:
package net.minecraft.crash;

import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Callable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.BlockPos;

public class CrashReportCategory
{
    private final CrashReport crashReport;
    private final String name;
    private final List<Entry> children = Lists.<Entry>newArrayList();
    private StackTraceElement[] stackTrace = new StackTraceElement[0];

    public CrashReportCategory(CrashReport report, String name)
    {
        this.crashReport = report;
        this.name = name;
    }

    public static String getCoordinateInfo(double x, double y, double z)
    {
        return String.format("%.2f,%.2f,%.2f - %s", new Object[] {Double.valueOf(x), Double.valueOf(y), Double.valueOf(z), getCoordinateInfo(new BlockPos(x, y, z))});
    }

    public static String getCoordinateInfo(BlockPos pos)
    {
        int i = pos.getX();
        int j = pos.getY();
        int k = pos.getZ();
        StringBuilder stringbuilder = new StringBuilder();

        try
        {
            stringbuilder.append(String.format("World: (%d,%d,%d)", new Object[] {Integer.valueOf(i), Integer.valueOf(j), Integer.valueOf(k)}));
        }
        catch (Throwable var17)
        {
            stringbuilder.append("(Error finding world loc)");
        }

        stringbuilder.append(", ");

        try
        {
            int l = i >> 4;
            int i1 = k >> 4;
            int j1 = i & 15;
            int k1 = j >> 4;
            int l1 = k & 15;
            int i2 = l << 4;
            int j2 = i1 << 4;
            int k2 = (l + 1 << 4) - 1;
            int l2 = (i1 + 1 << 4) - 1;
            stringbuilder.append(String.format("Chunk: (at %d,%d,%d in %d,%d; contains blocks %d,0,%d to %d,255,%d)", new Object[] {Integer.valueOf(j1), Integer.valueOf(k1), Integer.valueOf(l1), Integer.valueOf(l), Integer.valueOf(i1), Integer.valueOf(i2), Integer.valueOf(j2), Integer.valueOf(k2), Integer.valueOf(l2)}));
        }
        catch (Throwable var16)
        {
            stringbuilder.append("(Error finding chunk loc)");
        }

        stringbuilder.append(", ");

        try
        {
            int j3 = i >> 9;
            int k3 = k >> 9;
            int l3 = j3 << 5;
            int i4 = k3 << 5;
            int j4 = (j3 + 1 << 5) - 1;
            int k4 = (k3 + 1 << 5) - 1;
            int l4 = j3 << 9;
            int i5 = k3 << 9;
            int j5 = (j3 + 1 << 9) - 1;
            int i3 = (k3 + 1 << 9) - 1;
            stringbuilder.append(String.format("Region: (%d,%d; contains chunks %d,%d to %d,%d, blocks %d,0,%d to %d,255,%d)", new Object[] {Integer.valueOf(j3), Integer.valueOf(k3), Integer.valueOf(l3), Integer.valueOf(i4), Integer.valueOf(j4), Integer.valueOf(k4), Integer.valueOf(l4), Integer.valueOf(i5), Integer.valueOf(j5), Integer.valueOf(i3)}));
        }
        catch (Throwable var15)
        {
            stringbuilder.append("(Error finding world loc)");
        }

        return stringbuilder.toString();
    }

    /**
     * Adds a Crashreport section with the given name with the value set to the result of the given Callable;
     */
    public void addCrashSectionCallable(String sectionName, Callable<String> callable)
    {
        try
        {
            this.addCrashSection(sectionName, callable.call());
        }
        catch (Throwable throwable)
        {
            this.addCrashSectionThrowable(sectionName, throwable);
        }
    }

    /**
     * Adds a Crashreport section with the given name with the given value (convered .toString())
     */
    public void addCrashSection(String sectionName, Object value)
    {
        this.children.add(new Entry(sectionName, value));
    }

    /**
     * Adds a Crashreport section with the given name with the given Throwable
     */
    public void addCrashSectionThrowable(String sectionName, Throwable throwable)
    {
        this.addCrashSection(sectionName, throwable);
    }

    /**
     * Resets our stack trace according to the current trace, pruning the deepest 3 entries.  The parameter indicates
     * how many additional deepest entries to prune.  Returns the number of entries in the resulting pruned stack trace.
     */
    public int getPrunedStackTrace(int size)
    {
        StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace();

        if (astacktraceelement.length <= 0)
        {
            return 0;
        }
        else
        {
            this.stackTrace = new StackTraceElement[astacktraceelement.length - 3 - size];
            System.arraycopy(astacktraceelement, 3 + size, this.stackTrace, 0, this.stackTrace.length);
            return this.stackTrace.length;
        }
    }

    /**
     * Do the deepest two elements of our saved stack trace match the given elements, in order from the deepest?
     */
    public boolean firstTwoElementsOfStackTraceMatch(StackTraceElement s1, StackTraceElement s2)
    {
        if (this.stackTrace.length != 0 && s1 != null)
        {
            StackTraceElement stacktraceelement = this.stackTrace[0];

            if (stacktraceelement.isNativeMethod() == s1.isNativeMethod() && stacktraceelement.getClassName().equals(s1.getClassName()) && stacktraceelement.getFileName().equals(s1.getFileName()) && stacktraceelement.getMethodName().equals(s1.getMethodName()))
            {
                if (s2 != null != this.stackTrace.length > 1)
                {
                    return false;
                }
                else if (s2 != null && !this.stackTrace[1].equals(s2))
                {
                    return false;
                }
                else
                {
                    this.stackTrace[0] = s1;
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    /**
     * Removes the given number entries from the bottom of the stack trace.
     */
    public void trimStackTraceEntriesFromBottom(int amount)
    {
        StackTraceElement[] astacktraceelement = new StackTraceElement[this.stackTrace.length - amount];
        System.arraycopy(this.stackTrace, 0, astacktraceelement, 0, astacktraceelement.length);
        this.stackTrace = astacktraceelement;
    }

    public void appendToStringBuilder(StringBuilder builder)
    {
        builder.append("-- ").append(this.name).append(" --\n");
        builder.append("Details:");

        for (Entry crashreportcategory$entry : this.children)
        {
            builder.append("\n\t");
            builder.append(crashreportcategory$entry.getKey());
            builder.append(": ");
            builder.append(crashreportcategory$entry.getValue());
        }

        if (this.stackTrace != null && this.stackTrace.length > 0)
        {
            builder.append("\nStacktrace:");

            for (StackTraceElement stacktraceelement : this.stackTrace)
            {
                builder.append("\n\tat ");
                builder.append(stacktraceelement.toString());
            }
        }
    }

    public StackTraceElement[] getStackTrace()
    {
        return this.stackTrace;
    }

    public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final Block blockIn, final int blockData)
    {
        final int i = Block.getIdFromBlock(blockIn);
        category.addCrashSectionCallable("Block type", new Callable<String>()
        {
            public String call() throws Exception
            {
                try
                {
                    return String.format("ID #%d (%s // %s)", new Object[] {Integer.valueOf(i), blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName()});
                }
                catch (Throwable var2)
                {
                    return "ID #" + i;
                }
            }
        });
        category.addCrashSectionCallable("Block data value", new Callable<String>()
        {
            public String call() throws Exception
            {
                if (blockData < 0)
                {
                    return "Unknown? (Got " + blockData + ")";
                }
                else
                {
                    String s = String.format("%4s", new Object[] {Integer.toBinaryString(blockData)}).replace(" ", "0");
                    return String.format("%1$d / 0x%1$X / 0b%2$s", new Object[] {Integer.valueOf(blockData), s});
                }
            }
        });
        category.addCrashSectionCallable("Block location", new Callable<String>()
        {
            public String call() throws Exception
            {
                return CrashReportCategory.getCoordinateInfo(pos);
            }
        });
    }

    public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final IBlockState state)
    {
        category.addCrashSectionCallable("Block", new Callable<String>()
        {
            public String call() throws Exception
            {
                return state.toString();
            }
        });
        category.addCrashSectionCallable("Block location", new Callable<String>()
        {
            public String call() throws Exception
            {
                return CrashReportCategory.getCoordinateInfo(pos);
            }
        });
    }

    static class Entry
    {
        private final String key;
        private final String value;

        public Entry(String key, Object value)
        {
            this.key = key;

            if (value == null)
            {
                this.value = "~~NULL~~";
            }
            else if (value instanceof Throwable)
            {
                Throwable throwable = (Throwable)value;
                this.value = "~~ERROR~~ " + throwable.getClass().getSimpleName() + ": " + throwable.getMessage();
            }
            else
            {
                this.value = value.toString();
            }
        }

        public String getKey()
        {
            return this.key;
        }

        public String getValue()
        {
            return this.value;
        }
    }
}


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

package org.apache.hadoop.hbase.coprocessor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableSet;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.client.Append;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Increment;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.ByteArrayComparable;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
import org.apache.hadoop.hbase.regionserver.KeyValueScanner;
import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
import org.apache.hadoop.hbase.regionserver.RegionScanner;
import org.apache.hadoop.hbase.regionserver.ScanType;
import org.apache.hadoop.hbase.regionserver.Store;
import org.apache.hadoop.hbase.regionserver.StoreFile;
import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Pair;
import org.mortbay.log.Log;

import com.google.common.collect.ImmutableList;

/**
 * An abstract class that implements RegionObserver.
 * By extending it, you can create your own region observer without
 * overriding all abstract methods of RegionObserver.
 */
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
@InterfaceStability.Evolving
public abstract class BaseRegionObserver implements RegionObserver {
  @Override
  public void start(CoprocessorEnvironment e) throws IOException { }

  @Override
  public void stop(CoprocessorEnvironment e) throws IOException { }

  @Override
  public void preOpen(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException { }

  @Override
  public void postOpen(ObserverContext<RegionCoprocessorEnvironment> e) { }

  @Override
  public void preClose(ObserverContext<RegionCoprocessorEnvironment> c, boolean abortRequested)
      throws IOException { }

  @Override
  public void postClose(ObserverContext<RegionCoprocessorEnvironment> e,
      boolean abortRequested) { }

  @Override
  public InternalScanner preFlushScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final KeyValueScanner memstoreScanner, final InternalScanner s)
      throws IOException {
    return s;
  }

  @Override
  public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
  }

  @Override
  public void postFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
  }

  @Override
  public InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> e, Store store,
      InternalScanner scanner) throws IOException {
    return scanner;
  }

  @Override
  public void postFlush(ObserverContext<RegionCoprocessorEnvironment> e, Store store,
      StoreFile resultFile) throws IOException {
  }

  @Override
  public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
  }

  @Override
  public void preSplit(ObserverContext<RegionCoprocessorEnvironment> c,
      byte[] splitRow) throws IOException {
  }

  @Override
  public void preRollBackSplit(ObserverContext<RegionCoprocessorEnvironment> ctx)
      throws IOException {
  }

  @Override
  public void postRollBackSplit(
      ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException {
  }

  @Override
  public void postCompleteSplit(
      ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException {
  }

  @Override
  public void postSplit(ObserverContext<RegionCoprocessorEnvironment> e, HRegion l, HRegion r)
      throws IOException {
  }

  @Override
  public void preCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final List<StoreFile> candidates) throws IOException { }

  @Override
  public void preCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final List<StoreFile> candidates, final CompactionRequest request)
      throws IOException {
    preCompactSelection(c, store, candidates);
  }

  @Override
  public void postCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final ImmutableList<StoreFile> selected) { }

  @Override
  public void postCompactSelection(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final ImmutableList<StoreFile> selected, CompactionRequest request) {
    postCompactSelection(c, store, selected);
  }

  @Override
  public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e,
      final Store store, final InternalScanner scanner, final ScanType scanType)
      throws IOException {
    return scanner;
  }

  @Override
  public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e,
      final Store store, final InternalScanner scanner, final ScanType scanType,
      CompactionRequest request) throws IOException {
    return preCompact(e, store, scanner, scanType);
  }

  @Override
  public InternalScanner preCompactScannerOpen(
      final ObserverContext<RegionCoprocessorEnvironment> c, final Store store,
      List<? extends KeyValueScanner> scanners, final ScanType scanType, final long earliestPutTs,
      final InternalScanner s) throws IOException {
    return s;
  }

  @Override
  public InternalScanner preCompactScannerOpen(
      final ObserverContext<RegionCoprocessorEnvironment> c, final Store store,
      List<? extends KeyValueScanner> scanners, final ScanType scanType, final long earliestPutTs,
      final InternalScanner s, CompactionRequest request) throws IOException {
    return preCompactScannerOpen(c, store, scanners, scanType, earliestPutTs, s);
  }

  @Override
  public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, final Store store,
      final StoreFile resultFile) throws IOException {
  }

@Override
  public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, final Store store,
      final StoreFile resultFile, CompactionRequest request) throws IOException {
    postCompact(e, store, resultFile);
  }

  @Override
  public void preGetClosestRowBefore(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final Result result)
    throws IOException {
  }

  @Override
  public void postGetClosestRowBefore(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final Result result)
      throws IOException {
  }

  @Override
  public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Get get, final List<Cell> results) throws IOException {
    // By default we are executing the deprecated preGet to support legacy RegionObservers
    // We may use the results coming in and we may return the results going out.
    List<KeyValue> kvs = new ArrayList<KeyValue>(results.size());
    for (Cell c : results) {
      kvs.add(KeyValueUtil.ensureKeyValue(c));
    }
    preGet(e, get, kvs);
    results.clear();
    results.addAll(kvs);
  }

  /**
   * WARNING: please override preGetOp instead of this method.  This is to maintain some
   * compatibility and to ease the transition from 0.94 -> 0.96.  It is super inefficient!
   */
  @Deprecated
  @Override
  public void preGet(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get,
      final List<KeyValue> result)
    throws IOException {
  }

  @Override
  public void postGetOp(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Get get, final List<Cell> results) throws IOException {
    // By default we are executing the deprecated preGet to support legacy RegionObservers
    // We may use the results coming in and we may return the results going out.
    List<KeyValue> kvs = new ArrayList<KeyValue>(results.size());
    for (Cell c : results) {
      kvs.add(KeyValueUtil.ensureKeyValue(c));
    }
    postGet(e, get, kvs);
    results.clear();
    results.addAll(kvs);
  }

  /**
   * WARNING: please override postGetOp instead of this method.  This is to maintain some
   * compatibility and to ease the transition from 0.94 -> 0.96.  It is super inefficient!
   */
  @Deprecated
  @Override
  public void postGet(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get,
      final List<KeyValue> result)
    throws IOException {
  }

  @Override
  public boolean preExists(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Get get, final boolean exists) throws IOException {
    return exists;
  }

  @Override
  public boolean postExists(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Get get, boolean exists) throws IOException {
    return exists;
  }

  @Override
  public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Put put, final WALEdit edit, final Durability durability) throws IOException {
  }

  @Override
  public void postPut(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Put put, final WALEdit edit, final Durability durability) throws IOException {
  }

  @Override
  public void preDelete(final ObserverContext<RegionCoprocessorEnvironment> e, final Delete delete,
      final WALEdit edit, final Durability durability) throws IOException {
  }

  @Override
  public void postDelete(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Delete delete, final WALEdit edit, final Durability durability)
      throws IOException {
  }

  @Override
  public void preBatchMutate(final ObserverContext<RegionCoprocessorEnvironment> c,
      final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
  }

  @Override
  public void postBatchMutate(final ObserverContext<RegionCoprocessorEnvironment> c,
      final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
  }

  @Override
  public boolean preCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final CompareOp compareOp, final ByteArrayComparable comparator,
      final Put put, final boolean result) throws IOException {
    return result;
  }

  @Override
  public boolean postCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final CompareOp compareOp, final ByteArrayComparable comparator,
      final Put put, final boolean result) throws IOException {
    return result;
  }

  @Override
  public boolean preCheckAndDelete(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final CompareOp compareOp, final ByteArrayComparable comparator,
      final Delete delete, final boolean result) throws IOException {
    return result;
  }

  @Override
  public boolean postCheckAndDelete(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final CompareOp compareOp, final ByteArrayComparable comparator,
      final Delete delete, final boolean result) throws IOException {
    return result;
  }

  @Override
  public Result preAppend(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Append append) throws IOException {
    return null;
  }

  @Override
  public Result postAppend(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Append append, final Result result) throws IOException {
    return result;
  }

  @Override
  public long preIncrementColumnValue(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final long amount, final boolean writeToWAL) throws IOException {
    return amount;
  }

  @Override
  public long postIncrementColumnValue(final ObserverContext<RegionCoprocessorEnvironment> e,
      final byte [] row, final byte [] family, final byte [] qualifier,
      final long amount, final boolean writeToWAL, long result)
      throws IOException {
    return result;
  }

  @Override
  public Result preIncrement(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Increment increment) throws IOException {
    return null;
  }

  @Override
  public Result postIncrement(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Increment increment, final Result result) throws IOException {
    return result;
  }

  @Override
  public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Scan scan, final RegionScanner s) throws IOException {
    return s;
  }

  @Override
  public KeyValueScanner preStoreScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
      final Store store, final Scan scan, final NavigableSet<byte[]> targetCols,
      final KeyValueScanner s) throws IOException {
    return s;
  }

  @Override
  public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> e,
      final Scan scan, final RegionScanner s) throws IOException {
    return s;
  }

  @Override
  public boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> e,
      final InternalScanner s, final List<Result> results,
      final int limit, final boolean hasMore) throws IOException {
    return hasMore;
  }

  @Override
  public boolean postScannerNext(final ObserverContext<RegionCoprocessorEnvironment> e,
      final InternalScanner s, final List<Result> results, final int limit,
      final boolean hasMore) throws IOException {
    return hasMore;
  }

  @Override
  public boolean postScannerFilterRow(final ObserverContext<RegionCoprocessorEnvironment> e,
      final InternalScanner s, final byte[] currentRow, final boolean hasMore) throws IOException {
    return hasMore;
  }

  @Override
  public void preScannerClose(final ObserverContext<RegionCoprocessorEnvironment> e,
      final InternalScanner s) throws IOException {
  }

  @Override
  public void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> e,
      final InternalScanner s) throws IOException {
  }

  @Override
  public void preWALRestore(ObserverContext<RegionCoprocessorEnvironment> env, HRegionInfo info,
      HLogKey logKey, WALEdit logEdit) throws IOException {
  }

  @Override
  public void postWALRestore(ObserverContext<RegionCoprocessorEnvironment> env,
      HRegionInfo info, HLogKey logKey, WALEdit logEdit) throws IOException {
  }

  @Override
  public void preBulkLoadHFile(final ObserverContext<RegionCoprocessorEnvironment> ctx,
    List<Pair<byte[], String>> familyPaths) throws IOException {
  }

  @Override
  public boolean postBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
    List<Pair<byte[], String>> familyPaths, boolean hasLoaded) throws IOException {
    return hasLoaded;
  }
}


text:
namespace typefu {

  template <bool... Bs>
  using for_ = typename std::enable_if<all<Bs...>::value>::type;

  template <typename... Ts>
  using for_arithmetic =
    typename std::enable_if<is_arithmetic<Ts...>::value>::type;

  template <typename... Ts>
  using for_floating =
    typename std::enable_if<is_floating_point<Ts...>::value>::type;

  template <typename... Ts>
  using for_integral = typename std::enable_if<is_integral<Ts...>::value>::type;

  template <typename... Ts>
  using for_signed = typename std::enable_if<is_signed<Ts...>::value>::type;

  template <typename... Ts>
  using for_signed_integral =
    typename std::enable_if<is_signed_integral<Ts...>::value>::type;

  template <typename... Ts>
  using for_unsigned = typename std::enable_if<is_unsigned<Ts...>::value>::type;

  template <typename... Ts>
  using for_convertible =
    typename std::enable_if<is_convertible<Ts...>::value>::type;
}


text:
import * as React from "react";
import { deleteJob } from "#SRC/js/events/MetronomeClient";
import { Trans, t } from "@lingui/macro";
import { i18n } from "#SRC/js/i18n";
import { DialogModalWithFooter, PrimaryButton } from "@dcos/ui-kit";
import { Link } from "react-router";

type Props = {
  open: boolean;
  jobId: string;
  onSuccess: () => void;
  onClose: () => void;
};
export default function JobDelete({ open, jobId, onSuccess, onClose }: Props) {
  const [state, setState] = React.useState({ errMsg: null, deleting: false });

  const err = state.errMsg || "";
  const isTaskRunning = err.includes("stopCurrentJobRuns=true");
  const deps = err.match(/children=\[(.+)\]/)?.[1]?.split(",");

  const onConfirm = () =>
    deleteJob(jobId, isTaskRunning).subscribe(
      () => {
        setState({ errMsg: null, deleting: false });
        onSuccess();
      },
      (error) => {
        const errMsg =
          error?.response?.message ||
          `Unknown Metronome Error: ${JSON.stringify(error)}`;
        void setState({ deleting: false, errMsg });
      }
    );

  const ctaDisabled = state.deleting || !!deps?.length;
  return (
    <DialogModalWithFooter
      onClose={onClose}
      isOpen={open}
      title={<Trans id="Delete Job" />}
      ctaButton={
        <PrimaryButton onClick={onConfirm} disabled={ctaDisabled}>
          {state.deleting ? (
            <Trans id="Deleting" />
          ) : isTaskRunning ? (
            <Trans id="Stop Current Runs and Delete Job" />
          ) : (
            <Trans id="Delete Job" />
          )}
        </PrimaryButton>
      }
      closeText={i18n._(t`Cancel`)}
    >
      {isTaskRunning ? (
        <Trans render="p">
          Couldn't delete {jobId} as there are currently active job runs. Do you
          want to stop all runs and delete the job?
        </Trans>
      ) : deps ? (

          <Trans render="p">
            Could not delete {jobId} because the following Jobs depend on it:
          </Trans>

            {deps.map((id) => (

                <Link to={`/jobs/detail/${id}`} onClick={onClose}>
                  {id}
                </Link>

            ))}

      ) : state.errMsg ? (
        state.errMsg
      ) : (
        <Trans render="p">
          Are you sure you want to delete {jobId}? This action is irreversible.
        </Trans>
      )}
    </DialogModalWithFooter>
  );
}


text:
Namespace zxweb.xtag

'*******************************************************************************
'	Process multiple tags all at once.
'
'!!	Don't use Converter as the name, since collides with System.Converter.
'
'	Todos:
'		- extract tag class.
'		2011.11.21 - optimize passon()
'
'	History:
'		2011-11-20 changed defaulthost
'

Public Class XTagConverter
	Inherits ConverterBase

Private _isNewWay As Boolean = False
Protected Function isNewWay() As Boolean
	Return _isNewWay
End Function
Protected Sub setNewWay(Optional bv As Boolean = True)
	_isNewWay = bv
End Sub

'*****************
'	Life cycle
'
'*****************

'XX
Public Sub New()
End Sub

Public Sub New( _
	tkey As String, _
	Optional hasValues As Boolean = False _
)
	newHelper(tkey, hasValues)
End Sub

Public Sub New( _
	tkey As String, _
	argType As EnumArgType _
)
	newHelper(tkey, argType)

	'setNewWay()
End Sub

'*************
'	Events
'
'*************

'!! The 'middle' should not be modified.
'XX merge
'!! obsolete
Protected Overridable Function transform( _
	ByRef body As String _
) As String
	XTrace.showRun("XTagConverter.transform")

	If _isNewWay Then
		Return ""
	End If

	Dim akey As String = getKey()

	If body = "" Then
		body = getParam() 'XX last
	End If

	If body = "" Or akey = "" Then
		XTrace.warn("XTagConverter.transform", "body or key empty, return")
		XTrace.show("XTagConverter.transform", "key", akey, _
			"body", body)
		Return "" ' no change
	End If

	Dim rslt As String = "<" & akey & ">" & body & "</" & akey & ">"

	XTrace.showEnd("XTagConverter.transform")
	Return rslt
End Function

Protected Overrides Function transform2( _
	ByRef ioFullText As String _
) As Integer
	Dim rslt As Integer

	If String.IsNullOrEmpty(ioFullText) Then
		Return 0 '?? ex
	End If

	XTrace.show("XTagConverter.transform2", _
		"CurrentTag.getWhole()", CurrentTag.getWhole())

	If Not isNewWay() Then
		Dim news As String = transform(CurrentTag.Body)
		XTrace.show("ConverterBase.transform", "Transformed")

		'XX allow "" replacement
		If news <> "" Then
			'!! don't replace with ""
			ioFullText = ioFullText.Replace(CurrentTag.getWhole(), news)
		End If
	Else
		Dim isok As Boolean = True '!! default
		Dim news2 As String = transformTag(isok)

		If isok Then
			ioFullText = ioFullText.Replace(CurrentTag.getWhole(), news2)
		End If
	End If

	rslt = ioFullText.Length
	'XTrace.show("XTagConverter.transform2", "ioFullText", ioFullText)
		'"rslt", rslt)
	Return rslt
End Function

End Class 'XTagConverter

End Namespace


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.User = exports.userUrl = undefined;

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); // ---------------------------------------------------------------------------
// 'External' modules --------------------------------------------------------
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Project modules -----------------------------------------------------------
// ---------------------------------------------------------------------------

exports.debug = debug;

var _util = require('util');

var _util2 = _interopRequireDefault(_util);

var _request = require('../../request');

var _util3 = require('../util');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// ---------------------------------------------------------------------------
// User URLs -----------------------------------------------------------------
// ---------------------------------------------------------------------------
var userUrl = exports.userUrl = { login: function login() {
        return (0, _util3.baseUrl)('www') + '/login.xml';
    },
    accounts: function accounts() {
        return (0, _util3.baseUrl)('www') + '/users/accounts.xml';
    },
    changeAccount: function changeAccount(_ref) {
        var accountName = _ref.accountName;
        return (0, _util3.baseUrl)(accountName) + '/users/change_account.xml';
    }
};
function debug(x) {
    return _util2.default.inspect(x, { depth: null, colors: true });
}
// ---------------------------------------------------------------------------
// External Class ------------------------------------------------------------
// ---------------------------------------------------------------------------

var User = exports.User = function () {
    function User() {
        _classCallCheck(this, User);
    }

    _createClass(User, null, [{
        key: 'login',
        value: function login(body) {
            return (0, _request.publisher)(Object.assign({}, (0, _util3.unAuthPostSetup)(userUrl.login), { root: 'credentials', body: body })).get('accounts').get('account').then(function (data) {
                return (0, _util3.toArray)(data);
            });
            // AccountLoginInformation[]
        }
    }, {
        key: 'accounts',
        value: function accounts(auth) {
            return (0, _request.getter)((0, _util3.getSetup)(auth, userUrl.accounts, {})).get('accounts').get('account').then(function (data) {
                return (0, _util3.toArray)(data);
            });
            // AccountLoginInformation[]
        }
    }, {
        key: 'changeAccount',
        value: function changeAccount(auth, id) {
            return (0, _request.publisher)(Object.assign({}, (0, _util3.putSetup)(auth, userUrl.changeAccount, { id: id }), { root: 'change_account_to' }));
        }
    }]);

    return User;
}();
//# sourceMappingURL=index.js.map


text:
<!DOCTYPE html>

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


text:
/**
 * @author AnnatarHe
 * @email iamhele1994@gmail.com
 * @date 2017.01.10
 */
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var React = require("react");
var index_1 = require("./index");
var Root = (function (_super) {
    __extends(Root, _super);
    function Root(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            switchStatus: true
        };
        return _this;
    }
    Root.prototype.render = function () {
        var _this = this;
        return (React.createElement("div", null,
            React.createElement(index_1.Switch, { desc: "hello", onChange: function (e) { return _this.setState({ switchStatus: !_this.state.switchStatus }); }, pos: this.state.switchStatus }),
            React.createElement(index_1.Loading, null),
            React.createElement(index_1.Alert, { msg: "hello", type: "success", cb: function () { return console.log('oh'); } })));
    };
    return Root;
}(React.PureComponent));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Root;
//# sourceMappingURL=_root.js.map


text:
[//]: # (title: Equality)

In Kotlin there are two types of equality:

* _Structural_ equality (`==` - a check for `equals()`)
* _Referential_ equality (`===` - two references point to the same object)

## Structural equality

Structural equality is checked by the `==` operation and its negated counterpart `!=`.
By convention, an expression like `a == b` is translated to:

```kotlin
a?.equals(b) ?: (b === null)
```

If `a` is not `null`, it calls the `equals(Any?)` function, otherwise (`a` is `null`) it checks that `b`
is referentially equal to `null`.

Note that there's no point in optimizing your code when comparing to `null` explicitly:
`a == null` will be automatically translated to `a === null`.

To provide a custom equals check implementation, override the
[`equals(other: Any?): Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/equals.html) function.
Functions with the same name and other signatures, like `equals(other: Foo)`, don't affect equality checks with
the operators `==` and `!=`.

Structural equality has nothing to do with comparison defined by the `Comparable<...>` interface, so only a custom
`equals(Any?)` implementation may affect the behavior of the operator.

## Referential equality

Referential equality is checked by the `===` operation and its negated counterpart `!==`. `a === b` evaluates to
true if and only if `a` and `b` point to the same object. For values represented by primitive types at runtime
(for example, `Int`), the `===` equality check is equivalent to the `==` check.

## Floating-point numbers equality

When an equality check operands are statically known to be `Float` or `Double` (nullable or not), the check follows the
[IEEE 754 Standard for Floating-Point Arithmetic](https://en.wikipedia.org/wiki/IEEE_754).

Otherwise, structural equality is used, which disagrees with the standard so that `NaN` is equal to itself, `NaN` is considered greater than any other element, including `POSITIVE_INFINITY`, and `-0.0` is not equal to `0.0`.

See: [Floating-point numbers comparison](numbers.md#floating-point-numbers-comparison).


text:
@interface APServiceExUnsupported () {
 @public
  jint key_;
  IOSByteArray *content_;
}

@end

J2OBJC_FIELD_SETTER(APServiceExUnsupported, content_, IOSByteArray *)

@implementation APServiceExUnsupported

- (instancetype)initWithInt:(jint)key
              withByteArray:(IOSByteArray *)content {
  APServiceExUnsupported_initWithInt_withByteArray_(self, key, content);
  return self;
}

- (jint)getHeader {
  return self->key_;
}

- (void)parseWithBSBserValues:(BSBserValues *)values {
  @throw new_JavaIoIOException_initWithNSString_(@"Parsing is unsupported");
}

- (void)serializeWithBSBserWriter:(BSBserWriter *)writer {
  [((BSBserWriter *) nil_chk(writer)) writeRawWithByteArray:content_];
}

@end

void APServiceExUnsupported_initWithInt_withByteArray_(APServiceExUnsupported *self, jint key, IOSByteArray *content) {
  (void) APServiceEx_init(self);
  self->key_ = key;
  self->content_ = content;
}

APServiceExUnsupported *new_APServiceExUnsupported_initWithInt_withByteArray_(jint key, IOSByteArray *content) {
  APServiceExUnsupported *self = [APServiceExUnsupported alloc];
  APServiceExUnsupported_initWithInt_withByteArray_(self, key, content);
  return self;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(APServiceExUnsupported)


text:
package org.apache.photark.security.authorization.services;

import org.apache.photark.security.authorization.*;
import org.oasisopen.sca.annotation.Init;
import org.oasisopen.sca.annotation.Reference;
import org.oasisopen.sca.annotation.Scope;
import org.oasisopen.sca.annotation.Service;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import static org.apache.photark.security.utils.Constants.*;

@Service(Servlet.class)
@Scope("COMPOSITE")
public class SecurityServiceImpl extends HttpServlet implements Servlet /*SecurityService*/ {

    /**
     *
     */
    private static final long serialVersionUID = -6452934544772432330L;
    private AccessManager accessManager;
    private static boolean initialised = false;
//     private boolean userInit =false;
    //JSONRPCSecurityManager jsonSecurityManager = new JSONRPCSecurityManager();

    @Reference(name = "accessmanager")
    protected void setAccessService(AccessManager accessManager) {
        this.accessManager = accessManager;
    }

    @Init
    public synchronized void init() {
        if (!accessManager.isUserActive(SUPER_ADMIN)) {
            String token = createAccessToken(SUPER_ADMIN);
            accessManager.putAccessListAndToken(accessManager.createAccessList(SUPER_ADMIN, ""), token);
        }
        initialised=true;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
//            AccessList accessList;
        if (!(request.getSession().getAttribute(ACCESS_LIST) != null && !request.getSession().getAttribute(ACCESS_LIST).equals(""))) {
            AccessList accessList = accessManager.createAccessList(GUEST, "");
            request.getSession().setAttribute(ACCESS_LIST, accessList);
//
        }

        PrintWriter out = response.getWriter();
        StringBuffer sb = new StringBuffer();

        if ("getUserInfo".equalsIgnoreCase(request.getParameter("request"))) {
            String userId = ((AccessList) request.getSession().getAttribute(ACCESS_LIST)).getUserId();
            StringBuffer ssb = createJSONUser(request);
            if (accessManager.isUserStoredInList(userId, REGISTERED_USER_LIST)) {
                request.getSession().setAttribute(USER_NEED_TO_REGISTER, "false");

                sb.append("{registered:'true'," + ssb + "}");
                //  response.sendRedirect(request.getContextPath() + "/admin/upload.html");
            } else {
                sb.append("{registered:'false'," + ssb + "}");

            }
            send(out, sb);
        } else if ("setUserInfo".equalsIgnoreCase(request.getParameter("request"))) {
            String userId = ((AccessList) request.getSession().getAttribute(ACCESS_LIST)).getUserId();
            User user;
            if (request.getParameter(USER_DISPLAY_NAME) != null && !request.getParameter(USER_DISPLAY_NAME).trim().equals("")) {
                request.getSession().setAttribute(USER_NEED_TO_REGISTER, "false");
                user = new User(userId);
                UserInfo userInfo = new UserInfo(request.getParameter(USER_DISPLAY_NAME),
                        request.getParameter(USER_EMAIL),
                        request.getParameter(USER_REAL_NAME),
                        request.getParameter(USER_WEBSITE));
                user.setUserInfo(userInfo);

                if (accessManager.isUserStoredInList(userId, UNREGISTERED_USER_LIST)) {
                    accessManager.removeUserFromList(userId, UNREGISTERED_USER_LIST);
                }
                if (!accessManager.isUserStoredInList(userId, REGISTERED_USER_LIST)) {
                    accessManager.addUserToList(user, REGISTERED_USER_LIST);
                }
                sb.append("OK");
            }
            AccessList accessList = accessManager.createAccessList(userId, request.getParameter(USER_EMAIL));
            request.getSession().setAttribute(ACCESS_LIST, accessList);
            send(out, sb);
        } else if ("getUser".equalsIgnoreCase(request.getParameter("request"))) {
            sb.append("{" + createJSONUser(request) + "}");
            send(out, sb);
        } else if ("getJSONAccessList".equalsIgnoreCase(request.getParameter("request"))) {

            sb.append("{" + getJSONAccessList(request) + "}");
            send(out, sb);
        } else {
            response.sendRedirect(request.getContextPath() + "/home/authenticate");
        }

    }

    private String createAccessToken(String userId) {
        Random randomGenerator = new Random();
        String token = "";
        for (int i = 0; i < 25; i++) {
            int n = randomGenerator.nextInt(36);
            if (n < 10) {
                token += (n); // digit 0-9
            } else {
                token += (char) (n - 10 + 'A'); // alpha A-Z
            }
        }
        //  System.out.println(token);

        return userId + token;
    }

    public String getJSONAccessList(HttpServletRequest request) {
        AccessList accessList = (AccessList) request.getSession().getAttribute(ACCESS_LIST);
//        if (!userInit) {
//            accessManager.putAccessListAndToken(accessManager.createAccessList(GUEST, ""), createAccessToken(GUEST));
//            userInit = true;
//        }
        String token;
        if (accessManager.isUserActive(accessList.getUserId())) {
            token = accessManager.getSecurityTokenFromUserId(accessList.getUserId());
            accessList = accessManager.getAccessListFromUserId(accessList.getUserId());
            request.getSession().setAttribute(ACCESS_LIST, accessList);
            accessManager.putAccessListAndToken(accessList, token);
        } else {
            token = createAccessToken(accessList.getUserId());
            accessManager.putAccessListAndToken(accessList, token);
        }
        if(!initialised){
            init();
        }

        //    JSONRPCSecurityManager.putAccessListAndToken(accessList,token);
        String jsonPermission = "|";
        for (String albumName : accessList.getPermissions().keySet()) {
            List permissions = accessList.getPermissions().get(albumName);
            for (Object permission : permissions) {
                jsonPermission += albumName + "." + ((Permission) permission).getPermission() + "|";
            }
        }
        return "userId:'" + accessList.getUserId() +
                "',token:'" + token +
                "',permissions:'" + jsonPermission + "'";

    }

    private void send(PrintWriter out, StringBuffer sb) {
        out.write(sb.toString());
        out.flush();
        out.close();
    }

    private StringBuffer createJSONUser(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        if (request.getSession().getAttribute(ACCESS_LIST) != null && request.getSession().getAttribute(ACCESS_LIST) != "") {

            AccessList accessList = (AccessList) request.getSession().getAttribute(ACCESS_LIST);

            String userId = accessList.getUserId();
            if (userId.equals(SUPER_ADMIN)) {

                sb.append("user:{userId:'" + userId +
                        "',userInfo:{realName:'" +
                        "',displayName:'" + userId +
                        "',email:'" +
                        "',website:'" + "'}}");

            } else {
                User user;
                user = accessManager.getUser(userId);
                UserInfo userInfo = user.getUserInfo();

                sb.append("user:{userId:'" + userId +
                        "',userInfo:{realName:'" + userInfo.getRealName() +
                        "',displayName:'" + userInfo.getDisplayName() +
                        "',email:'" + userInfo.getEmail() +
                        "',website:'" + userInfo.getWebsite() + "'}}");
            }

        } else {
            sb.append("user:{userId:'null'}");
        }
        return sb;
    }

}


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

namespace WindowsFormsApplication1 {

    class ComboBoxItem {
        public String Valeur;
        public int ID;

        public ComboBoxItem(int id, string valeur) {
            Valeur = valeur;
            ID = id;
        }

        //Override ToString method
        public override string ToString() {
            return Valeur;
        }

    }
}


text:
An experiment in node.js, express.js, and Instagram running on Heroku
using less.js.

## What does it do?

The idea was simple: I wanted to put a bit of JS on my blog to show my
latest few instagram photos. I just wanted thumbnails. The problem I ran
into was that Instagram requires authentication to get to a users
photostream, even if that user is marked as public. So, that would imply
that any JS only solution would require the OAuth tokens to be in the
clear in the JavaScript code. That seemed like a bad idea.

So, here's a simple proxy that lets you sign up, OAuth to Instagram, and
get an opaque API key. The API key only lets a client READ from the API
call, and only the most recent 30 photos. This should be safe. The
actual OAuth credentials that give you full access to the Instagram API
will remain on the server.

## What is it built with?

This is still a work in progress, but so far, we're using:

- node.js
- express.js
- less.js
- Bootstrap by Twitter

## License

See the LICENSE file for details.


text: zephir_compiled_expr *zephir_fcall_compile(zephir_context *context, zval *expr TSRMLS_DC);


text:
package br.com.pandox.nursery.domain.alert.event.processor;

import br.com.pandox.nursery.domain.alert.Alert;
import br.com.pandox.nursery.domain.alert.event.DataViolatedThresdhold;
import br.com.pandox.nursery.domain.alert.factory.AlertFactory;
import br.com.pandox.nursery.domain.alert.service.AlertService;
import br.com.pandox.nursery.domain.metric.loader.MetricLoader;
import br.com.pandox.nursery.domain.metric.model.Metric;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class DataViolatedThresholdProcessor {

    @Autowired
    private EventBus eventBus;

    @Autowired
    private AlertService alertService;

    @Autowired
    private AlertFactory alertFactory;

    @Autowired
    private MetricLoader metricLoader;

    public DataViolatedThresholdProcessor() {
    }

    @Deprecated
    public void injectAlertservice(AlertService alertService) {
        this.alertService = alertService;
    }

    @PostConstruct
    public void init() {
        eventBus.register(this);
    }

    @Subscribe
    public void process(DataViolatedThresdhold event) {
        Metric metric = metricLoader.loadByID(event.getMetricId(), false, true);
        if(!metric.getAlerts().isEmpty()){
            return;
        }

        Alert alert = alertFactory.from(metric, event.getData());
        alertService.create(alert);
    }
}


text:
[![](img/featurelayer.png)]()

## サンプル
[台風情報](https://esrijapan.github.io/arcgis-samples-4.0-js/beta/beta1/featureLayer/index.html)

## リソース

* [ArcGIS API 4.0 for JavaScript](https://developers.arcgis.com/javascript/beta/)
    + [esri/layers/FeatureLayer](https://developers.arcgis.com/javascript/beta/api-reference/esri-layers-FeatureLayer.html)


text:
package org.zstack.test.kvm;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.image.ImageInventory;
import org.zstack.header.storage.primary.ImageCacheVO;
import org.zstack.header.storage.primary.ImageCacheVO_;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.kvm.KVMAgentCommands.BootDev;
import org.zstack.kvm.KVMAgentCommands.StartVmCmd;
import org.zstack.kvm.KVMConstant;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.simulator.storage.backup.sftp.SftpBackupStorageSimulatorConfig;
import org.zstack.simulator.storage.primary.nfs.NfsPrimaryStorageSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.test.deployer.schema.NfsPrimaryStorageConfig;
import org.zstack.test.storage.backup.sftp.TestSftpBackupStorageDeleteImage2;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

public class TestCreateVmOnKvmIso {
    CLogger logger = Utils.getLogger(TestSftpBackupStorageDeleteImage2.class);
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    SftpBackupStorageSimulatorConfig config;
    KVMSimulatorConfig kconfig;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/kvm/TestCreateVmOnKvmIso.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        config = loader.getComponent(SftpBackupStorageSimulatorConfig.class);
        kconfig = loader.getComponent(KVMSimulatorConfig.class);
        session = api.loginAsAdmin();
    }

	@Test
	public void test() {
        ImageInventory iso = deployer.images.get("TestImage");
        SimpleQuery query = dbf.createQuery(ImageCacheVO.class);
        query.add(ImageCacheVO_.imageUuid, Op.EQ, iso.getUuid());
        ImageCacheVO isoCache = (ImageCacheVO) query.find();
        Assert.assertNotNull(isoCache);

        StartVmCmd scmd = kconfig.startVmCmd;
        Assert.assertNotNull(scmd);

        Assert.assertEquals(BootDev.cdrom.toString(), scmd.getBootDev().get(0));
        Assert.assertEquals(isoCache.getInstallUrl(), scmd.getBootIso().getPath());

        VmInstanceInventory vm = deployer.vms.get("TestVm");
        Assert.assertEquals("qcow2", vm.getRootVolume().getFormat());
    }
}