text
stringlengths 2
99.9k
| meta
dict |
|---|---|
module BootstrapForm
module Helpers
module Bootstrap
def button(value=nil, options={}, &block)
setup_css_class "btn btn-secondary", options
super
end
def submit(name=nil, options={})
setup_css_class "btn btn-secondary", options
super
end
def primary(name=nil, options={}, &block)
setup_css_class "btn btn-primary", options
if options[:render_as_button] || block_given?
options.except! :render_as_button
button(name, options, &block)
else
submit(name, options)
end
end
def alert_message(title, options={}) # rubocop:disable Metrics/AbcSize
css = options[:class] || "alert alert-danger"
return unless object.respond_to?(:errors) && object.errors.full_messages.any?
tag.div class: css do
concat tag.p title
concat error_summary unless options[:error_summary] == false
end
end
def error_summary
return unless object.errors.any?
tag.ul class: "rails-bootstrap-forms-error-summary" do
object.errors.full_messages.each do |error|
concat tag.li(error)
end
end
end
def errors_on(name, options={})
return unless error?(name)
hide_attribute_name = options[:hide_attribute_name] || false
tag.div class: "alert alert-danger" do
if hide_attribute_name
object.errors[name].join(", ")
else
object.errors.full_messages_for(name).join(", ")
end
end
end
def static_control(*args)
options = args.extract_options!
name = args.first
static_options = options.merge(
readonly: true,
control_class: [options[:control_class], static_class].compact
)
static_options[:value] = object.send(name) unless static_options.key?(:value)
text_field_with_bootstrap(name, static_options)
end
def custom_control(*args, &block)
options = args.extract_options!
name = args.first
form_group_builder(name, options, &block)
end
def prepend_and_append_input(name, options, &block)
options = options.extract!(:prepend, :append, :input_group_class)
input = capture(&block) || ActiveSupport::SafeBuffer.new
input = attach_input(options, :prepend) + input + attach_input(options, :append)
input += generate_error(name)
options.present? &&
input = tag.div(input, class: ["input-group", options[:input_group_class]].compact)
input
end
def input_with_error(name, &block)
input = capture(&block)
input << generate_error(name)
end
def input_group_content(content)
return content if /btn/.match?(content)
tag.span(content, class: "input-group-text")
end
def static_class
"form-control-plaintext"
end
private
def attach_input(options, key)
tags = [*options[key]].map do |item|
tag.div(input_group_content(item), class: "input-group-#{key}")
end
ActiveSupport::SafeBuffer.new(tags.join)
end
def setup_css_class(the_class, options={})
return if options.key? :class
if (extra_class = options.delete(:extra_class))
the_class = "#{the_class} #{extra_class}"
end
options[:class] = the_class
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
# Settings specified here will take precedence over those in config/environment.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.action_controller.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.action_view.cache_template_loading = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
|
{
"pile_set_name": "Github"
}
|
/*
Simple DirectMedia Layer
Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
#if (SDL_VIDEO_RENDER_D3D || SDL_VIDEO_RENDER_D3D11) && !SDL_RENDER_DISABLED
#include "SDL_stdinc.h"
#include "SDL_d3dmath.h"
/* Direct3D matrix math functions */
Float4X4 MatrixIdentity()
{
Float4X4 m;
SDL_zero(m);
m._11 = 1.0f;
m._22 = 1.0f;
m._33 = 1.0f;
m._44 = 1.0f;
return m;
}
Float4X4 MatrixMultiply(Float4X4 M1, Float4X4 M2)
{
Float4X4 m;
m._11 = M1._11 * M2._11 + M1._12 * M2._21 + M1._13 * M2._31 + M1._14 * M2._41;
m._12 = M1._11 * M2._12 + M1._12 * M2._22 + M1._13 * M2._32 + M1._14 * M2._42;
m._13 = M1._11 * M2._13 + M1._12 * M2._23 + M1._13 * M2._33 + M1._14 * M2._43;
m._14 = M1._11 * M2._14 + M1._12 * M2._24 + M1._13 * M2._34 + M1._14 * M2._44;
m._21 = M1._21 * M2._11 + M1._22 * M2._21 + M1._23 * M2._31 + M1._24 * M2._41;
m._22 = M1._21 * M2._12 + M1._22 * M2._22 + M1._23 * M2._32 + M1._24 * M2._42;
m._23 = M1._21 * M2._13 + M1._22 * M2._23 + M1._23 * M2._33 + M1._24 * M2._43;
m._24 = M1._21 * M2._14 + M1._22 * M2._24 + M1._23 * M2._34 + M1._24 * M2._44;
m._31 = M1._31 * M2._11 + M1._32 * M2._21 + M1._33 * M2._31 + M1._34 * M2._41;
m._32 = M1._31 * M2._12 + M1._32 * M2._22 + M1._33 * M2._32 + M1._34 * M2._42;
m._33 = M1._31 * M2._13 + M1._32 * M2._23 + M1._33 * M2._33 + M1._34 * M2._43;
m._34 = M1._31 * M2._14 + M1._32 * M2._24 + M1._33 * M2._34 + M1._34 * M2._44;
m._41 = M1._41 * M2._11 + M1._42 * M2._21 + M1._43 * M2._31 + M1._44 * M2._41;
m._42 = M1._41 * M2._12 + M1._42 * M2._22 + M1._43 * M2._32 + M1._44 * M2._42;
m._43 = M1._41 * M2._13 + M1._42 * M2._23 + M1._43 * M2._33 + M1._44 * M2._43;
m._44 = M1._41 * M2._14 + M1._42 * M2._24 + M1._43 * M2._34 + M1._44 * M2._44;
return m;
}
Float4X4 MatrixScaling(float x, float y, float z)
{
Float4X4 m;
SDL_zero(m);
m._11 = x;
m._22 = y;
m._33 = z;
m._44 = 1.0f;
return m;
}
Float4X4 MatrixTranslation(float x, float y, float z)
{
Float4X4 m;
SDL_zero(m);
m._11 = 1.0f;
m._22 = 1.0f;
m._33 = 1.0f;
m._44 = 1.0f;
m._41 = x;
m._42 = y;
m._43 = z;
return m;
}
Float4X4 MatrixRotationX(float r)
{
float sinR = SDL_sinf(r);
float cosR = SDL_cosf(r);
Float4X4 m;
SDL_zero(m);
m._11 = 1.0f;
m._22 = cosR;
m._23 = sinR;
m._32 = -sinR;
m._33 = cosR;
m._44 = 1.0f;
return m;
}
Float4X4 MatrixRotationY(float r)
{
float sinR = SDL_sinf(r);
float cosR = SDL_cosf(r);
Float4X4 m;
SDL_zero(m);
m._11 = cosR;
m._13 = -sinR;
m._22 = 1.0f;
m._31 = sinR;
m._33 = cosR;
m._44 = 1.0f;
return m;
}
Float4X4 MatrixRotationZ(float r)
{
float sinR = SDL_sinf(r);
float cosR = SDL_cosf(r);
Float4X4 m;
SDL_zero(m);
m._11 = cosR;
m._12 = sinR;
m._21 = -sinR;
m._22 = cosR;
m._33 = 1.0f;
m._44 = 1.0f;
return m;
}
#endif /* (SDL_VIDEO_RENDER_D3D || SDL_VIDEO_RENDER_D3D11) && !SDL_RENDER_DISABLED */
/* vi: set ts=4 sw=4 expandtab: */
|
{
"pile_set_name": "Github"
}
|
// lib.rs
//
// Copyright (c) 2020 All The Music, LLC
//
// This work is licensed under the Creative Commons Attribution 4.0 International License.
// To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send
// a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
//! `libatm` is a library for generating and working with MIDI files. It was purpose-built for
//! All the Music, LLC to assist in its mission to enable musicians to make all of their music
//! without the fear of frivolous copyright lawsuits. All code is released into the public domain
//! via the [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/).
//! If you're looking for a command line tool to generate and work with MIDI files, check out
//! [the `atm-cli` project](https://github.com/allthemusicllc/atm-cli) that utilizes this library. For
//! more information on All the Music, check out [allthemusic.info](http://allthemusic.info).
// Allow dead code
#![allow(unused_parens)]
extern crate byteorder;
extern crate thiserror;
pub mod midi_event;
pub mod midi_file;
pub mod midi_note;
pub use midi_event::*;
pub use midi_file::*;
pub use midi_note::*;
// TODO: Finish writing tests for each module
// #[cfg(test)]
// mod tests {
// use super::*;
//
// #[test]
// fn test_midievent_noteon() {
// let note = MIDINote::new(MIDINoteType::C, 4);
// let event = MIDIChannelVoiceMessage::new(0, ¬e, 100, MIDIStatus::NoteOn, 0);
// let status = 0b10010000;
// assert_eq!(status, event.status);
// }
//
// #[test]
// fn test_midievent_runningstatus() {
// let note = MIDINote::new(MIDINoteType::C, 4);
// let event = MIDIChannelVoiceMessage::new(0, ¬e, 100, MIDIStatus::RunningStatus, 0);
// assert_eq!(0, event.status);
// }
//
// #[test]
// fn test_midifile_size() {
// let sequence = "C:4,D:4,E:4,C:4,D:4,E:4,C:4,D:4,E:4,C:4,D:4,E:4"
// .parse::<MIDINoteSet>()
// .unwrap();
// let mfile = MIDIFile::new(sequence, MIDIFormat::Format0, 1, 1);
// assert_eq!(95, mfile.gen_size());
// }
// }
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
*
* psaux.h
*
* Auxiliary functions and data structures related to PostScript fonts
* (specification).
*
* Copyright (C) 1996-2019 by
* David Turner, Robert Wilhelm, and Werner Lemberg.
*
* This file is part of the FreeType project, and may only be used,
* modified, and distributed under the terms of the FreeType project
* license, LICENSE.TXT. By continuing to use, modify, or distribute
* this file you indicate that you have read the license and
* understand and accept it fully.
*
*/
#ifndef PSAUX_H_
#define PSAUX_H_
#include <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_TYPE1_TYPES_H
#include FT_INTERNAL_HASH_H
#include FT_INTERNAL_TRUETYPE_TYPES_H
#include FT_SERVICE_POSTSCRIPT_CMAPS_H
#include FT_INTERNAL_CFF_TYPES_H
#include FT_INTERNAL_CFF_OBJECTS_TYPES_H
FT_BEGIN_HEADER
/**************************************************************************
*
* PostScript modules driver class.
*/
typedef struct PS_DriverRec_
{
FT_DriverRec root;
FT_UInt hinting_engine;
FT_Bool no_stem_darkening;
FT_Int darken_params[8];
FT_Int32 random_seed;
} PS_DriverRec, *PS_Driver;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1_TABLE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct PS_TableRec_* PS_Table;
typedef const struct PS_Table_FuncsRec_* PS_Table_Funcs;
/**************************************************************************
*
* @struct:
* PS_Table_FuncsRec
*
* @description:
* A set of function pointers to manage PS_Table objects.
*
* @fields:
* table_init ::
* Used to initialize a table.
*
* table_done ::
* Finalizes resp. destroy a given table.
*
* table_add ::
* Adds a new object to a table.
*
* table_release ::
* Releases table data, then finalizes it.
*/
typedef struct PS_Table_FuncsRec_
{
FT_Error
(*init)( PS_Table table,
FT_Int count,
FT_Memory memory );
void
(*done)( PS_Table table );
FT_Error
(*add)( PS_Table table,
FT_Int idx,
const void* object,
FT_UInt length );
void
(*release)( PS_Table table );
} PS_Table_FuncsRec;
/**************************************************************************
*
* @struct:
* PS_TableRec
*
* @description:
* A PS_Table is a simple object used to store an array of objects in a
* single memory block.
*
* @fields:
* block ::
* The address in memory of the growheap's block. This can change
* between two object adds, due to reallocation.
*
* cursor ::
* The current top of the grow heap within its block.
*
* capacity ::
* The current size of the heap block. Increments by 1kByte chunks.
*
* init ::
* Set to 0xDEADBEEF if 'elements' and 'lengths' have been allocated.
*
* max_elems ::
* The maximum number of elements in table.
*
* num_elems ::
* The current number of elements in table.
*
* elements ::
* A table of element addresses within the block.
*
* lengths ::
* A table of element sizes within the block.
*
* memory ::
* The object used for memory operations (alloc/realloc).
*
* funcs ::
* A table of method pointers for this object.
*/
typedef struct PS_TableRec_
{
FT_Byte* block; /* current memory block */
FT_Offset cursor; /* current cursor in memory block */
FT_Offset capacity; /* current size of memory block */
FT_ULong init;
FT_Int max_elems;
FT_Int num_elems;
FT_Byte** elements; /* addresses of table elements */
FT_UInt* lengths; /* lengths of table elements */
FT_Memory memory;
PS_Table_FuncsRec funcs;
} PS_TableRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 FIELDS & TOKENS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct PS_ParserRec_* PS_Parser;
typedef struct T1_TokenRec_* T1_Token;
typedef struct T1_FieldRec_* T1_Field;
/* simple enumeration type used to identify token types */
typedef enum T1_TokenType_
{
T1_TOKEN_TYPE_NONE = 0,
T1_TOKEN_TYPE_ANY,
T1_TOKEN_TYPE_STRING,
T1_TOKEN_TYPE_ARRAY,
T1_TOKEN_TYPE_KEY, /* aka `name' */
/* do not remove */
T1_TOKEN_TYPE_MAX
} T1_TokenType;
/* a simple structure used to identify tokens */
typedef struct T1_TokenRec_
{
FT_Byte* start; /* first character of token in input stream */
FT_Byte* limit; /* first character after the token */
T1_TokenType type; /* type of token */
} T1_TokenRec;
/* enumeration type used to identify object fields */
typedef enum T1_FieldType_
{
T1_FIELD_TYPE_NONE = 0,
T1_FIELD_TYPE_BOOL,
T1_FIELD_TYPE_INTEGER,
T1_FIELD_TYPE_FIXED,
T1_FIELD_TYPE_FIXED_1000,
T1_FIELD_TYPE_STRING,
T1_FIELD_TYPE_KEY,
T1_FIELD_TYPE_BBOX,
T1_FIELD_TYPE_MM_BBOX,
T1_FIELD_TYPE_INTEGER_ARRAY,
T1_FIELD_TYPE_FIXED_ARRAY,
T1_FIELD_TYPE_CALLBACK,
/* do not remove */
T1_FIELD_TYPE_MAX
} T1_FieldType;
typedef enum T1_FieldLocation_
{
T1_FIELD_LOCATION_CID_INFO,
T1_FIELD_LOCATION_FONT_DICT,
T1_FIELD_LOCATION_FONT_EXTRA,
T1_FIELD_LOCATION_FONT_INFO,
T1_FIELD_LOCATION_PRIVATE,
T1_FIELD_LOCATION_BBOX,
T1_FIELD_LOCATION_LOADER,
T1_FIELD_LOCATION_FACE,
T1_FIELD_LOCATION_BLEND,
/* do not remove */
T1_FIELD_LOCATION_MAX
} T1_FieldLocation;
typedef void
(*T1_Field_ParseFunc)( FT_Face face,
FT_Pointer parser );
/* structure type used to model object fields */
typedef struct T1_FieldRec_
{
const char* ident; /* field identifier */
T1_FieldLocation location;
T1_FieldType type; /* type of field */
T1_Field_ParseFunc reader;
FT_UInt offset; /* offset of field in object */
FT_Byte size; /* size of field in bytes */
FT_UInt array_max; /* maximum number of elements for */
/* array */
FT_UInt count_offset; /* offset of element count for */
/* arrays; must not be zero if in */
/* use -- in other words, a */
/* `num_FOO' element must not */
/* start the used structure if we */
/* parse a `FOO' array */
FT_UInt dict; /* where we expect it */
} T1_FieldRec;
#define T1_FIELD_DICT_FONTDICT ( 1 << 0 ) /* also FontInfo and FDArray */
#define T1_FIELD_DICT_PRIVATE ( 1 << 1 )
#define T1_NEW_SIMPLE_FIELD( _ident, _type, _fname, _dict ) \
{ \
_ident, T1CODE, _type, \
0, \
FT_FIELD_OFFSET( _fname ), \
FT_FIELD_SIZE( _fname ), \
0, 0, \
_dict \
},
#define T1_NEW_CALLBACK_FIELD( _ident, _reader, _dict ) \
{ \
_ident, T1CODE, T1_FIELD_TYPE_CALLBACK, \
(T1_Field_ParseFunc)_reader, \
0, 0, \
0, 0, \
_dict \
},
#define T1_NEW_TABLE_FIELD( _ident, _type, _fname, _max, _dict ) \
{ \
_ident, T1CODE, _type, \
0, \
FT_FIELD_OFFSET( _fname ), \
FT_FIELD_SIZE_DELTA( _fname ), \
_max, \
FT_FIELD_OFFSET( num_ ## _fname ), \
_dict \
},
#define T1_NEW_TABLE_FIELD2( _ident, _type, _fname, _max, _dict ) \
{ \
_ident, T1CODE, _type, \
0, \
FT_FIELD_OFFSET( _fname ), \
FT_FIELD_SIZE_DELTA( _fname ), \
_max, 0, \
_dict \
},
#define T1_FIELD_BOOL( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BOOL, _fname, _dict )
#define T1_FIELD_NUM( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER, _fname, _dict )
#define T1_FIELD_FIXED( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED, _fname, _dict )
#define T1_FIELD_FIXED_1000( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_1000, _fname, \
_dict )
#define T1_FIELD_STRING( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_STRING, _fname, _dict )
#define T1_FIELD_KEY( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_KEY, _fname, _dict )
#define T1_FIELD_BBOX( _ident, _fname, _dict ) \
T1_NEW_SIMPLE_FIELD( _ident, T1_FIELD_TYPE_BBOX, _fname, _dict )
#define T1_FIELD_NUM_TABLE( _ident, _fname, _fmax, _dict ) \
T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \
_fname, _fmax, _dict )
#define T1_FIELD_FIXED_TABLE( _ident, _fname, _fmax, _dict ) \
T1_NEW_TABLE_FIELD( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \
_fname, _fmax, _dict )
#define T1_FIELD_NUM_TABLE2( _ident, _fname, _fmax, _dict ) \
T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_INTEGER_ARRAY, \
_fname, _fmax, _dict )
#define T1_FIELD_FIXED_TABLE2( _ident, _fname, _fmax, _dict ) \
T1_NEW_TABLE_FIELD2( _ident, T1_FIELD_TYPE_FIXED_ARRAY, \
_fname, _fmax, _dict )
#define T1_FIELD_CALLBACK( _ident, _name, _dict ) \
T1_NEW_CALLBACK_FIELD( _ident, _name, _dict )
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef const struct PS_Parser_FuncsRec_* PS_Parser_Funcs;
typedef struct PS_Parser_FuncsRec_
{
void
(*init)( PS_Parser parser,
FT_Byte* base,
FT_Byte* limit,
FT_Memory memory );
void
(*done)( PS_Parser parser );
void
(*skip_spaces)( PS_Parser parser );
void
(*skip_PS_token)( PS_Parser parser );
FT_Long
(*to_int)( PS_Parser parser );
FT_Fixed
(*to_fixed)( PS_Parser parser,
FT_Int power_ten );
FT_Error
(*to_bytes)( PS_Parser parser,
FT_Byte* bytes,
FT_Offset max_bytes,
FT_ULong* pnum_bytes,
FT_Bool delimiters );
FT_Int
(*to_coord_array)( PS_Parser parser,
FT_Int max_coords,
FT_Short* coords );
FT_Int
(*to_fixed_array)( PS_Parser parser,
FT_Int max_values,
FT_Fixed* values,
FT_Int power_ten );
void
(*to_token)( PS_Parser parser,
T1_Token token );
void
(*to_token_array)( PS_Parser parser,
T1_Token tokens,
FT_UInt max_tokens,
FT_Int* pnum_tokens );
FT_Error
(*load_field)( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags );
FT_Error
(*load_field_table)( PS_Parser parser,
const T1_Field field,
void** objects,
FT_UInt max_objects,
FT_ULong* pflags );
} PS_Parser_FuncsRec;
/**************************************************************************
*
* @struct:
* PS_ParserRec
*
* @description:
* A PS_Parser is an object used to parse a Type 1 font very quickly.
*
* @fields:
* cursor ::
* The current position in the text.
*
* base ::
* Start of the processed text.
*
* limit ::
* End of the processed text.
*
* error ::
* The last error returned.
*
* memory ::
* The object used for memory operations (alloc/realloc).
*
* funcs ::
* A table of functions for the parser.
*/
typedef struct PS_ParserRec_
{
FT_Byte* cursor;
FT_Byte* base;
FT_Byte* limit;
FT_Error error;
FT_Memory memory;
PS_Parser_FuncsRec funcs;
} PS_ParserRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PS BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct PS_Builder_ PS_Builder;
typedef const struct PS_Builder_FuncsRec_* PS_Builder_Funcs;
typedef struct PS_Builder_FuncsRec_
{
void
(*init)( PS_Builder* ps_builder,
void* builder,
FT_Bool is_t1 );
void
(*done)( PS_Builder* builder );
} PS_Builder_FuncsRec;
/**************************************************************************
*
* @struct:
* PS_Builder
*
* @description:
* A structure used during glyph loading to store its outline.
*
* @fields:
* memory ::
* The current memory object.
*
* face ::
* The current face object.
*
* glyph ::
* The current glyph slot.
*
* loader ::
* XXX
*
* base ::
* The base glyph outline.
*
* current ::
* The current glyph outline.
*
* pos_x ::
* The horizontal translation (if composite glyph).
*
* pos_y ::
* The vertical translation (if composite glyph).
*
* left_bearing ::
* The left side bearing point.
*
* advance ::
* The horizontal advance vector.
*
* bbox ::
* Unused.
*
* path_begun ::
* A flag which indicates that a new path has begun.
*
* load_points ::
* If this flag is not set, no points are loaded.
*
* no_recurse ::
* Set but not used.
*
* metrics_only ::
* A boolean indicating that we only want to compute the metrics of a
* given glyph, not load all of its points.
*
* is_t1 ::
* Set if current font type is Type 1.
*
* funcs ::
* An array of function pointers for the builder.
*/
struct PS_Builder_
{
FT_Memory memory;
FT_Face face;
CFF_GlyphSlot glyph;
FT_GlyphLoader loader;
FT_Outline* base;
FT_Outline* current;
FT_Pos* pos_x;
FT_Pos* pos_y;
FT_Vector* left_bearing;
FT_Vector* advance;
FT_BBox* bbox; /* bounding box */
FT_Bool path_begun;
FT_Bool load_points;
FT_Bool no_recurse;
FT_Bool metrics_only;
FT_Bool is_t1;
PS_Builder_FuncsRec funcs;
};
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PS DECODER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define PS_MAX_OPERANDS 48
#define PS_MAX_SUBRS_CALLS 16 /* maximum subroutine nesting; */
/* only 10 are allowed but there exist */
/* fonts like `HiraKakuProN-W3.ttf' */
/* (Hiragino Kaku Gothic ProN W3; */
/* 8.2d6e1; 2014-12-19) that exceed */
/* this limit */
/* execution context charstring zone */
typedef struct PS_Decoder_Zone_
{
FT_Byte* base;
FT_Byte* limit;
FT_Byte* cursor;
} PS_Decoder_Zone;
typedef FT_Error
(*CFF_Decoder_Get_Glyph_Callback)( TT_Face face,
FT_UInt glyph_index,
FT_Byte** pointer,
FT_ULong* length );
typedef void
(*CFF_Decoder_Free_Glyph_Callback)( TT_Face face,
FT_Byte** pointer,
FT_ULong length );
typedef struct PS_Decoder_
{
PS_Builder builder;
FT_Fixed stack[PS_MAX_OPERANDS + 1];
FT_Fixed* top;
PS_Decoder_Zone zones[PS_MAX_SUBRS_CALLS + 1];
PS_Decoder_Zone* zone;
FT_Int flex_state;
FT_Int num_flex_vectors;
FT_Vector flex_vectors[7];
CFF_Font cff;
CFF_SubFont current_subfont; /* for current glyph_index */
FT_Generic* cf2_instance;
FT_Pos* glyph_width;
FT_Bool width_only;
FT_Int num_hints;
FT_UInt num_locals;
FT_UInt num_globals;
FT_Int locals_bias;
FT_Int globals_bias;
FT_Byte** locals;
FT_Byte** globals;
FT_Byte** glyph_names; /* for pure CFF fonts only */
FT_UInt num_glyphs; /* number of glyphs in font */
FT_Render_Mode hint_mode;
FT_Bool seac;
CFF_Decoder_Get_Glyph_Callback get_glyph_callback;
CFF_Decoder_Free_Glyph_Callback free_glyph_callback;
/* Type 1 stuff */
FT_Service_PsCMaps psnames; /* for seac */
FT_Int lenIV; /* internal for sub routine calls */
FT_UInt* locals_len; /* array of subrs length (optional) */
FT_Hash locals_hash; /* used if `num_subrs' was massaged */
FT_Matrix font_matrix;
FT_Vector font_offset;
PS_Blend blend; /* for multiple master support */
FT_Long* buildchar;
FT_UInt len_buildchar;
} PS_Decoder;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct T1_BuilderRec_* T1_Builder;
typedef FT_Error
(*T1_Builder_Check_Points_Func)( T1_Builder builder,
FT_Int count );
typedef void
(*T1_Builder_Add_Point_Func)( T1_Builder builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag );
typedef FT_Error
(*T1_Builder_Add_Point1_Func)( T1_Builder builder,
FT_Pos x,
FT_Pos y );
typedef FT_Error
(*T1_Builder_Add_Contour_Func)( T1_Builder builder );
typedef FT_Error
(*T1_Builder_Start_Point_Func)( T1_Builder builder,
FT_Pos x,
FT_Pos y );
typedef void
(*T1_Builder_Close_Contour_Func)( T1_Builder builder );
typedef const struct T1_Builder_FuncsRec_* T1_Builder_Funcs;
typedef struct T1_Builder_FuncsRec_
{
void
(*init)( T1_Builder builder,
FT_Face face,
FT_Size size,
FT_GlyphSlot slot,
FT_Bool hinting );
void
(*done)( T1_Builder builder );
T1_Builder_Check_Points_Func check_points;
T1_Builder_Add_Point_Func add_point;
T1_Builder_Add_Point1_Func add_point1;
T1_Builder_Add_Contour_Func add_contour;
T1_Builder_Start_Point_Func start_point;
T1_Builder_Close_Contour_Func close_contour;
} T1_Builder_FuncsRec;
/* an enumeration type to handle charstring parsing states */
typedef enum T1_ParseState_
{
T1_Parse_Start,
T1_Parse_Have_Width,
T1_Parse_Have_Moveto,
T1_Parse_Have_Path
} T1_ParseState;
/**************************************************************************
*
* @struct:
* T1_BuilderRec
*
* @description:
* A structure used during glyph loading to store its outline.
*
* @fields:
* memory ::
* The current memory object.
*
* face ::
* The current face object.
*
* glyph ::
* The current glyph slot.
*
* loader ::
* XXX
*
* base ::
* The base glyph outline.
*
* current ::
* The current glyph outline.
*
* max_points ::
* maximum points in builder outline
*
* max_contours ::
* Maximum number of contours in builder outline.
*
* pos_x ::
* The horizontal translation (if composite glyph).
*
* pos_y ::
* The vertical translation (if composite glyph).
*
* left_bearing ::
* The left side bearing point.
*
* advance ::
* The horizontal advance vector.
*
* bbox ::
* Unused.
*
* parse_state ::
* An enumeration which controls the charstring parsing state.
*
* load_points ::
* If this flag is not set, no points are loaded.
*
* no_recurse ::
* Set but not used.
*
* metrics_only ::
* A boolean indicating that we only want to compute the metrics of a
* given glyph, not load all of its points.
*
* funcs ::
* An array of function pointers for the builder.
*/
typedef struct T1_BuilderRec_
{
FT_Memory memory;
FT_Face face;
FT_GlyphSlot glyph;
FT_GlyphLoader loader;
FT_Outline* base;
FT_Outline* current;
FT_Pos pos_x;
FT_Pos pos_y;
FT_Vector left_bearing;
FT_Vector advance;
FT_BBox bbox; /* bounding box */
T1_ParseState parse_state;
FT_Bool load_points;
FT_Bool no_recurse;
FT_Bool metrics_only;
void* hints_funcs; /* hinter-specific */
void* hints_globals; /* hinter-specific */
T1_Builder_FuncsRec funcs;
} T1_BuilderRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** T1 DECODER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#if 0
/**************************************************************************
*
* T1_MAX_SUBRS_CALLS details the maximum number of nested sub-routine
* calls during glyph loading.
*/
#define T1_MAX_SUBRS_CALLS 8
/**************************************************************************
*
* T1_MAX_CHARSTRING_OPERANDS is the charstring stack's capacity. A
* minimum of 16 is required.
*/
#define T1_MAX_CHARSTRINGS_OPERANDS 32
#endif /* 0 */
typedef struct T1_Decoder_ZoneRec_
{
FT_Byte* cursor;
FT_Byte* base;
FT_Byte* limit;
} T1_Decoder_ZoneRec, *T1_Decoder_Zone;
typedef struct T1_DecoderRec_* T1_Decoder;
typedef const struct T1_Decoder_FuncsRec_* T1_Decoder_Funcs;
typedef FT_Error
(*T1_Decoder_Callback)( T1_Decoder decoder,
FT_UInt glyph_index );
typedef struct T1_Decoder_FuncsRec_
{
FT_Error
(*init)( T1_Decoder decoder,
FT_Face face,
FT_Size size,
FT_GlyphSlot slot,
FT_Byte** glyph_names,
PS_Blend blend,
FT_Bool hinting,
FT_Render_Mode hint_mode,
T1_Decoder_Callback callback );
void
(*done)( T1_Decoder decoder );
#ifdef T1_CONFIG_OPTION_OLD_ENGINE
FT_Error
(*parse_charstrings_old)( T1_Decoder decoder,
FT_Byte* base,
FT_UInt len );
#else
FT_Error
(*parse_metrics)( T1_Decoder decoder,
FT_Byte* base,
FT_UInt len );
#endif
FT_Error
(*parse_charstrings)( PS_Decoder* decoder,
FT_Byte* charstring_base,
FT_ULong charstring_len );
} T1_Decoder_FuncsRec;
typedef struct T1_DecoderRec_
{
T1_BuilderRec builder;
FT_Long stack[T1_MAX_CHARSTRINGS_OPERANDS];
FT_Long* top;
T1_Decoder_ZoneRec zones[T1_MAX_SUBRS_CALLS + 1];
T1_Decoder_Zone zone;
FT_Service_PsCMaps psnames; /* for seac */
FT_UInt num_glyphs;
FT_Byte** glyph_names;
FT_Int lenIV; /* internal for sub routine calls */
FT_Int num_subrs;
FT_Byte** subrs;
FT_UInt* subrs_len; /* array of subrs length (optional) */
FT_Hash subrs_hash; /* used if `num_subrs' was massaged */
FT_Matrix font_matrix;
FT_Vector font_offset;
FT_Int flex_state;
FT_Int num_flex_vectors;
FT_Vector flex_vectors[7];
PS_Blend blend; /* for multiple master support */
FT_Render_Mode hint_mode;
T1_Decoder_Callback parse_callback;
T1_Decoder_FuncsRec funcs;
FT_Long* buildchar;
FT_UInt len_buildchar;
FT_Bool seac;
FT_Generic cf2_instance;
} T1_DecoderRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CFF BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct CFF_Builder_ CFF_Builder;
typedef FT_Error
(*CFF_Builder_Check_Points_Func)( CFF_Builder* builder,
FT_Int count );
typedef void
(*CFF_Builder_Add_Point_Func)( CFF_Builder* builder,
FT_Pos x,
FT_Pos y,
FT_Byte flag );
typedef FT_Error
(*CFF_Builder_Add_Point1_Func)( CFF_Builder* builder,
FT_Pos x,
FT_Pos y );
typedef FT_Error
(*CFF_Builder_Start_Point_Func)( CFF_Builder* builder,
FT_Pos x,
FT_Pos y );
typedef void
(*CFF_Builder_Close_Contour_Func)( CFF_Builder* builder );
typedef FT_Error
(*CFF_Builder_Add_Contour_Func)( CFF_Builder* builder );
typedef const struct CFF_Builder_FuncsRec_* CFF_Builder_Funcs;
typedef struct CFF_Builder_FuncsRec_
{
void
(*init)( CFF_Builder* builder,
TT_Face face,
CFF_Size size,
CFF_GlyphSlot glyph,
FT_Bool hinting );
void
(*done)( CFF_Builder* builder );
CFF_Builder_Check_Points_Func check_points;
CFF_Builder_Add_Point_Func add_point;
CFF_Builder_Add_Point1_Func add_point1;
CFF_Builder_Add_Contour_Func add_contour;
CFF_Builder_Start_Point_Func start_point;
CFF_Builder_Close_Contour_Func close_contour;
} CFF_Builder_FuncsRec;
/**************************************************************************
*
* @struct:
* CFF_Builder
*
* @description:
* A structure used during glyph loading to store its outline.
*
* @fields:
* memory ::
* The current memory object.
*
* face ::
* The current face object.
*
* glyph ::
* The current glyph slot.
*
* loader ::
* The current glyph loader.
*
* base ::
* The base glyph outline.
*
* current ::
* The current glyph outline.
*
* pos_x ::
* The horizontal translation (if composite glyph).
*
* pos_y ::
* The vertical translation (if composite glyph).
*
* left_bearing ::
* The left side bearing point.
*
* advance ::
* The horizontal advance vector.
*
* bbox ::
* Unused.
*
* path_begun ::
* A flag which indicates that a new path has begun.
*
* load_points ::
* If this flag is not set, no points are loaded.
*
* no_recurse ::
* Set but not used.
*
* metrics_only ::
* A boolean indicating that we only want to compute the metrics of a
* given glyph, not load all of its points.
*
* hints_funcs ::
* Auxiliary pointer for hinting.
*
* hints_globals ::
* Auxiliary pointer for hinting.
*
* funcs ::
* A table of method pointers for this object.
*/
struct CFF_Builder_
{
FT_Memory memory;
TT_Face face;
CFF_GlyphSlot glyph;
FT_GlyphLoader loader;
FT_Outline* base;
FT_Outline* current;
FT_Pos pos_x;
FT_Pos pos_y;
FT_Vector left_bearing;
FT_Vector advance;
FT_BBox bbox; /* bounding box */
FT_Bool path_begun;
FT_Bool load_points;
FT_Bool no_recurse;
FT_Bool metrics_only;
void* hints_funcs; /* hinter-specific */
void* hints_globals; /* hinter-specific */
CFF_Builder_FuncsRec funcs;
};
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** CFF DECODER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define CFF_MAX_OPERANDS 48
#define CFF_MAX_SUBRS_CALLS 16 /* maximum subroutine nesting; */
/* only 10 are allowed but there exist */
/* fonts like `HiraKakuProN-W3.ttf' */
/* (Hiragino Kaku Gothic ProN W3; */
/* 8.2d6e1; 2014-12-19) that exceed */
/* this limit */
#define CFF_MAX_TRANS_ELEMENTS 32
/* execution context charstring zone */
typedef struct CFF_Decoder_Zone_
{
FT_Byte* base;
FT_Byte* limit;
FT_Byte* cursor;
} CFF_Decoder_Zone;
typedef struct CFF_Decoder_
{
CFF_Builder builder;
CFF_Font cff;
FT_Fixed stack[CFF_MAX_OPERANDS + 1];
FT_Fixed* top;
CFF_Decoder_Zone zones[CFF_MAX_SUBRS_CALLS + 1];
CFF_Decoder_Zone* zone;
FT_Int flex_state;
FT_Int num_flex_vectors;
FT_Vector flex_vectors[7];
FT_Pos glyph_width;
FT_Pos nominal_width;
FT_Bool read_width;
FT_Bool width_only;
FT_Int num_hints;
FT_Fixed buildchar[CFF_MAX_TRANS_ELEMENTS];
FT_UInt num_locals;
FT_UInt num_globals;
FT_Int locals_bias;
FT_Int globals_bias;
FT_Byte** locals;
FT_Byte** globals;
FT_Byte** glyph_names; /* for pure CFF fonts only */
FT_UInt num_glyphs; /* number of glyphs in font */
FT_Render_Mode hint_mode;
FT_Bool seac;
CFF_SubFont current_subfont; /* for current glyph_index */
CFF_Decoder_Get_Glyph_Callback get_glyph_callback;
CFF_Decoder_Free_Glyph_Callback free_glyph_callback;
} CFF_Decoder;
typedef const struct CFF_Decoder_FuncsRec_* CFF_Decoder_Funcs;
typedef struct CFF_Decoder_FuncsRec_
{
void
(*init)( CFF_Decoder* decoder,
TT_Face face,
CFF_Size size,
CFF_GlyphSlot slot,
FT_Bool hinting,
FT_Render_Mode hint_mode,
CFF_Decoder_Get_Glyph_Callback get_callback,
CFF_Decoder_Free_Glyph_Callback free_callback );
FT_Error
(*prepare)( CFF_Decoder* decoder,
CFF_Size size,
FT_UInt glyph_index );
#ifdef CFF_CONFIG_OPTION_OLD_ENGINE
FT_Error
(*parse_charstrings_old)( CFF_Decoder* decoder,
FT_Byte* charstring_base,
FT_ULong charstring_len,
FT_Bool in_dict );
#endif
FT_Error
(*parse_charstrings)( PS_Decoder* decoder,
FT_Byte* charstring_base,
FT_ULong charstring_len );
} CFF_Decoder_FuncsRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** AFM PARSER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct AFM_ParserRec_* AFM_Parser;
typedef struct AFM_Parser_FuncsRec_
{
FT_Error
(*init)( AFM_Parser parser,
FT_Memory memory,
FT_Byte* base,
FT_Byte* limit );
void
(*done)( AFM_Parser parser );
FT_Error
(*parse)( AFM_Parser parser );
} AFM_Parser_FuncsRec;
typedef struct AFM_StreamRec_* AFM_Stream;
/**************************************************************************
*
* @struct:
* AFM_ParserRec
*
* @description:
* An AFM_Parser is a parser for the AFM files.
*
* @fields:
* memory ::
* The object used for memory operations (alloc and realloc).
*
* stream ::
* This is an opaque object.
*
* FontInfo ::
* The result will be stored here.
*
* get_index ::
* A user provided function to get a glyph index by its name.
*/
typedef struct AFM_ParserRec_
{
FT_Memory memory;
AFM_Stream stream;
AFM_FontInfo FontInfo;
FT_Int
(*get_index)( const char* name,
FT_Offset len,
void* user_data );
void* user_data;
} AFM_ParserRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** TYPE1 CHARMAPS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef const struct T1_CMap_ClassesRec_* T1_CMap_Classes;
typedef struct T1_CMap_ClassesRec_
{
FT_CMap_Class standard;
FT_CMap_Class expert;
FT_CMap_Class custom;
FT_CMap_Class unicode;
} T1_CMap_ClassesRec;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PSAux Module Interface *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
typedef struct PSAux_ServiceRec_
{
/* don't use `PS_Table_Funcs' and friends to avoid compiler warnings */
const PS_Table_FuncsRec* ps_table_funcs;
const PS_Parser_FuncsRec* ps_parser_funcs;
const T1_Builder_FuncsRec* t1_builder_funcs;
const T1_Decoder_FuncsRec* t1_decoder_funcs;
void
(*t1_decrypt)( FT_Byte* buffer,
FT_Offset length,
FT_UShort seed );
FT_UInt32
(*cff_random)( FT_UInt32 r );
void
(*ps_decoder_init)( PS_Decoder* ps_decoder,
void* decoder,
FT_Bool is_t1 );
void
(*t1_make_subfont)( FT_Face face,
PS_Private priv,
CFF_SubFont subfont );
T1_CMap_Classes t1_cmap_classes;
/* fields after this comment line were added after version 2.1.10 */
const AFM_Parser_FuncsRec* afm_parser_funcs;
const CFF_Decoder_FuncsRec* cff_decoder_funcs;
} PSAux_ServiceRec, *PSAux_Service;
/* backward compatible type definition */
typedef PSAux_ServiceRec PSAux_Interface;
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** Some convenience functions *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define IS_PS_NEWLINE( ch ) \
( (ch) == '\r' || \
(ch) == '\n' )
#define IS_PS_SPACE( ch ) \
( (ch) == ' ' || \
IS_PS_NEWLINE( ch ) || \
(ch) == '\t' || \
(ch) == '\f' || \
(ch) == '\0' )
#define IS_PS_SPECIAL( ch ) \
( (ch) == '/' || \
(ch) == '(' || (ch) == ')' || \
(ch) == '<' || (ch) == '>' || \
(ch) == '[' || (ch) == ']' || \
(ch) == '{' || (ch) == '}' || \
(ch) == '%' )
#define IS_PS_DELIM( ch ) \
( IS_PS_SPACE( ch ) || \
IS_PS_SPECIAL( ch ) )
#define IS_PS_DIGIT( ch ) \
( (ch) >= '0' && (ch) <= '9' )
#define IS_PS_XDIGIT( ch ) \
( IS_PS_DIGIT( ch ) || \
( (ch) >= 'A' && (ch) <= 'F' ) || \
( (ch) >= 'a' && (ch) <= 'f' ) )
#define IS_PS_BASE85( ch ) \
( (ch) >= '!' && (ch) <= 'u' )
#define IS_PS_TOKEN( cur, limit, token ) \
( (char)(cur)[0] == (token)[0] && \
( (cur) + sizeof ( (token) ) == (limit) || \
( (cur) + sizeof( (token) ) < (limit) && \
IS_PS_DELIM( (cur)[sizeof ( (token) ) - 1] ) ) ) && \
ft_strncmp( (char*)(cur), (token), sizeof ( (token) ) - 1 ) == 0 )
FT_END_HEADER
#endif /* PSAUX_H_ */
/* END */
|
{
"pile_set_name": "Github"
}
|
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!ENTITY addButton.label "Neue Umgebung hinzufügen">
<!ENTITY addButton.accesskey "N">
<!ENTITY preferencesButton.label "Einstellungen">
<!ENTITY removeButton.label "Löschen">
<!-- « is « however it's not defined in XML -->
<!ENTITY backLink.label "« Zurück zu Datenschutz">
<!ENTITY window.title "Neue Umgebung hinzufügen">
<!ENTITY window.width "45em">
<!ENTITY name.label "Name:">
<!ENTITY name.accesskey "N">
<!ENTITY name.placeholder "Umgebungsnamen eingeben">
<!ENTITY icon.label "Symbol:">
<!ENTITY icon.accesskey "S">
<!ENTITY color.label "Farbe:">
<!ENTITY color.accesskey "F">
<!ENTITY windowClose.key "w">
<!ENTITY button.ok.label "Fertig">
<!ENTITY button.ok.accesskey "e">
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.helloworldapp" >
<application>
<activity
android:name=".Debug" />
</application>
</manifest>
|
{
"pile_set_name": "Github"
}
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// test numeric_limits
// has_signaling_NaN
#include <limits>
#include "test_macros.h"
template <class T, bool expected>
void
test()
{
static_assert(std::numeric_limits<T>::has_signaling_NaN == expected, "has_signaling_NaN test 1");
static_assert(std::numeric_limits<const T>::has_signaling_NaN == expected, "has_signaling_NaN test 2");
static_assert(std::numeric_limits<volatile T>::has_signaling_NaN == expected, "has_signaling_NaN test 3");
static_assert(std::numeric_limits<const volatile T>::has_signaling_NaN == expected, "has_signaling_NaN test 4");
}
int main(int, char**)
{
test<bool, false>();
test<char, false>();
test<signed char, false>();
test<unsigned char, false>();
test<wchar_t, false>();
#if TEST_STD_VER > 17 && defined(__cpp_char8_t)
test<char8_t, false>();
#endif
#ifndef _LIBCPP_HAS_NO_UNICODE_CHARS
test<char16_t, false>();
test<char32_t, false>();
#endif // _LIBCPP_HAS_NO_UNICODE_CHARS
test<short, false>();
test<unsigned short, false>();
test<int, false>();
test<unsigned int, false>();
test<long, false>();
test<unsigned long, false>();
test<long long, false>();
test<unsigned long long, false>();
#ifndef _LIBCPP_HAS_NO_INT128
test<__int128_t, false>();
test<__uint128_t, false>();
#endif
test<float, true>();
test<double, true>();
test<long double, true>();
return 0;
}
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSDictionary, NSString;
@interface SVGTextSpan : NSObject
{
NSString *_text;
NSDictionary *_attributes;
struct CGRect _rect;
}
@property(retain, nonatomic) NSDictionary *attributes; // @synthesize attributes=_attributes;
@property(nonatomic) struct CGRect rect; // @synthesize rect=_rect;
@property(retain, nonatomic) NSString *text; // @synthesize text=_text;
@end
|
{
"pile_set_name": "Github"
}
|
INCLUDE_DIRECTORIES(
${BULLET_PHYSICS_SOURCE_DIR}/src
)
ADD_LIBRARY(
BulletInverseDynamicsUtils
CloneTreeCreator.cpp
CoilCreator.cpp
MultiBodyTreeCreator.cpp
btMultiBodyTreeCreator.cpp
DillCreator.cpp
MultiBodyTreeDebugGraph.cpp
invdyn_bullet_comparison.cpp
IDRandomUtil.cpp
RandomTreeCreator.cpp
SimpleTreeCreator.cpp
MultiBodyNameMap.cpp
User2InternalIndex.cpp
)
SET_TARGET_PROPERTIES(BulletInverseDynamicsUtils PROPERTIES VERSION ${BULLET_VERSION})
SET_TARGET_PROPERTIES(BulletInverseDynamicsUtils PROPERTIES SOVERSION ${BULLET_VERSION})
IF (BUILD_SHARED_LIBS)
TARGET_LINK_LIBRARIES(BulletInverseDynamicsUtils BulletInverseDynamics BulletDynamics BulletCollision Bullet3Common LinearMath)
ENDIF (BUILD_SHARED_LIBS)
IF (INSTALL_EXTRA_LIBS)
IF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
#FILES_MATCHING requires CMake 2.6
IF (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 2.5)
IF (APPLE AND BUILD_SHARED_LIBS AND FRAMEWORK)
INSTALL(TARGETS BulletInverseDynamicsUtils DESTINATION .)
ELSE (APPLE AND BUILD_SHARED_LIBS AND FRAMEWORK)
INSTALL(TARGETS BulletInverseDynamicsUtils DESTINATION lib${LIB_SUFFIX})
INSTALL(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
DESTINATION ${INCLUDE_INSTALL_DIR} FILES_MATCHING PATTERN "*.h" PATTERN
".svn" EXCLUDE PATTERN "CMakeFiles" EXCLUDE)
ENDIF (APPLE AND BUILD_SHARED_LIBS AND FRAMEWORK)
ENDIF (${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION} GREATER 2.5)
IF (APPLE AND BUILD_SHARED_LIBS AND FRAMEWORK)
SET_TARGET_PROPERTIES(BulletInverseDynamicsUtils PROPERTIES FRAMEWORK true)
SET_TARGET_PROPERTIES(BulletInverseDynamicsUtils PROPERTIES PUBLIC_HEADER "BulletInverseDynamicsUtilsCommon.h" )
ENDIF (APPLE AND BUILD_SHARED_LIBS AND FRAMEWORK)
ENDIF (NOT INTERNAL_CREATE_DISTRIBUTABLE_MSVC_PROJECTFILES)
ENDIF (INSTALL_EXTRA_LIBS)
|
{
"pile_set_name": "Github"
}
|
<?php
// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议 https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目:https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------
return [
// 不需要验证登录的控制器
'no_login_controller' => [
'login',
],
// 不需要验证登录的节点
'no_login_node' => [
'login/index',
'login/out',
],
// 不需要验证权限的控制器
'no_auth_controller' => [
'ajax',
'login',
'index',
],
// 不需要验证权限的节点
'no_auth_node' => [
'login/index',
'login/out',
],
];
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category design
* @package base_default
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
/** @var $this Mage_Oauth_Block_Customer_Token_List */
?>
<?php echo $this->getMessagesBlock()->toHtml() ?>
<div class="page-title">
<h1><?php echo $this->__('My Applications') ?></h1>
</div>
<?php if ($this->getCollection() && $this->count()): ?>
<?php echo $this->getToolbarHtml() ?>
<table class="data-table" id="my-apps-table">
<col />
<col width="100" align="right" />
<col width="110" align="right" />
<thead>
<tr>
<th><?php echo $this->__('App Name') ?></th>
<th><?php echo $this->__('Status') ?></th>
<th> </th>
</tr>
</thead>
<tbody>
<?php /** @var $item Mage_Oauth_Model_Token */ ?>
<?php foreach ($this->getCollection() as $item) : ?>
<tr>
<td><span class="app-name">
<?php echo $this->escapeHtml($item->getName()); ?></span></td>
<td><em><?php echo $this->getStatusLabel($item->getRevoked()) ?></em></td>
<td align="right">
<a href="<?php echo $this->getUpdateRevokeLink($item)?>" class="nobr"
onclick="return confirm('<?php echo $this->getChangeStatusConfirmMessage($item->getRevoked()) ?>')">
<?php echo $this->getChangeStatusLabel($item->getRevoked()) ?></a>
<span class="separator">|</span> <a href="<?php echo $this->getDeleteLink($item)?>" class="nobr"
onclick="return confirm('<?php echo $this->__('Are you sure you want to delete this application?') ?>')">
<?php echo $this->__('Delete') ?></a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">
//<![CDATA[
decorateTable('my-apps-table');
//]]>
</script>
<?php echo $this->getToolbarHtml() ?>
<?php else: ?>
<p><?php echo $this->__('You have no applications.'); ?></p>
<?php endif; ?>
|
{
"pile_set_name": "Github"
}
|
package com.x.cms.assemble.control.factory;
import com.x.base.core.project.tools.ListTools;
import com.x.cms.assemble.control.AbstractFactory;
import com.x.cms.assemble.control.Business;
import com.x.cms.core.entity.CategoryInfo;
import com.x.cms.core.entity.CategoryInfo_;
import com.x.cms.core.express.tools.CriteriaBuilderTools;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
/**
* 分类信息基础功能服务类
*
* @author O2LEE
*/
public class CategoryInfoFactory extends AbstractFactory {
public CategoryInfoFactory(Business business) throws Exception {
super(business);
}
//@MethodDescribe("获取指定Id的CategoryInfo分类信息对象")
public CategoryInfo get( String id ) throws Exception {
return this.entityManagerContainer().find( id, CategoryInfo.class );
}
//@MethodDescribe("列示全部的CategoryInfo分类信息列表")
@SuppressWarnings("unused")
public List<CategoryInfo> listAll() throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CategoryInfo> cq = cb.createQuery( CategoryInfo.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
return em.createQuery(cq).getResultList();
}
//@MethodDescribe("列示全部的CategoryInfo分类信息列表")
public List<String> listAllIds() throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
cq.select(root.get(CategoryInfo_.id));
return em.createQuery(cq).getResultList();
}
//@MethodDescribe("列示指定Id的CategoryInfo分类信息列表")
// public List<CategoryInfo> list(List<String> ids) throws Exception {
// EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
// CriteriaBuilder cb = em.getCriteriaBuilder();
// CriteriaQuery<CategoryInfo> cq = cb.createQuery( CategoryInfo.class );
// Root<CategoryInfo> root = cq.from( CategoryInfo.class );
// Predicate p = root.get( CategoryInfo_.id).in(ids);
// return em.createQuery(cq.where(p)).getResultList();
// }
//@MethodDescribe("根据应用ID列示所有的CategoryInfo分类信息列表")
public List<String> listByAppId( String appId ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
Predicate p = cb.equal(root.get( CategoryInfo_.appId ), appId );
cq.select(root.get( CategoryInfo_.id));
return em.createQuery( cq.where(p) ).setMaxResults(1000).getResultList();
}
/**
* 根据需要过滤的栏目列表和信息类型以及返回最大条目数量列示栏目信息ID列表
* @param appIds
* @param documentType
* @param maxCount
* @return
* @throws Exception
*/
public List<String> listByAppIds( List<String> appIds, String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
TypedQuery<String> query = null;
Predicate p = null;
//需要过滤的栏目ID为空
if( ListTools.isEmpty( appIds )) {
p = CriteriaBuilderTools.predicate_and(cb, null, root.get( CategoryInfo_.appId ).in( appIds ) );
}
//查询指定信息类别下的所有分类信息列表
if( StringUtils.isNotEmpty( documentType ) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
p = CriteriaBuilderTools.predicate_and(cb, null, cb.equal( root.get( CategoryInfo_.documentType ), documentType ) );
}
if( p != null ){
cq.select(root.get( CategoryInfo_.id)).where( p );
}else{
cq.select(root.get( CategoryInfo_.id));
}
return em.createQuery( cq.where(p) ).setMaxResults(maxCount).getResultList();
}
public List<CategoryInfo> listCategoryByAppId( String appId, String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CategoryInfo> cq = cb.createQuery( CategoryInfo.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
Predicate p = cb.equal(root.get( CategoryInfo_.appId ), appId );
if( StringUtils.isNotEmpty( documentType ) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType ), documentType ));
}
return em.createQuery( cq.where(p) ).setMaxResults(maxCount).getResultList();
}
//@MethodDescribe("根据应用ID列示所有的CategoryInfo分类信息数量")
public Long countByAppId( String appId, String documentType ) throws Exception {
EntityManager em = this.entityManagerContainer().get(CategoryInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
Predicate p = cb.equal( root.get(CategoryInfo_.appId), appId );
if( StringUtils.isNotEmpty( documentType ) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType ), documentType ));
}
cq.select(cb.count(root));
return em.createQuery(cq.where(p)).getSingleResult();
}
//@MethodDescribe("根据分类ID列示所有下级CategoryInfo分类信息列表")
public List<String> listByParentId( String categoryId ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery( String.class );
Root<CategoryInfo> root = cq.from( CategoryInfo.class );
Predicate p = cb.equal(root.get( CategoryInfo_.parentId ), categoryId );
cq.select(root.get( CategoryInfo_.id));
return em.createQuery( cq.where(p) ).setMaxResults(100).getResultList();
}
//@MethodDescribe("对分类信息进行模糊查询,并且返回信息列表.")
public List<String> listLike(String keyStr, String documentType ) throws Exception {
String str = keyStr.replaceAll("_", "\\\\_");
str = str.replaceAll("%", "\\\\%");
str = str.toLowerCase();
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from( CategoryInfo.class);
Predicate p = cb.like(root.get( CategoryInfo_.categoryName ), "%" + str + "%", '\\');
p = cb.or(p, cb.like(root.get( CategoryInfo_.categoryAlias ), str + "%", '\\'));
if( StringUtils.isNotEmpty( documentType ) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType ), documentType ));
}
cq.select(root.get( CategoryInfo_.id));
return em.createQuery(cq.where(p)).setMaxResults(200).getResultList();
}
public List<String> listMyCategoryWithAppId( List<String> myCategoryIds, String documentType, String appId ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
cq.select(root.get(CategoryInfo_.id));
Predicate p = cb.equal( root.get( CategoryInfo_.appId ), appId );
if( myCategoryIds != null && !myCategoryIds.isEmpty() ){
p = cb.and( p, root.get( CategoryInfo_.id ).in( myCategoryIds ) );
}
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType) && !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
return em.createQuery(cq.where( p )).getResultList();
}
public List<String> listByAlias( List<String> categoryAlias) throws Exception {
if(ListTools.isEmpty( categoryAlias )) {
return null;
}
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
cq.select(root.get(CategoryInfo_.id));
Predicate p = root.get( CategoryInfo_.categoryAlias ).in( categoryAlias );
return em.createQuery(cq.where( p )).getResultList();
}
public List<CategoryInfo> listByAliases(List<String> categoryAlias) throws Exception {
if(ListTools.isEmpty( categoryAlias )) {
return null;
}
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CategoryInfo> cq = cb.createQuery(CategoryInfo.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
Predicate p = root.get( CategoryInfo_.categoryAlias ).in( categoryAlias );
return em.createQuery(cq.where( p )).getResultList();
}
/**
* 根据权限查询用户可以发布文档的分类ID列表(根据权限, 不检测allPeopleView和allPeoplePublish)
* 可管理的分类也属于可发布的分类
* @param personName
* @param unitNames
* @param groupNames
* @param inAppInfoIds - 需要限定的栏目ID列表
* @param inCategoryIds - 栏目ID的最大范围
* @param excludCategoryIds - 需要排除的栏目ID
* @return
* @throws Exception
*/
public List<String> listPublishableCategoryInfoIdsWithPermission(String personName, List<String> unitNames,
List<String> groupNames, List<String> inAppInfoIds, List<String> inCategoryIds,
List<String> excludCategoryIds, String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get(CategoryInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
Predicate p = null;
Predicate p_filter = null;
//限定栏目范围
if( ListTools.isNotEmpty( inAppInfoIds )) {
p_filter = root.get( CategoryInfo_.appId ).in( inAppInfoIds );
}
//限定范围
if( ListTools.isNotEmpty( inCategoryIds )) {
if( p_filter == null ) {
p_filter = root.get( CategoryInfo_.id ).in( inCategoryIds );
}else {
p_filter = cb.and( p_filter, root.get( CategoryInfo_.id ).in( inCategoryIds ));
}
}
//排除指定的ID列表
if( ListTools.isNotEmpty( excludCategoryIds )) {
if( p_filter == null ) {
p_filter = cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds ));
}else {
p_filter = cb.and( p_filter, cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds )));
}
}
Predicate p_permission = null;
if( StringUtils.isNotEmpty( personName )) {
//可以管理的栏目,肯定可以发布信息
p_permission = cb.isMember( personName, root.get( CategoryInfo_.manageablePersonList ));
p_permission = cb.or( p_permission, cb.isMember( personName, root.get( CategoryInfo_.publishablePersonList )));
}
if( ListTools.isNotEmpty( unitNames )) {
if( p_permission == null ) {
p_permission = root.get( CategoryInfo_.publishableUnitList).in(unitNames);
}else {
p_permission = cb.or( p_permission, root.get( CategoryInfo_.publishableUnitList).in(unitNames));
}
}
if( ListTools.isNotEmpty( groupNames )) {
if( p_permission == null ) {
p_permission = root.get( CategoryInfo_.publishableGroupList).in(groupNames);
}else {
p_permission = cb.or( p_permission, root.get( CategoryInfo_.publishableGroupList).in(groupNames));
}
}
//使用新的条件将两个条件组合起来
if( p_filter != null ) {
p = p_filter;
}
if( p != null ) {
if( p_permission != null ) {
p = cb.and(p, p_permission);
}
}else {
if( p_permission != null ) {
p = p_permission;
}
}
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
cq.select(root.get( CategoryInfo_.id ));
return em.createQuery( cq.where( p ) ).setMaxResults(maxCount).getResultList();
}
/**
* 根据权限查询用户可以访问文档的分类ID列表(根据权限, 不检测allPeopleView和allPeoplePublish)
* 可发布、可管理的分类也属于可见分类
* @param personName
* @param unitNames
* @param groupNames
* @param inAppInfoIds - 需要限定的栏目ID列表
* @param inCategoryIds - 栏目ID的最大范围
* @param excludCategoryIds - 需要排除的栏目ID
* @return
* @throws Exception
*/
public List<String> listViewableCategoryInfoIdsWithPermission(String personName, List<String> unitNames, List<String> groupNames,
List<String> inAppInfoIds, List<String> inCategoryIds, List<String> excludCategoryIds,
String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get(CategoryInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
Predicate p = null;
Predicate p_filter = null;
//限定栏目范围
if( ListTools.isNotEmpty( inAppInfoIds )) {
p_filter = root.get( CategoryInfo_.appId ).in( inAppInfoIds );
}
//限定范围
if( ListTools.isNotEmpty( inCategoryIds )) {
if( p_filter == null ) {
p_filter = root.get( CategoryInfo_.id ).in( inCategoryIds );
}else {
p_filter = cb.and( p_filter, root.get( CategoryInfo_.id ).in( inCategoryIds ));
}
}
//排除指定的ID列表
if( ListTools.isNotEmpty( excludCategoryIds )) {
if( p_filter == null ) {
p_filter = cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds ));
}else {
p_filter = cb.and( p_filter, cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds )));
}
}
Predicate p_permission = null;
if( StringUtils.isNotEmpty( personName )) {
//可以管理的栏目,肯定可以发布信息
p_permission = cb.isMember( personName, root.get( CategoryInfo_.manageablePersonList ));
p_permission = cb.or( p_permission, cb.isMember( personName, root.get( CategoryInfo_.publishablePersonList )));
}
if( ListTools.isNotEmpty( unitNames )) {
if( p_permission == null ){
p_permission = root.get( CategoryInfo_.publishableUnitList).in(unitNames);
p_permission = cb.or( p_permission, root.get( CategoryInfo_.viewableUnitList).in(unitNames));
}else {
p_permission = cb.or( p_permission, root.get( CategoryInfo_.publishableUnitList).in(unitNames));
p_permission = cb.or( p_permission, root.get( CategoryInfo_.viewableUnitList).in(unitNames));
}
}
if( ListTools.isNotEmpty( groupNames )) {
if( p_permission == null ){
p_permission = root.get( CategoryInfo_.publishableGroupList).in(groupNames);
p_permission = cb.or( p_permission, root.get( CategoryInfo_.viewableGroupList).in(groupNames));
}else {
p_permission = cb.or( p_permission, root.get( CategoryInfo_.publishableGroupList).in(groupNames));
p_permission = cb.or( p_permission, root.get( CategoryInfo_.viewableGroupList).in(groupNames));
}
}
//使用新的条件将两个条件组合起来
if( p_filter != null ) {
p = p_filter;
}
if( p != null ) {
if( p_permission != null ) {
p = cb.and(p, p_permission);
}
}else {
if( p_permission != null ) {
p = p_permission;
}
}
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType) && !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
cq.select(root.get( CategoryInfo_.id ));
return em.createQuery( cq.where( p ) ).setMaxResults(maxCount).getResultList();
}
/**
* 查询所有用户都可以发布的分类ID列表
* @param inAppInfoIds
* @param inCategoryIds
* @param excludCategoryIds
* @return
* @throws Exception
*/
public List<String> listAllPeoplePublishableCategoryInfoIds(List<String> inAppInfoIds, List<String> inCategoryIds,
List<String> excludCategoryIds, String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
cq.select(root.get(CategoryInfo_.id));
Predicate p = cb.isTrue( root.get( CategoryInfo_.allPeoplePublish ) );
if( ListTools.isNotEmpty( inAppInfoIds )) {
p = cb.and( p, root.get( CategoryInfo_.appId ).in( inAppInfoIds ) );
}
if( ListTools.isNotEmpty( inCategoryIds )) {
p = cb.and( p, root.get( CategoryInfo_.id ).in( inCategoryIds ));
}
if( ListTools.isNotEmpty( excludCategoryIds )) {
p = cb.and( p, cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds )));
}
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType) && !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
return em.createQuery(cq.where( p )).setMaxResults(maxCount).getResultList();
}
/**
* 查询所有用户都可以发布的分类ID列表(检测allPeopleView和allPeoplePublish)
* @param inAppInfoIds
* @param inCategoryIds
* @param excludCategoryIds
* @return
* @throws Exception
*/
public List<String> listAllPeopleViewableCategoryInfoIds(List<String> inAppInfoIds, List<String> inCategoryIds, List<String> excludCategoryIds,
String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get( CategoryInfo.class );
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
cq.select(root.get(CategoryInfo_.id));
Predicate p_all = cb.isTrue( root.get( CategoryInfo_.allPeopleView ) );
p_all = cb.or( p_all, cb.isTrue( root.get( CategoryInfo_.allPeoplePublish )));
Predicate p = root.get( CategoryInfo_.id ).isNotNull();
if( ListTools.isNotEmpty( inAppInfoIds )) {
p = cb.and( p, root.get( CategoryInfo_.appId ).in( inAppInfoIds ) );
}
if( ListTools.isNotEmpty( inCategoryIds )) {
p = cb.and( p, root.get( CategoryInfo_.id ).in( inCategoryIds ));
}
if( ListTools.isNotEmpty( excludCategoryIds )) {
p = cb.and( p, cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds )));
}
p = cb.and( p, p_all );
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType) && !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
return em.createQuery(cq.where( p )).setMaxResults(maxCount).getResultList();
}
/**
* 查询指定用户,组织,群组可以管理的分类列表
* @param personName
* @param unitNames
* @param groupNames
* @param inAppInfoIds
* @return
* @throws Exception
*/
public List<String> listManageableCategoryIds( String personName, List<String> unitNames, List<String> groupNames, List<String> inAppInfoIds,
String documentType, Integer maxCount ) throws Exception {
EntityManager em = this.entityManagerContainer().get(CategoryInfo.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<CategoryInfo> root = cq.from(CategoryInfo.class);
Predicate p = cb.isMember( personName, root.get( CategoryInfo_.manageablePersonList ));
if( ListTools.isNotEmpty( inAppInfoIds )) {
p = cb.and( p, root.get( CategoryInfo_.appId ).in( inAppInfoIds ) );
}
if( ListTools.isNotEmpty( unitNames )) {
p = cb.or( p, root.get( CategoryInfo_.manageableUnitList).in(unitNames));
}
if( ListTools.isNotEmpty( groupNames )) {
p = cb.or( p, root.get( CategoryInfo_.manageableGroupList).in(groupNames));
}
cq.select(root.get( CategoryInfo_.id ));
if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType) && !"all".equalsIgnoreCase(documentType)) {
p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
}
return em.createQuery( cq.where( p ) ).setMaxResults(maxCount).getResultList();
}
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2007. 2012 Spring IDE Developers
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spring IDE Developers - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.core;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
/**
* Base class for handling save and restore of simple boolean preferences.
* Depending if a {@link IProject} is passed in {@link #isEnabled(IProject)} and
* {@link #setEnabled(boolean,IProject)} the preference is stored in the
* project preferences or under global workspace scope.
* @author Christian Dupuis
* @author Tomasz Zarna
* @since 2.0.2
*/
public abstract class PersistablePreferenceObjectSupport {
private boolean isEnabledByDefault = true;
/**
* Returns the preference id that should be used for storing the value
* @return the preference key
*/
protected abstract String getPreferenceId();
protected boolean hasProjectSpecificOptions(IProject project) {
return SpringCorePreferences.getProjectPreferences(project).getBoolean(
SpringCore.PROJECT_PROPERTY_ID, false);
}
/**
* Checks if the current preference identified by a call to
* {@link #getPreferenceId()} is enabled in the scope of the given project.
* <p>
* If the project is <code>null</code> the check is executed against the
* global workspace settings.
* @return true if preference is enabled for the given project
*/
public boolean isEnabled(IProject project) {
if (project != null && hasProjectSpecificOptions(project)) {
return SpringCorePreferences.getProjectPreferences(project)
.getBoolean(getPreferenceId(), this.isEnabledByDefault);
}
else {
return SpringCore.getDefault().getPluginPreferences().getBoolean(
getPreferenceIdForPluginPreference());
}
}
/**
* Checks if the current preference is enabled by default.
*
* @return <code>true</code> if the preference is enabled by default, <code>false</code> otherwise
*
* @since 3.2.0
*/
public boolean isEnabledByDefault() {
return isEnabledByDefault;
}
/**
* Sets this preferences to the value of <code>isEnabled</code>.
* <p>
* If the project is <code>null</code> the preference will be stored in
* the global workspace settings.
* @param isEnabled
* @param project
*/
public void setEnabled(boolean isEnabled, IProject project) {
if (project != null) {
SpringCorePreferences.getProjectPreferences(project).putBoolean(
getPreferenceId(), isEnabled);
}
else {
SpringCore.getDefault().getPluginPreferences().setValue(
getPreferenceIdForPluginPreference(), isEnabled);
}
onEnablementChanged(isEnabled, project);
}
private String getPreferenceIdForPluginPreference() {
return SpringCore.PLUGIN_ID + "." + getPreferenceId();
}
/**
* Set the default value if no value has been stored
* @param isEnabledByDefault
*/
protected void setEnabledByDefault(boolean isEnabledByDefault) {
this.isEnabledByDefault = isEnabledByDefault;
SpringCore.getDefault().getPluginPreferences().setDefault(
getPreferenceIdForPluginPreference(), this.isEnabledByDefault);
}
/**
* Called after the value has been changed by a call to
* {@link #setEnabled(boolean, IProject)}.
* <p>
* This default implementation is empty but can be overridden by subclasses
* to executed some kind of lifecycle management (e.g. cleanup of
* {@link IMarker}).
* @param isEnabled
* @param project
*/
protected void onEnablementChanged(boolean isEnabled, IProject project) {
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// Unit test for include/gtest/gtest_prod.h.
#include "gtest/gtest.h"
#include "test/production.h"
// Tests that private members can be accessed from a TEST declared as
// a friend of the class.
TEST(PrivateCodeTest, CanAccessPrivateMembers) {
PrivateCode a;
EXPECT_EQ(0, a.x_);
a.set_x(1);
EXPECT_EQ(1, a.x_);
}
typedef testing::Test PrivateCodeFixtureTest;
// Tests that private members can be accessed from a TEST_F declared
// as a friend of the class.
TEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) {
PrivateCode a;
EXPECT_EQ(0, a.x_);
a.set_x(2);
EXPECT_EQ(2, a.x_);
}
|
{
"pile_set_name": "Github"
}
|
{
"id": "squat-toilet",
"name": "Squat Toilet",
"games": {
"nh": {
"sellPrice": {
"currency": "bells",
"value": 375
},
"buyPrices": [
{
"currency": "bells",
"value": 1500
}
]
}
},
"category": "Furniture"
}
|
{
"pile_set_name": "Github"
}
|
---
title: "Create and run unit tests for a Store app"
ms.date: 11/15/2016
ms.prod: "visual-studio-dev14"
ms.technology: vs-ide-test
ms.topic: conceptual
helpviewer_keywords:
- "unit tests"
ms.assetid: d3de7b31-0262-4373-ba84-e74eda7651e4
caps.latest.revision: 28
author: "alexhomer1"
ms.author: jillfra
manager: jillfra
---
# Create and run unit tests for a Store app in Visual Studio
[!INCLUDE[vs2017banner](../includes/vs2017banner.md)]
The Visual Studio 2012 Express for Windows 8 unit test tools are designed to support developers and teams who incorporate unit testing in their software development practices. Unit tests give developers and testers an efficient, maintainable way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects.
> [!NOTE]
> The topics in this section describe the functionality of Visual Studio 2012 Express for Windows 8. Visual Studio Ultimate, VS Premium, and VS Professional provide additional features for unit testing.
>
> - In VS Ultimate, VS Premium, and VS Professional you can use any third-party or open source unit test framework that has created an add-on adapter for the Microsoft Test Explorer. You can also analyze and display code coverage information for your tests with VS Ultimate and VS Premium.
> - In VS Ultimate, you can run your tests after every build. You can also use Microsoft Fakes, an isolation framework for managed code to focus your tests on your own code by substituting test code for system and third-party functionality.
> - **JavaScript**. JavaScript unit testing is not available from the IDE of Visual Studio Express for Windows 8. In Visual Studio Professional, Premium and Ultimate, JavaScript unit test frameworks are available as extensions in the Visual Studio Gallery. You can also test JavaScript code by using one of the stand-alone third-party or open source JavaScript unit test frameworks.
>
> For more information, see [Unit Test Your Code](../test/unit-test-your-code.md) in the MSDN Library.
## In this section
[Unit test C# code](../test/unit-testing-visual-csharp-code-in-a-store-app.md)
[Unit testing a C++ DLL](../test/unit-testing-a-visual-cpp-dll-for-store-apps.md)
[Run unit tests in Test Explorer](../test/run-unit-tests-for-store-apps-in-visual-studio.md)
|
{
"pile_set_name": "Github"
}
|
local T, C, L, _ = unpack(select(2, ...))
if T.classic or C.skins.blizzard_frames ~= true then return end
----------------------------------------------------------------------------------------
-- ScrappingMachine skin
----------------------------------------------------------------------------------------
local function LoadSkin()
ScrappingMachineFrame:StripTextures()
ScrappingMachineFrame:SetTemplate("Transparent")
local ItemSlots = ScrappingMachineFrame.ItemSlots
ItemSlots:StripTextures()
for button in pairs(ItemSlots.scrapButtons.activeObjects) do
if not button.styled then
button:SetHighlightTexture("")
button.Icon:SkinIcon()
button.IconBorder:SetAlpha(0)
hooksecurefunc(button.IconBorder, "SetVertexColor", function(_, r, g, b) button.backdrop:SetBackdropBorderColor(r, g, b) end)
hooksecurefunc(button.IconBorder, "Hide", function() button.backdrop:SetBackdropBorderColor(unpack(C.media.border_color)) end)
button.styled = true
end
end
ScrappingMachineFrame.ScrapButton:SkinButton()
T.SkinCloseButton(ScrappingMachineFrameCloseButton)
end
T.SkinFuncs["Blizzard_ScrappingMachineUI"] = LoadSkin
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.route53.model;
import javax.annotation.Generated;
/**
* <p>
* The health check you're attempting to create already exists. Amazon Route 53 returns this error when you submit a
* request that has the following values:
* </p>
* <ul>
* <li>
* <p>
* The same value for <code>CallerReference</code> as an existing health check, and one or more values that differ from
* the existing health check that has the same caller reference.
* </p>
* </li>
* <li>
* <p>
* The same value for <code>CallerReference</code> as a health check that you created and later deleted, regardless of
* the other settings in the request.
* </p>
* </li>
* </ul>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HealthCheckAlreadyExistsException extends com.amazonaws.services.route53.model.AmazonRoute53Exception {
private static final long serialVersionUID = 1L;
/**
* Constructs a new HealthCheckAlreadyExistsException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public HealthCheckAlreadyExistsException(String message) {
super(message);
}
}
|
{
"pile_set_name": "Github"
}
|
package org.apereo.cas.configuration.model.support.okta;
import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.apereo.cas.configuration.support.RequiresModule;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import java.io.Serializable;
/**
* This is {@link OktaAuthenticationProperties}.
*
* @author Misagh Moayyed
* @since 6.2.0
*/
@RequiresModule(name = "cas-server-support-okta-authentication", automated = true)
@Getter
@Setter
@Accessors(chain = true)
public class OktaAuthenticationProperties implements Serializable {
private static final long serialVersionUID = -13245764438426360L;
/**
* The name of the authentication handler.
*/
private String name;
/**
* The order of this authentication handler in the chain.
*/
private int order = Integer.MAX_VALUE;
/**
* Password encoding properties.
*/
@NestedConfigurationProperty
private PasswordEncoderProperties passwordEncoder = new PasswordEncoderProperties();
/**
* Principal transformation properties.
*/
@NestedConfigurationProperty
private PrincipalTransformationProperties principalTransformation = new PrincipalTransformationProperties();
/**
* Send requests via a proxy; define the hostname.
*/
private String proxyHost;
/**
* Send requests via a proxy; define the proxy port.
* Negative/zero values should deactivate the proxy configuration
* for the http client.
*/
private int proxyPort;
/**
* Send requests via a proxy; define the proxy username.
*/
private String proxyUsername;
/**
* Send requests via a proxy; define the proxy password.
*/
private String proxyPassword;
/**
* Connection timeout in milliseconds.
*/
private int connectionTimeout = 5000;
/**
* A number of authentication handlers are allowed to determine whether they can operate on the provided credential
* and as such lend themselves to be tried and tested during the authentication handler selection phase.
* The credential criteria may be one of the following options:<ul>
* <li>1) A regular expression pattern that is tested against the credential identifier.</li>
* <li>2) A fully qualified class name of your own design that implements {@code Predicate<Credential>}.</li>
* <li>3) Path to an external Groovy script that implements the same interface.</li>
* </ul>
*/
private String credentialCriteria;
/**
* Okta domain.
*/
@RequiredProperty
private String organizationUrl;
}
|
{
"pile_set_name": "Github"
}
|
## Unix tee-like functionality via a Python class
Originally published: 2017-03-31 14:30:28
Last updated: 2017-03-31 14:30:30
Author: Vasudev Ram
The Unix tee commmand, when used in a command pipeline, allows you to capture the output of the preceding command to a file or files, while still sending it on to standard output (stdout) for further processing via other commands in a pipeline, or to print it, etc.
This recipe shows how to implement simple tee-like functionality via a Python class. I do not aim to exactly replicate the functionality of the Unix tee, only something similar.
More details and sample output here:
https://jugad2.blogspot.in/2017/03/a-python-class-like-unix-tee-command.html
|
{
"pile_set_name": "Github"
}
|
/**
* @name Foo
* @class
*/
/**#@+
* @memberOf Foo#
* @field
*/
/**
* @name bar
* @type Object[]
*/
/**#@-*/
/**
* @name Foo2
* @class
*/
/**#@+
* @memberOf Foo2#
* @field
*/
/**
* @name bar
* @type Object[]
*/
/**#@-*/
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
#include <ThreeSliceAttributes.h>
#include <DataNode.h>
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Init utility for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
void ThreeSliceAttributes::Init()
{
x = 0;
y = 0;
z = 0;
interactive = true;
ThreeSliceAttributes::SelectAll();
}
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Copy utility for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
void ThreeSliceAttributes::Copy(const ThreeSliceAttributes &obj)
{
x = obj.x;
y = obj.y;
z = obj.z;
interactive = obj.interactive;
ThreeSliceAttributes::SelectAll();
}
// Type map format string
const char *ThreeSliceAttributes::TypeMapFormatString = THREESLICEATTRIBUTES_TMFS;
const AttributeGroup::private_tmfs_t ThreeSliceAttributes::TmfsStruct = {THREESLICEATTRIBUTES_TMFS};
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Default constructor for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes::ThreeSliceAttributes() :
AttributeSubject(ThreeSliceAttributes::TypeMapFormatString)
{
ThreeSliceAttributes::Init();
}
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Constructor for the derived classes of ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes::ThreeSliceAttributes(private_tmfs_t tmfs) :
AttributeSubject(tmfs.tmfs)
{
ThreeSliceAttributes::Init();
}
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Copy constructor for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes::ThreeSliceAttributes(const ThreeSliceAttributes &obj) :
AttributeSubject(ThreeSliceAttributes::TypeMapFormatString)
{
ThreeSliceAttributes::Copy(obj);
}
// ****************************************************************************
// Method: ThreeSliceAttributes::ThreeSliceAttributes
//
// Purpose:
// Copy constructor for derived classes of the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes::ThreeSliceAttributes(const ThreeSliceAttributes &obj, private_tmfs_t tmfs) :
AttributeSubject(tmfs.tmfs)
{
ThreeSliceAttributes::Copy(obj);
}
// ****************************************************************************
// Method: ThreeSliceAttributes::~ThreeSliceAttributes
//
// Purpose:
// Destructor for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes::~ThreeSliceAttributes()
{
// nothing here
}
// ****************************************************************************
// Method: ThreeSliceAttributes::operator =
//
// Purpose:
// Assignment operator for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
ThreeSliceAttributes&
ThreeSliceAttributes::operator = (const ThreeSliceAttributes &obj)
{
if (this == &obj) return *this;
ThreeSliceAttributes::Copy(obj);
return *this;
}
// ****************************************************************************
// Method: ThreeSliceAttributes::operator ==
//
// Purpose:
// Comparison operator == for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
bool
ThreeSliceAttributes::operator == (const ThreeSliceAttributes &obj) const
{
// Create the return value
return ((x == obj.x) &&
(y == obj.y) &&
(z == obj.z) &&
(interactive == obj.interactive));
}
// ****************************************************************************
// Method: ThreeSliceAttributes::operator !=
//
// Purpose:
// Comparison operator != for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
bool
ThreeSliceAttributes::operator != (const ThreeSliceAttributes &obj) const
{
return !(this->operator == (obj));
}
// ****************************************************************************
// Method: ThreeSliceAttributes::TypeName
//
// Purpose:
// Type name method for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
const std::string
ThreeSliceAttributes::TypeName() const
{
return "ThreeSliceAttributes";
}
// ****************************************************************************
// Method: ThreeSliceAttributes::CopyAttributes
//
// Purpose:
// CopyAttributes method for the ThreeSliceAttributes class.
//
// Programmer: Akira Haddox
// Creation: Mon Jun 9 13:18:30 PST 2003
//
// Modifications:
//
// ****************************************************************************
bool
ThreeSliceAttributes::CopyAttributes(const AttributeGroup *atts)
{
if(atts->TypeName() == "PointAttributes")
{
if (interactive)
{
const PointAttributes *tmp = (const PointAttributes *)atts;
const double *xyz = tmp->GetPoint();
SetX(xyz[0]);
SetY(xyz[1]);
SetZ(xyz[2]);
return true;
}
}
if(TypeName() != atts->TypeName())
return false;
// Call assignment operator.
const ThreeSliceAttributes *tmp = (const ThreeSliceAttributes *)atts;
*this = *tmp;
return true;
}
// ****************************************************************************
// Method: ThreeSliceAttributes::CreateCompatible
//
// Purpose:
// CreateCompatible method for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: Akira Haddox
// Creation: Mon Jun 9 13:18:30 PST 2003
//
// Modifications:
// Akira Haddox, Wed Jul 2 11:11:26 PDT 2003
// Added PointAttributes.
//
// ****************************************************************************
AttributeSubject *
ThreeSliceAttributes::CreateCompatible(const std::string &tname) const
{
AttributeSubject *retval = 0;
if(TypeName() == tname)
retval = new ThreeSliceAttributes(*this);
if(tname == "PointAttributes" && interactive)
{
PointAttributes *p = new PointAttributes;
double pt[3];
pt[0] = GetX();
pt[1] = GetY();
pt[2] = GetZ();
p->SetPoint(pt);
retval = p;
}
return retval;
}
// ****************************************************************************
// Method: ThreeSliceAttributes::NewInstance
//
// Purpose:
// NewInstance method for the ThreeSliceAttributes class.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
AttributeSubject *
ThreeSliceAttributes::NewInstance(bool copy) const
{
AttributeSubject *retval = 0;
if(copy)
retval = new ThreeSliceAttributes(*this);
else
retval = new ThreeSliceAttributes;
return retval;
}
// ****************************************************************************
// Method: ThreeSliceAttributes::SelectAll
//
// Purpose:
// Selects all attributes.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
void
ThreeSliceAttributes::SelectAll()
{
Select(ID_x, (void *)&x);
Select(ID_y, (void *)&y);
Select(ID_z, (void *)&z);
Select(ID_interactive, (void *)&interactive);
}
///////////////////////////////////////////////////////////////////////////////
// Persistence methods
///////////////////////////////////////////////////////////////////////////////
// ****************************************************************************
// Method: ThreeSliceAttributes::CreateNode
//
// Purpose:
// This method creates a DataNode representation of the object so it can be saved to a config file.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
bool
ThreeSliceAttributes::CreateNode(DataNode *parentNode, bool completeSave, bool forceAdd)
{
if(parentNode == 0)
return false;
ThreeSliceAttributes defaultObject;
bool addToParent = false;
// Create a node for ThreeSliceAttributes.
DataNode *node = new DataNode("ThreeSliceAttributes");
if(completeSave || !FieldsEqual(ID_x, &defaultObject))
{
addToParent = true;
node->AddNode(new DataNode("x", x));
}
if(completeSave || !FieldsEqual(ID_y, &defaultObject))
{
addToParent = true;
node->AddNode(new DataNode("y", y));
}
if(completeSave || !FieldsEqual(ID_z, &defaultObject))
{
addToParent = true;
node->AddNode(new DataNode("z", z));
}
if(completeSave || !FieldsEqual(ID_interactive, &defaultObject))
{
addToParent = true;
node->AddNode(new DataNode("interactive", interactive));
}
// Add the node to the parent node.
if(addToParent || forceAdd)
parentNode->AddNode(node);
else
delete node;
return (addToParent || forceAdd);
}
// ****************************************************************************
// Method: ThreeSliceAttributes::SetFromNode
//
// Purpose:
// This method sets attributes in this object from values in a DataNode representation of the object.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
void
ThreeSliceAttributes::SetFromNode(DataNode *parentNode)
{
if(parentNode == 0)
return;
DataNode *searchNode = parentNode->GetNode("ThreeSliceAttributes");
if(searchNode == 0)
return;
DataNode *node;
if((node = searchNode->GetNode("x")) != 0)
SetX(node->AsDouble());
if((node = searchNode->GetNode("y")) != 0)
SetY(node->AsDouble());
if((node = searchNode->GetNode("z")) != 0)
SetZ(node->AsDouble());
if((node = searchNode->GetNode("interactive")) != 0)
SetInteractive(node->AsBool());
}
///////////////////////////////////////////////////////////////////////////////
// Set property methods
///////////////////////////////////////////////////////////////////////////////
void
ThreeSliceAttributes::SetX(double x_)
{
x = x_;
Select(ID_x, (void *)&x);
}
void
ThreeSliceAttributes::SetY(double y_)
{
y = y_;
Select(ID_y, (void *)&y);
}
void
ThreeSliceAttributes::SetZ(double z_)
{
z = z_;
Select(ID_z, (void *)&z);
}
void
ThreeSliceAttributes::SetInteractive(bool interactive_)
{
interactive = interactive_;
Select(ID_interactive, (void *)&interactive);
}
///////////////////////////////////////////////////////////////////////////////
// Get property methods
///////////////////////////////////////////////////////////////////////////////
double
ThreeSliceAttributes::GetX() const
{
return x;
}
double
ThreeSliceAttributes::GetY() const
{
return y;
}
double
ThreeSliceAttributes::GetZ() const
{
return z;
}
bool
ThreeSliceAttributes::GetInteractive() const
{
return interactive;
}
///////////////////////////////////////////////////////////////////////////////
// Keyframing methods
///////////////////////////////////////////////////////////////////////////////
// ****************************************************************************
// Method: ThreeSliceAttributes::GetFieldName
//
// Purpose:
// This method returns the name of a field given its index.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
std::string
ThreeSliceAttributes::GetFieldName(int index) const
{
switch (index)
{
case ID_x: return "x";
case ID_y: return "y";
case ID_z: return "z";
case ID_interactive: return "interactive";
default: return "invalid index";
}
}
// ****************************************************************************
// Method: ThreeSliceAttributes::GetFieldType
//
// Purpose:
// This method returns the type of a field given its index.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
AttributeGroup::FieldType
ThreeSliceAttributes::GetFieldType(int index) const
{
switch (index)
{
case ID_x: return FieldType_double;
case ID_y: return FieldType_double;
case ID_z: return FieldType_double;
case ID_interactive: return FieldType_bool;
default: return FieldType_unknown;
}
}
// ****************************************************************************
// Method: ThreeSliceAttributes::GetFieldTypeName
//
// Purpose:
// This method returns the name of a field type given its index.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
std::string
ThreeSliceAttributes::GetFieldTypeName(int index) const
{
switch (index)
{
case ID_x: return "double";
case ID_y: return "double";
case ID_z: return "double";
case ID_interactive: return "bool";
default: return "invalid index";
}
}
// ****************************************************************************
// Method: ThreeSliceAttributes::FieldsEqual
//
// Purpose:
// This method compares two fields and return true if they are equal.
//
// Note: Autogenerated by xml2atts.
//
// Programmer: xml2atts
// Creation: omitted
//
// Modifications:
//
// ****************************************************************************
bool
ThreeSliceAttributes::FieldsEqual(int index_, const AttributeGroup *rhs) const
{
const ThreeSliceAttributes &obj = *((const ThreeSliceAttributes*)rhs);
bool retval = false;
switch (index_)
{
case ID_x:
{ // new scope
retval = (x == obj.x);
}
break;
case ID_y:
{ // new scope
retval = (y == obj.y);
}
break;
case ID_z:
{ // new scope
retval = (z == obj.z);
}
break;
case ID_interactive:
{ // new scope
retval = (interactive == obj.interactive);
}
break;
default: retval = false;
}
return retval;
}
///////////////////////////////////////////////////////////////////////////////
// User-defined methods.
///////////////////////////////////////////////////////////////////////////////
|
{
"pile_set_name": "Github"
}
|
fileFormatVersion: 2
guid: 493e5e35d9e265f499004a07237f579c
timeCreated: 1504815833
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
|
{
"pile_set_name": "Github"
}
|
// @flow
const {assertProjectDir} = require('../utils/assert-project-dir.js');
const {isProjectInstalled} = require('../utils/is-project-installed.js');
const {install} = require('./install.js');
const {getPassThroughArgs} = require('../utils/parse-argv.js');
const {executeProjectCommand} = require('../utils/execute-project-command.js');
/*::
import type {Stdio} from '../utils/node-helpers.js';
export type TestArgs = {
root: string,
cwd: string,
args: Array<string>,
stdio?: Stdio,
}
export type Test = (TestArgs) => Promise<void>
*/
const test /*: Test */ = async ({root, cwd, args, stdio = 'inherit'}) => {
await assertProjectDir({dir: cwd});
if (!(await isProjectInstalled({root, cwd}))) {
await install({root, cwd, conservative: true});
}
const params = getPassThroughArgs(args);
await executeProjectCommand({
root,
cwd,
command: 'test',
args: params,
stdio,
});
};
module.exports = {test};
|
{
"pile_set_name": "Github"
}
|
/* Frontend part of the Linux driver for the Afatech 9005
* USB1.1 DVB-T receiver.
*
* Copyright (C) 2007 Luca Olivetti (luca@ventoso.org)
*
* Thanks to Afatech who kindly provided information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* see Documentation/dvb/README.dvb-usb for more information
*/
#include "af9005.h"
#include "af9005-script.h"
#include "mt2060.h"
#include "qt1010.h"
#include <asm/div64.h>
struct af9005_fe_state {
struct dvb_usb_device *d;
enum fe_status stat;
/* retraining parameters */
u32 original_fcw;
u16 original_rf_top;
u16 original_if_top;
u16 original_if_min;
u16 original_aci0_if_top;
u16 original_aci1_if_top;
u16 original_aci0_if_min;
u8 original_if_unplug_th;
u8 original_rf_unplug_th;
u8 original_dtop_if_unplug_th;
u8 original_dtop_rf_unplug_th;
/* statistics */
u32 pre_vit_error_count;
u32 pre_vit_bit_count;
u32 ber;
u32 post_vit_error_count;
u32 post_vit_bit_count;
u32 unc;
u16 abort_count;
int opened;
int strong;
unsigned long next_status_check;
struct dvb_frontend frontend;
};
static int af9005_write_word_agc(struct dvb_usb_device *d, u16 reghi,
u16 reglo, u8 pos, u8 len, u16 value)
{
int ret;
if ((ret = af9005_write_ofdm_register(d, reglo, (u8) (value & 0xff))))
return ret;
return af9005_write_register_bits(d, reghi, pos, len,
(u8) ((value & 0x300) >> 8));
}
static int af9005_read_word_agc(struct dvb_usb_device *d, u16 reghi,
u16 reglo, u8 pos, u8 len, u16 * value)
{
int ret;
u8 temp0, temp1;
if ((ret = af9005_read_ofdm_register(d, reglo, &temp0)))
return ret;
if ((ret = af9005_read_ofdm_register(d, reghi, &temp1)))
return ret;
switch (pos) {
case 0:
*value = ((u16) (temp1 & 0x03) << 8) + (u16) temp0;
break;
case 2:
*value = ((u16) (temp1 & 0x0C) << 6) + (u16) temp0;
break;
case 4:
*value = ((u16) (temp1 & 0x30) << 4) + (u16) temp0;
break;
case 6:
*value = ((u16) (temp1 & 0xC0) << 2) + (u16) temp0;
break;
default:
err("invalid pos in read word agc");
return -EINVAL;
}
return 0;
}
static int af9005_is_fecmon_available(struct dvb_frontend *fe, int *available)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp;
*available = false;
ret = af9005_read_register_bits(state->d, xd_p_fec_vtb_rsd_mon_en,
fec_vtb_rsd_mon_en_pos,
fec_vtb_rsd_mon_en_len, &temp);
if (ret)
return ret;
if (temp & 1) {
ret =
af9005_read_register_bits(state->d,
xd_p_reg_ofsm_read_rbc_en,
reg_ofsm_read_rbc_en_pos,
reg_ofsm_read_rbc_en_len, &temp);
if (ret)
return ret;
if ((temp & 1) == 0)
*available = true;
}
return 0;
}
static int af9005_get_post_vit_err_cw_count(struct dvb_frontend *fe,
u32 * post_err_count,
u32 * post_cw_count,
u16 * abort_count)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u32 err_count;
u32 cw_count;
u8 temp, temp0, temp1, temp2;
u16 loc_abort_count;
*post_err_count = 0;
*post_cw_count = 0;
/* check if error bit count is ready */
ret =
af9005_read_register_bits(state->d, xd_r_fec_rsd_ber_rdy,
fec_rsd_ber_rdy_pos, fec_rsd_ber_rdy_len,
&temp);
if (ret)
return ret;
if (!temp) {
deb_info("rsd counter not ready\n");
return 100;
}
/* get abort count */
ret =
af9005_read_ofdm_register(state->d,
xd_r_fec_rsd_abort_packet_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d,
xd_r_fec_rsd_abort_packet_cnt_15_8,
&temp1);
if (ret)
return ret;
loc_abort_count = ((u16) temp1 << 8) + temp0;
/* get error count */
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_15_8,
&temp1);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_rsd_bit_err_cnt_23_16,
&temp2);
if (ret)
return ret;
err_count = ((u32) temp2 << 16) + ((u32) temp1 << 8) + temp0;
*post_err_count = err_count - (u32) loc_abort_count *8 * 8;
/* get RSD packet number */
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_15_8,
&temp1);
if (ret)
return ret;
cw_count = ((u32) temp1 << 8) + temp0;
if (cw_count == 0) {
err("wrong RSD packet count");
return -EIO;
}
deb_info("POST abort count %d err count %d rsd packets %d\n",
loc_abort_count, err_count, cw_count);
*post_cw_count = cw_count - (u32) loc_abort_count;
*abort_count = loc_abort_count;
return 0;
}
static int af9005_get_post_vit_ber(struct dvb_frontend *fe,
u32 * post_err_count, u32 * post_cw_count,
u16 * abort_count)
{
u32 loc_cw_count = 0, loc_err_count;
u16 loc_abort_count = 0;
int ret;
ret =
af9005_get_post_vit_err_cw_count(fe, &loc_err_count, &loc_cw_count,
&loc_abort_count);
if (ret)
return ret;
*post_err_count = loc_err_count;
*post_cw_count = loc_cw_count * 204 * 8;
*abort_count = loc_abort_count;
return 0;
}
static int af9005_get_pre_vit_err_bit_count(struct dvb_frontend *fe,
u32 * pre_err_count,
u32 * pre_bit_count)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp, temp0, temp1, temp2;
u32 super_frame_count, x, bits;
int ret;
ret =
af9005_read_register_bits(state->d, xd_r_fec_vtb_ber_rdy,
fec_vtb_ber_rdy_pos, fec_vtb_ber_rdy_len,
&temp);
if (ret)
return ret;
if (!temp) {
deb_info("viterbi counter not ready\n");
return 101; /* ERR_APO_VTB_COUNTER_NOT_READY; */
}
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_15_8,
&temp1);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_fec_vtb_err_bit_cnt_23_16,
&temp2);
if (ret)
return ret;
*pre_err_count = ((u32) temp2 << 16) + ((u32) temp1 << 8) + temp0;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_super_frm_unit_7_0,
&temp0);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_p_fec_super_frm_unit_15_8,
&temp1);
if (ret)
return ret;
super_frame_count = ((u32) temp1 << 8) + temp0;
if (super_frame_count == 0) {
deb_info("super frame count 0\n");
return 102;
}
/* read fft mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_txmod,
reg_tpsd_txmod_pos, reg_tpsd_txmod_len,
&temp);
if (ret)
return ret;
if (temp == 0) {
/* 2K */
x = 1512;
} else if (temp == 1) {
/* 8k */
x = 6048;
} else {
err("Invalid fft mode");
return -EINVAL;
}
/* read modulation mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_const,
reg_tpsd_const_pos, reg_tpsd_const_len,
&temp);
if (ret)
return ret;
switch (temp) {
case 0: /* QPSK */
bits = 2;
break;
case 1: /* QAM_16 */
bits = 4;
break;
case 2: /* QAM_64 */
bits = 6;
break;
default:
err("invalid modulation mode");
return -EINVAL;
}
*pre_bit_count = super_frame_count * 68 * 4 * x * bits;
deb_info("PRE err count %d frame count %d bit count %d\n",
*pre_err_count, super_frame_count, *pre_bit_count);
return 0;
}
static int af9005_reset_pre_viterbi(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
/* set super frame count to 1 */
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_super_frm_unit_7_0,
1 & 0xff);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_p_fec_super_frm_unit_15_8,
1 >> 8);
if (ret)
return ret;
/* reset pre viterbi error count */
ret =
af9005_write_register_bits(state->d, xd_p_fec_vtb_ber_rst,
fec_vtb_ber_rst_pos, fec_vtb_ber_rst_len,
1);
return ret;
}
static int af9005_reset_post_viterbi(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
/* set packet unit */
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_7_0,
10000 & 0xff);
if (ret)
return ret;
ret =
af9005_write_ofdm_register(state->d, xd_p_fec_rsd_packet_unit_15_8,
10000 >> 8);
if (ret)
return ret;
/* reset post viterbi error count */
ret =
af9005_write_register_bits(state->d, xd_p_fec_rsd_ber_rst,
fec_rsd_ber_rst_pos, fec_rsd_ber_rst_len,
1);
return ret;
}
static int af9005_get_statistic(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret, fecavailable;
u64 numerator, denominator;
deb_info("GET STATISTIC\n");
ret = af9005_is_fecmon_available(fe, &fecavailable);
if (ret)
return ret;
if (!fecavailable) {
deb_info("fecmon not available\n");
return 0;
}
ret = af9005_get_pre_vit_err_bit_count(fe, &state->pre_vit_error_count,
&state->pre_vit_bit_count);
if (ret == 0) {
af9005_reset_pre_viterbi(fe);
if (state->pre_vit_bit_count > 0) {
/* according to v 0.0.4 of the dvb api ber should be a multiple
of 10E-9 so we have to multiply the error count by
10E9=1000000000 */
numerator =
(u64) state->pre_vit_error_count * (u64) 1000000000;
denominator = (u64) state->pre_vit_bit_count;
state->ber = do_div(numerator, denominator);
} else {
state->ber = 0xffffffff;
}
}
ret = af9005_get_post_vit_ber(fe, &state->post_vit_error_count,
&state->post_vit_bit_count,
&state->abort_count);
if (ret == 0) {
ret = af9005_reset_post_viterbi(fe);
state->unc += state->abort_count;
if (ret)
return ret;
}
return 0;
}
static int af9005_fe_refresh_state(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (time_after(jiffies, state->next_status_check)) {
deb_info("REFRESH STATE\n");
/* statistics */
if (af9005_get_statistic(fe))
err("get_statistic_failed");
state->next_status_check = jiffies + 250 * HZ / 1000;
}
return 0;
}
static int af9005_fe_read_status(struct dvb_frontend *fe,
enum fe_status *stat)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp;
int ret;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
*stat = 0;
ret = af9005_read_register_bits(state->d, xd_p_agc_lock,
agc_lock_pos, agc_lock_len, &temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_SIGNAL;
ret = af9005_read_register_bits(state->d, xd_p_fd_tpsd_lock,
fd_tpsd_lock_pos, fd_tpsd_lock_len,
&temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_CARRIER;
ret = af9005_read_register_bits(state->d,
xd_r_mp2if_sync_byte_locked,
mp2if_sync_byte_locked_pos,
mp2if_sync_byte_locked_pos, &temp);
if (ret)
return ret;
if (temp)
*stat |= FE_HAS_SYNC | FE_HAS_VITERBI | FE_HAS_LOCK;
if (state->opened)
af9005_led_control(state->d, *stat & FE_HAS_LOCK);
ret =
af9005_read_register_bits(state->d, xd_p_reg_strong_sginal_detected,
reg_strong_sginal_detected_pos,
reg_strong_sginal_detected_len, &temp);
if (ret)
return ret;
if (temp != state->strong) {
deb_info("adjust for strong signal %d\n", temp);
state->strong = temp;
}
return 0;
}
static int af9005_fe_read_ber(struct dvb_frontend *fe, u32 * ber)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
af9005_fe_refresh_state(fe);
*ber = state->ber;
return 0;
}
static int af9005_fe_read_unc_blocks(struct dvb_frontend *fe, u32 * unc)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
af9005_fe_refresh_state(fe);
*unc = state->unc;
return 0;
}
static int af9005_fe_read_signal_strength(struct dvb_frontend *fe,
u16 * strength)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 if_gain, rf_gain;
if (fe->ops.tuner_ops.release == NULL)
return -ENODEV;
ret =
af9005_read_ofdm_register(state->d, xd_r_reg_aagc_rf_gain,
&rf_gain);
if (ret)
return ret;
ret =
af9005_read_ofdm_register(state->d, xd_r_reg_aagc_if_gain,
&if_gain);
if (ret)
return ret;
/* this value has no real meaning, but i don't have the tables that relate
the rf and if gain with the dbm, so I just scale the value */
*strength = (512 - rf_gain - if_gain) << 7;
return 0;
}
static int af9005_fe_read_snr(struct dvb_frontend *fe, u16 * snr)
{
/* the snr can be derived from the ber and the modulation
but I don't think this kind of complex calculations belong
in the driver. I may be wrong.... */
return -ENOSYS;
}
static int af9005_fe_program_cfoe(struct dvb_usb_device *d, u32 bw)
{
u8 temp0, temp1, temp2, temp3, buf[4];
int ret;
u32 NS_coeff1_2048Nu;
u32 NS_coeff1_8191Nu;
u32 NS_coeff1_8192Nu;
u32 NS_coeff1_8193Nu;
u32 NS_coeff2_2k;
u32 NS_coeff2_8k;
switch (bw) {
case 6000000:
NS_coeff1_2048Nu = 0x2ADB6DC;
NS_coeff1_8191Nu = 0xAB7313;
NS_coeff1_8192Nu = 0xAB6DB7;
NS_coeff1_8193Nu = 0xAB685C;
NS_coeff2_2k = 0x156DB6E;
NS_coeff2_8k = 0x55B6DC;
break;
case 7000000:
NS_coeff1_2048Nu = 0x3200001;
NS_coeff1_8191Nu = 0xC80640;
NS_coeff1_8192Nu = 0xC80000;
NS_coeff1_8193Nu = 0xC7F9C0;
NS_coeff2_2k = 0x1900000;
NS_coeff2_8k = 0x640000;
break;
case 8000000:
NS_coeff1_2048Nu = 0x3924926;
NS_coeff1_8191Nu = 0xE4996E;
NS_coeff1_8192Nu = 0xE49249;
NS_coeff1_8193Nu = 0xE48B25;
NS_coeff2_2k = 0x1C92493;
NS_coeff2_8k = 0x724925;
break;
default:
err("Invalid bandwidth %d.", bw);
return -EINVAL;
}
/*
* write NS_coeff1_2048Nu
*/
temp0 = (u8) (NS_coeff1_2048Nu & 0x000000FF);
temp1 = (u8) ((NS_coeff1_2048Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_2048Nu & 0x00FF0000) >> 16);
temp3 = (u8) ((NS_coeff1_2048Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
/* cfoe_NS_2k_coeff1_25_24 */
ret = af9005_write_ofdm_register(d, 0xAE00, buf[0]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_23_16 */
ret = af9005_write_ofdm_register(d, 0xAE01, buf[1]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_15_8 */
ret = af9005_write_ofdm_register(d, 0xAE02, buf[2]);
if (ret)
return ret;
/* cfoe_NS_2k_coeff1_7_0 */
ret = af9005_write_ofdm_register(d, 0xAE03, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff2_2k
*/
temp0 = (u8) ((NS_coeff2_2k & 0x0000003F));
temp1 = (u8) ((NS_coeff2_2k & 0x00003FC0) >> 6);
temp2 = (u8) ((NS_coeff2_2k & 0x003FC000) >> 14);
temp3 = (u8) ((NS_coeff2_2k & 0x01C00000) >> 22);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE04, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE05, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE06, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE07, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8191Nu
*/
temp0 = (u8) ((NS_coeff1_8191Nu & 0x000000FF));
temp1 = (u8) ((NS_coeff1_8191Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8191Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8191Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE08, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE09, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0A, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0B, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8192Nu
*/
temp0 = (u8) (NS_coeff1_8192Nu & 0x000000FF);
temp1 = (u8) ((NS_coeff1_8192Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8192Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8192Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE0C, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0D, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0E, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE0F, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff1_8193Nu
*/
temp0 = (u8) ((NS_coeff1_8193Nu & 0x000000FF));
temp1 = (u8) ((NS_coeff1_8193Nu & 0x0000FF00) >> 8);
temp2 = (u8) ((NS_coeff1_8193Nu & 0x00FFC000) >> 16);
temp3 = (u8) ((NS_coeff1_8193Nu & 0x03000000) >> 24);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE10, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE11, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE12, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE13, buf[3]);
if (ret)
return ret;
/*
* write NS_coeff2_8k
*/
temp0 = (u8) ((NS_coeff2_8k & 0x0000003F));
temp1 = (u8) ((NS_coeff2_8k & 0x00003FC0) >> 6);
temp2 = (u8) ((NS_coeff2_8k & 0x003FC000) >> 14);
temp3 = (u8) ((NS_coeff2_8k & 0x01C00000) >> 22);
/* big endian to make 8051 happy */
buf[0] = temp3;
buf[1] = temp2;
buf[2] = temp1;
buf[3] = temp0;
ret = af9005_write_ofdm_register(d, 0xAE14, buf[0]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE15, buf[1]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE16, buf[2]);
if (ret)
return ret;
ret = af9005_write_ofdm_register(d, 0xAE17, buf[3]);
return ret;
}
static int af9005_fe_select_bw(struct dvb_usb_device *d, u32 bw)
{
u8 temp;
switch (bw) {
case 6000000:
temp = 0;
break;
case 7000000:
temp = 1;
break;
case 8000000:
temp = 2;
break;
default:
err("Invalid bandwidth %d.", bw);
return -EINVAL;
}
return af9005_write_register_bits(d, xd_g_reg_bw, reg_bw_pos,
reg_bw_len, temp);
}
static int af9005_fe_power(struct dvb_frontend *fe, int on)
{
struct af9005_fe_state *state = fe->demodulator_priv;
u8 temp = on;
int ret;
deb_info("power %s tuner\n", on ? "on" : "off");
ret = af9005_send_command(state->d, 0x03, &temp, 1, NULL, 0);
return ret;
}
static struct mt2060_config af9005_mt2060_config = {
0xC0
};
static struct qt1010_config af9005_qt1010_config = {
0xC4
};
static int af9005_fe_init(struct dvb_frontend *fe)
{
struct af9005_fe_state *state = fe->demodulator_priv;
struct dvb_usb_adapter *adap = fe->dvb->priv;
int ret, i, scriptlen;
u8 temp, temp0 = 0, temp1 = 0, temp2 = 0;
u8 buf[2];
u16 if1;
deb_info("in af9005_fe_init\n");
/* reset */
deb_info("reset\n");
if ((ret =
af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst_en,
4, 1, 0x01)))
return ret;
if ((ret = af9005_write_ofdm_register(state->d, APO_REG_RESET, 0)))
return ret;
/* clear ofdm reset */
deb_info("clear ofdm reset\n");
for (i = 0; i < 150; i++) {
if ((ret =
af9005_read_ofdm_register(state->d,
xd_I2C_reg_ofdm_rst, &temp)))
return ret;
if (temp & (regmask[reg_ofdm_rst_len - 1] << reg_ofdm_rst_pos))
break;
msleep(10);
}
if (i == 150)
return -ETIMEDOUT;
/*FIXME in the dump
write B200 A9
write xd_g_reg_ofsm_clk 7
read eepr c6 (2)
read eepr c7 (2)
misc ctrl 3 -> 1
read eepr ca (6)
write xd_g_reg_ofsm_clk 0
write B200 a1
*/
ret = af9005_write_ofdm_register(state->d, 0xb200, 0xa9);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_g_reg_ofsm_clk, 0x07);
if (ret)
return ret;
temp = 0x01;
ret = af9005_send_command(state->d, 0x03, &temp, 1, NULL, 0);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, xd_g_reg_ofsm_clk, 0x00);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xb200, 0xa1);
if (ret)
return ret;
temp = regmask[reg_ofdm_rst_len - 1] << reg_ofdm_rst_pos;
if ((ret =
af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst,
reg_ofdm_rst_pos, reg_ofdm_rst_len, 1)))
return ret;
ret = af9005_write_register_bits(state->d, xd_I2C_reg_ofdm_rst,
reg_ofdm_rst_pos, reg_ofdm_rst_len, 0);
if (ret)
return ret;
/* don't know what register aefc is, but this is what the windows driver does */
ret = af9005_write_ofdm_register(state->d, 0xaefc, 0);
if (ret)
return ret;
/* set stand alone chip */
deb_info("set stand alone chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_stand_alone,
reg_dca_stand_alone_pos,
reg_dca_stand_alone_len, 1)))
return ret;
/* set dca upper & lower chip */
deb_info("set dca upper & lower chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_upper_chip,
reg_dca_upper_chip_pos,
reg_dca_upper_chip_len, 0)))
return ret;
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_lower_chip,
reg_dca_lower_chip_pos,
reg_dca_lower_chip_len, 0)))
return ret;
/* set 2wire master clock to 0x14 (for 60KHz) */
deb_info("set 2wire master clock to 0x14 (for 60KHz)\n");
if ((ret =
af9005_write_ofdm_register(state->d, xd_I2C_i2c_m_period, 0x14)))
return ret;
/* clear dca enable chip */
deb_info("clear dca enable chip\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_en,
reg_dca_en_pos, reg_dca_en_len, 0)))
return ret;
/* FIXME these are register bits, but I don't know which ones */
ret = af9005_write_ofdm_register(state->d, 0xa16c, 1);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xa3c1, 0);
if (ret)
return ret;
/* init other parameters: program cfoe and select bandwidth */
deb_info("program cfoe\n");
ret = af9005_fe_program_cfoe(state->d, 6000000);
if (ret)
return ret;
/* set read-update bit for modulation */
deb_info("set read-update bit for modulation\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_feq_read_update,
reg_feq_read_update_pos,
reg_feq_read_update_len, 1)))
return ret;
/* sample code has a set MPEG TS code here
but sniffing reveals that it doesn't do it */
/* set read-update bit to 1 for DCA modulation */
deb_info("set read-update bit 1 for DCA modulation\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_reg_dca_read_update,
reg_dca_read_update_pos,
reg_dca_read_update_len, 1)))
return ret;
/* enable fec monitor */
deb_info("enable fec monitor\n");
if ((ret =
af9005_write_register_bits(state->d, xd_p_fec_vtb_rsd_mon_en,
fec_vtb_rsd_mon_en_pos,
fec_vtb_rsd_mon_en_len, 1)))
return ret;
/* FIXME should be register bits, I don't know which ones */
ret = af9005_write_ofdm_register(state->d, 0xa601, 0);
/* set api_retrain_never_freeze */
deb_info("set api_retrain_never_freeze\n");
if ((ret = af9005_write_ofdm_register(state->d, 0xaefb, 0x01)))
return ret;
/* load init script */
deb_info("load init script\n");
scriptlen = sizeof(script) / sizeof(RegDesc);
for (i = 0; i < scriptlen; i++) {
if ((ret =
af9005_write_register_bits(state->d, script[i].reg,
script[i].pos,
script[i].len, script[i].val)))
return ret;
/* save 3 bytes of original fcw */
if (script[i].reg == 0xae18)
temp2 = script[i].val;
if (script[i].reg == 0xae19)
temp1 = script[i].val;
if (script[i].reg == 0xae1a)
temp0 = script[i].val;
/* save original unplug threshold */
if (script[i].reg == xd_p_reg_unplug_th)
state->original_if_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_rf_gain_th)
state->original_rf_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_dtop_if_gain_th)
state->original_dtop_if_unplug_th = script[i].val;
if (script[i].reg == xd_p_reg_unplug_dtop_rf_gain_th)
state->original_dtop_rf_unplug_th = script[i].val;
}
state->original_fcw =
((u32) temp2 << 16) + ((u32) temp1 << 8) + (u32) temp0;
/* save original TOPs */
deb_info("save original TOPs\n");
/* RF TOP */
ret =
af9005_read_word_agc(state->d,
xd_p_reg_aagc_rf_top_numerator_9_8,
xd_p_reg_aagc_rf_top_numerator_7_0, 0, 2,
&state->original_rf_top);
if (ret)
return ret;
/* IF TOP */
ret =
af9005_read_word_agc(state->d,
xd_p_reg_aagc_if_top_numerator_9_8,
xd_p_reg_aagc_if_top_numerator_7_0, 0, 2,
&state->original_if_top);
if (ret)
return ret;
/* ACI 0 IF TOP */
ret =
af9005_read_word_agc(state->d, 0xA60E, 0xA60A, 4, 2,
&state->original_aci0_if_top);
if (ret)
return ret;
/* ACI 1 IF TOP */
ret =
af9005_read_word_agc(state->d, 0xA60E, 0xA60B, 6, 2,
&state->original_aci1_if_top);
if (ret)
return ret;
/* attach tuner and init */
if (fe->ops.tuner_ops.release == NULL) {
/* read tuner and board id from eeprom */
ret = af9005_read_eeprom(adap->dev, 0xc6, buf, 2);
if (ret) {
err("Impossible to read EEPROM\n");
return ret;
}
deb_info("Tuner id %d, board id %d\n", buf[0], buf[1]);
switch (buf[0]) {
case 2: /* MT2060 */
/* read if1 from eeprom */
ret = af9005_read_eeprom(adap->dev, 0xc8, buf, 2);
if (ret) {
err("Impossible to read EEPROM\n");
return ret;
}
if1 = (u16) (buf[0] << 8) + buf[1];
if (dvb_attach(mt2060_attach, fe, &adap->dev->i2c_adap,
&af9005_mt2060_config, if1) == NULL) {
deb_info("MT2060 attach failed\n");
return -ENODEV;
}
break;
case 3: /* QT1010 */
case 9: /* QT1010B */
if (dvb_attach(qt1010_attach, fe, &adap->dev->i2c_adap,
&af9005_qt1010_config) ==NULL) {
deb_info("QT1010 attach failed\n");
return -ENODEV;
}
break;
default:
err("Unsupported tuner type %d", buf[0]);
return -ENODEV;
}
ret = fe->ops.tuner_ops.init(fe);
if (ret)
return ret;
}
deb_info("profit!\n");
return 0;
}
static int af9005_fe_sleep(struct dvb_frontend *fe)
{
return af9005_fe_power(fe, 0);
}
static int af9005_ts_bus_ctrl(struct dvb_frontend *fe, int acquire)
{
struct af9005_fe_state *state = fe->demodulator_priv;
if (acquire) {
state->opened++;
} else {
state->opened--;
if (!state->opened)
af9005_led_control(state->d, 0);
}
return 0;
}
static int af9005_fe_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fep = &fe->dtv_property_cache;
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp, temp0, temp1, temp2;
deb_info("af9005_fe_set_frontend freq %d bw %d\n", fep->frequency,
fep->bandwidth_hz);
if (fe->ops.tuner_ops.release == NULL) {
err("Tuner not attached");
return -ENODEV;
}
deb_info("turn off led\n");
/* not in the log */
ret = af9005_led_control(state->d, 0);
if (ret)
return ret;
/* not sure about the bits */
ret = af9005_write_register_bits(state->d, XD_MP2IF_MISC, 2, 1, 0);
if (ret)
return ret;
/* set FCW to default value */
deb_info("set FCW to default value\n");
temp0 = (u8) (state->original_fcw & 0x000000ff);
temp1 = (u8) ((state->original_fcw & 0x0000ff00) >> 8);
temp2 = (u8) ((state->original_fcw & 0x00ff0000) >> 16);
ret = af9005_write_ofdm_register(state->d, 0xae1a, temp0);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xae19, temp1);
if (ret)
return ret;
ret = af9005_write_ofdm_register(state->d, 0xae18, temp2);
if (ret)
return ret;
/* restore original TOPs */
deb_info("restore original TOPs\n");
ret =
af9005_write_word_agc(state->d,
xd_p_reg_aagc_rf_top_numerator_9_8,
xd_p_reg_aagc_rf_top_numerator_7_0, 0, 2,
state->original_rf_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d,
xd_p_reg_aagc_if_top_numerator_9_8,
xd_p_reg_aagc_if_top_numerator_7_0, 0, 2,
state->original_if_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d, 0xA60E, 0xA60A, 4, 2,
state->original_aci0_if_top);
if (ret)
return ret;
ret =
af9005_write_word_agc(state->d, 0xA60E, 0xA60B, 6, 2,
state->original_aci1_if_top);
if (ret)
return ret;
/* select bandwidth */
deb_info("select bandwidth");
ret = af9005_fe_select_bw(state->d, fep->bandwidth_hz);
if (ret)
return ret;
ret = af9005_fe_program_cfoe(state->d, fep->bandwidth_hz);
if (ret)
return ret;
/* clear easy mode flag */
deb_info("clear easy mode flag\n");
ret = af9005_write_ofdm_register(state->d, 0xaefd, 0);
if (ret)
return ret;
/* set unplug threshold to original value */
deb_info("set unplug threshold to original value\n");
ret =
af9005_write_ofdm_register(state->d, xd_p_reg_unplug_th,
state->original_if_unplug_th);
if (ret)
return ret;
/* set tuner */
deb_info("set tuner\n");
ret = fe->ops.tuner_ops.set_params(fe);
if (ret)
return ret;
/* trigger ofsm */
deb_info("trigger ofsm\n");
temp = 0;
ret = af9005_write_tuner_registers(state->d, 0xffff, &temp, 1);
if (ret)
return ret;
/* clear retrain and freeze flag */
deb_info("clear retrain and freeze flag\n");
ret =
af9005_write_register_bits(state->d,
xd_p_reg_api_retrain_request,
reg_api_retrain_request_pos, 2, 0);
if (ret)
return ret;
/* reset pre viterbi and post viterbi registers and statistics */
af9005_reset_pre_viterbi(fe);
af9005_reset_post_viterbi(fe);
state->pre_vit_error_count = 0;
state->pre_vit_bit_count = 0;
state->ber = 0;
state->post_vit_error_count = 0;
/* state->unc = 0; commented out since it should be ever increasing */
state->abort_count = 0;
state->next_status_check = jiffies;
state->strong = -1;
return 0;
}
static int af9005_fe_get_frontend(struct dvb_frontend *fe,
struct dtv_frontend_properties *fep)
{
struct af9005_fe_state *state = fe->demodulator_priv;
int ret;
u8 temp;
/* mode */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_const,
reg_tpsd_const_pos, reg_tpsd_const_len,
&temp);
if (ret)
return ret;
deb_info("===== fe_get_frontend_legacy = =============\n");
deb_info("CONSTELLATION ");
switch (temp) {
case 0:
fep->modulation = QPSK;
deb_info("QPSK\n");
break;
case 1:
fep->modulation = QAM_16;
deb_info("QAM_16\n");
break;
case 2:
fep->modulation = QAM_64;
deb_info("QAM_64\n");
break;
}
/* tps hierarchy and alpha value */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_hier,
reg_tpsd_hier_pos, reg_tpsd_hier_len,
&temp);
if (ret)
return ret;
deb_info("HIERARCHY ");
switch (temp) {
case 0:
fep->hierarchy = HIERARCHY_NONE;
deb_info("NONE\n");
break;
case 1:
fep->hierarchy = HIERARCHY_1;
deb_info("1\n");
break;
case 2:
fep->hierarchy = HIERARCHY_2;
deb_info("2\n");
break;
case 3:
fep->hierarchy = HIERARCHY_4;
deb_info("4\n");
break;
}
/* high/low priority */
ret =
af9005_read_register_bits(state->d, xd_g_reg_dec_pri,
reg_dec_pri_pos, reg_dec_pri_len, &temp);
if (ret)
return ret;
/* if temp is set = high priority */
deb_info("PRIORITY %s\n", temp ? "high" : "low");
/* high coderate */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_hpcr,
reg_tpsd_hpcr_pos, reg_tpsd_hpcr_len,
&temp);
if (ret)
return ret;
deb_info("CODERATE HP ");
switch (temp) {
case 0:
fep->code_rate_HP = FEC_1_2;
deb_info("FEC_1_2\n");
break;
case 1:
fep->code_rate_HP = FEC_2_3;
deb_info("FEC_2_3\n");
break;
case 2:
fep->code_rate_HP = FEC_3_4;
deb_info("FEC_3_4\n");
break;
case 3:
fep->code_rate_HP = FEC_5_6;
deb_info("FEC_5_6\n");
break;
case 4:
fep->code_rate_HP = FEC_7_8;
deb_info("FEC_7_8\n");
break;
}
/* low coderate */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_lpcr,
reg_tpsd_lpcr_pos, reg_tpsd_lpcr_len,
&temp);
if (ret)
return ret;
deb_info("CODERATE LP ");
switch (temp) {
case 0:
fep->code_rate_LP = FEC_1_2;
deb_info("FEC_1_2\n");
break;
case 1:
fep->code_rate_LP = FEC_2_3;
deb_info("FEC_2_3\n");
break;
case 2:
fep->code_rate_LP = FEC_3_4;
deb_info("FEC_3_4\n");
break;
case 3:
fep->code_rate_LP = FEC_5_6;
deb_info("FEC_5_6\n");
break;
case 4:
fep->code_rate_LP = FEC_7_8;
deb_info("FEC_7_8\n");
break;
}
/* guard interval */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_gi,
reg_tpsd_gi_pos, reg_tpsd_gi_len, &temp);
if (ret)
return ret;
deb_info("GUARD INTERVAL ");
switch (temp) {
case 0:
fep->guard_interval = GUARD_INTERVAL_1_32;
deb_info("1_32\n");
break;
case 1:
fep->guard_interval = GUARD_INTERVAL_1_16;
deb_info("1_16\n");
break;
case 2:
fep->guard_interval = GUARD_INTERVAL_1_8;
deb_info("1_8\n");
break;
case 3:
fep->guard_interval = GUARD_INTERVAL_1_4;
deb_info("1_4\n");
break;
}
/* fft */
ret =
af9005_read_register_bits(state->d, xd_g_reg_tpsd_txmod,
reg_tpsd_txmod_pos, reg_tpsd_txmod_len,
&temp);
if (ret)
return ret;
deb_info("TRANSMISSION MODE ");
switch (temp) {
case 0:
fep->transmission_mode = TRANSMISSION_MODE_2K;
deb_info("2K\n");
break;
case 1:
fep->transmission_mode = TRANSMISSION_MODE_8K;
deb_info("8K\n");
break;
}
/* bandwidth */
ret =
af9005_read_register_bits(state->d, xd_g_reg_bw, reg_bw_pos,
reg_bw_len, &temp);
deb_info("BANDWIDTH ");
switch (temp) {
case 0:
fep->bandwidth_hz = 6000000;
deb_info("6\n");
break;
case 1:
fep->bandwidth_hz = 7000000;
deb_info("7\n");
break;
case 2:
fep->bandwidth_hz = 8000000;
deb_info("8\n");
break;
}
return 0;
}
static void af9005_fe_release(struct dvb_frontend *fe)
{
struct af9005_fe_state *state =
(struct af9005_fe_state *)fe->demodulator_priv;
kfree(state);
}
static const struct dvb_frontend_ops af9005_fe_ops;
struct dvb_frontend *af9005_fe_attach(struct dvb_usb_device *d)
{
struct af9005_fe_state *state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct af9005_fe_state), GFP_KERNEL);
if (state == NULL)
goto error;
deb_info("attaching frontend af9005\n");
state->d = d;
state->opened = 0;
memcpy(&state->frontend.ops, &af9005_fe_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
error:
return NULL;
}
static const struct dvb_frontend_ops af9005_fe_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "AF9005 USB DVB-T",
.frequency_min = 44250000,
.frequency_max = 867250000,
.frequency_stepsize = 250000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 |
FE_CAN_QAM_AUTO | FE_CAN_TRANSMISSION_MODE_AUTO |
FE_CAN_GUARD_INTERVAL_AUTO | FE_CAN_RECOVER |
FE_CAN_HIERARCHY_AUTO,
},
.release = af9005_fe_release,
.init = af9005_fe_init,
.sleep = af9005_fe_sleep,
.ts_bus_ctrl = af9005_ts_bus_ctrl,
.set_frontend = af9005_fe_set_frontend,
.get_frontend = af9005_fe_get_frontend,
.read_status = af9005_fe_read_status,
.read_ber = af9005_fe_read_ber,
.read_signal_strength = af9005_fe_read_signal_strength,
.read_snr = af9005_fe_read_snr,
.read_ucblocks = af9005_fe_read_unc_blocks,
};
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Ilya Baran <ibaran@mit.edu>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BVALGORITHMS_H
#define EIGEN_BVALGORITHMS_H
namespace Eigen {
namespace internal {
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<typename BVH, typename Intersector>
bool intersect_helper(const BVH &tree, Intersector &intersector, typename BVH::Index root)
{
typedef typename BVH::Index Index;
typedef typename BVH::VolumeIterator VolIter;
typedef typename BVH::ObjectIterator ObjIter;
VolIter vBegin = VolIter(), vEnd = VolIter();
ObjIter oBegin = ObjIter(), oEnd = ObjIter();
std::vector<Index> todo(1, root);
while(!todo.empty()) {
tree.getChildren(todo.back(), vBegin, vEnd, oBegin, oEnd);
todo.pop_back();
for(; vBegin != vEnd; ++vBegin) //go through child volumes
if(intersector.intersectVolume(tree.getVolume(*vBegin)))
todo.push_back(*vBegin);
for(; oBegin != oEnd; ++oBegin) //go through child objects
if(intersector.intersectObject(*oBegin))
return true; //intersector said to stop query
}
return false;
}
#endif //not EIGEN_PARSED_BY_DOXYGEN
template<typename Volume1, typename Object1, typename Object2, typename Intersector>
struct intersector_helper1
{
intersector_helper1(const Object2 &inStored, Intersector &in) : stored(inStored), intersector(in) {}
bool intersectVolume(const Volume1 &vol) { return intersector.intersectVolumeObject(vol, stored); }
bool intersectObject(const Object1 &obj) { return intersector.intersectObjectObject(obj, stored); }
Object2 stored;
Intersector &intersector;
private:
intersector_helper1& operator=(const intersector_helper1&);
};
template<typename Volume2, typename Object2, typename Object1, typename Intersector>
struct intersector_helper2
{
intersector_helper2(const Object1 &inStored, Intersector &in) : stored(inStored), intersector(in) {}
bool intersectVolume(const Volume2 &vol) { return intersector.intersectObjectVolume(stored, vol); }
bool intersectObject(const Object2 &obj) { return intersector.intersectObjectObject(stored, obj); }
Object1 stored;
Intersector &intersector;
private:
intersector_helper2& operator=(const intersector_helper2&);
};
} // end namespace internal
/** Given a BVH, runs the query encapsulated by \a intersector.
* The Intersector type must provide the following members: \code
bool intersectVolume(const BVH::Volume &volume) //returns true if volume intersects the query
bool intersectObject(const BVH::Object &object) //returns true if the search should terminate immediately
\endcode
*/
template<typename BVH, typename Intersector>
void BVIntersect(const BVH &tree, Intersector &intersector)
{
internal::intersect_helper(tree, intersector, tree.getRootIndex());
}
/** Given two BVH's, runs the query on their Cartesian product encapsulated by \a intersector.
* The Intersector type must provide the following members: \code
bool intersectVolumeVolume(const BVH1::Volume &v1, const BVH2::Volume &v2) //returns true if product of volumes intersects the query
bool intersectVolumeObject(const BVH1::Volume &v1, const BVH2::Object &o2) //returns true if the volume-object product intersects the query
bool intersectObjectVolume(const BVH1::Object &o1, const BVH2::Volume &v2) //returns true if the volume-object product intersects the query
bool intersectObjectObject(const BVH1::Object &o1, const BVH2::Object &o2) //returns true if the search should terminate immediately
\endcode
*/
template<typename BVH1, typename BVH2, typename Intersector>
void BVIntersect(const BVH1 &tree1, const BVH2 &tree2, Intersector &intersector) //TODO: tandem descent when it makes sense
{
typedef typename BVH1::Index Index1;
typedef typename BVH2::Index Index2;
typedef internal::intersector_helper1<typename BVH1::Volume, typename BVH1::Object, typename BVH2::Object, Intersector> Helper1;
typedef internal::intersector_helper2<typename BVH2::Volume, typename BVH2::Object, typename BVH1::Object, Intersector> Helper2;
typedef typename BVH1::VolumeIterator VolIter1;
typedef typename BVH1::ObjectIterator ObjIter1;
typedef typename BVH2::VolumeIterator VolIter2;
typedef typename BVH2::ObjectIterator ObjIter2;
VolIter1 vBegin1 = VolIter1(), vEnd1 = VolIter1();
ObjIter1 oBegin1 = ObjIter1(), oEnd1 = ObjIter1();
VolIter2 vBegin2 = VolIter2(), vEnd2 = VolIter2(), vCur2 = VolIter2();
ObjIter2 oBegin2 = ObjIter2(), oEnd2 = ObjIter2(), oCur2 = ObjIter2();
std::vector<std::pair<Index1, Index2> > todo(1, std::make_pair(tree1.getRootIndex(), tree2.getRootIndex()));
while(!todo.empty()) {
tree1.getChildren(todo.back().first, vBegin1, vEnd1, oBegin1, oEnd1);
tree2.getChildren(todo.back().second, vBegin2, vEnd2, oBegin2, oEnd2);
todo.pop_back();
for(; vBegin1 != vEnd1; ++vBegin1) { //go through child volumes of first tree
const typename BVH1::Volume &vol1 = tree1.getVolume(*vBegin1);
for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree
if(intersector.intersectVolumeVolume(vol1, tree2.getVolume(*vCur2)))
todo.push_back(std::make_pair(*vBegin1, *vCur2));
}
for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree
Helper1 helper(*oCur2, intersector);
if(internal::intersect_helper(tree1, helper, *vBegin1))
return; //intersector said to stop query
}
}
for(; oBegin1 != oEnd1; ++oBegin1) { //go through child objects of first tree
for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree
Helper2 helper(*oBegin1, intersector);
if(internal::intersect_helper(tree2, helper, *vCur2))
return; //intersector said to stop query
}
for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree
if(intersector.intersectObjectObject(*oBegin1, *oCur2))
return; //intersector said to stop query
}
}
}
}
namespace internal {
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<typename BVH, typename Minimizer>
typename Minimizer::Scalar minimize_helper(const BVH &tree, Minimizer &minimizer, typename BVH::Index root, typename Minimizer::Scalar minimum)
{
typedef typename Minimizer::Scalar Scalar;
typedef typename BVH::Index Index;
typedef std::pair<Scalar, Index> QueueElement; //first element is priority
typedef typename BVH::VolumeIterator VolIter;
typedef typename BVH::ObjectIterator ObjIter;
VolIter vBegin = VolIter(), vEnd = VolIter();
ObjIter oBegin = ObjIter(), oEnd = ObjIter();
std::priority_queue<QueueElement, std::vector<QueueElement>, std::greater<QueueElement> > todo; //smallest is at the top
todo.push(std::make_pair(Scalar(), root));
while(!todo.empty()) {
tree.getChildren(todo.top().second, vBegin, vEnd, oBegin, oEnd);
todo.pop();
for(; oBegin != oEnd; ++oBegin) //go through child objects
minimum = (std::min)(minimum, minimizer.minimumOnObject(*oBegin));
for(; vBegin != vEnd; ++vBegin) { //go through child volumes
Scalar val = minimizer.minimumOnVolume(tree.getVolume(*vBegin));
if(val < minimum)
todo.push(std::make_pair(val, *vBegin));
}
}
return minimum;
}
#endif //not EIGEN_PARSED_BY_DOXYGEN
template<typename Volume1, typename Object1, typename Object2, typename Minimizer>
struct minimizer_helper1
{
typedef typename Minimizer::Scalar Scalar;
minimizer_helper1(const Object2 &inStored, Minimizer &m) : stored(inStored), minimizer(m) {}
Scalar minimumOnVolume(const Volume1 &vol) { return minimizer.minimumOnVolumeObject(vol, stored); }
Scalar minimumOnObject(const Object1 &obj) { return minimizer.minimumOnObjectObject(obj, stored); }
Object2 stored;
Minimizer &minimizer;
private:
minimizer_helper1& operator=(const minimizer_helper1&) {}
};
template<typename Volume2, typename Object2, typename Object1, typename Minimizer>
struct minimizer_helper2
{
typedef typename Minimizer::Scalar Scalar;
minimizer_helper2(const Object1 &inStored, Minimizer &m) : stored(inStored), minimizer(m) {}
Scalar minimumOnVolume(const Volume2 &vol) { return minimizer.minimumOnObjectVolume(stored, vol); }
Scalar minimumOnObject(const Object2 &obj) { return minimizer.minimumOnObjectObject(stored, obj); }
Object1 stored;
Minimizer &minimizer;
private:
minimizer_helper2& operator=(const minimizer_helper2&);
};
} // end namespace internal
/** Given a BVH, runs the query encapsulated by \a minimizer.
* \returns the minimum value.
* The Minimizer type must provide the following members: \code
typedef Scalar //the numeric type of what is being minimized--not necessarily the Scalar type of the BVH (if it has one)
Scalar minimumOnVolume(const BVH::Volume &volume)
Scalar minimumOnObject(const BVH::Object &object)
\endcode
*/
template<typename BVH, typename Minimizer>
typename Minimizer::Scalar BVMinimize(const BVH &tree, Minimizer &minimizer)
{
return internal::minimize_helper(tree, minimizer, tree.getRootIndex(), (std::numeric_limits<typename Minimizer::Scalar>::max)());
}
/** Given two BVH's, runs the query on their cartesian product encapsulated by \a minimizer.
* \returns the minimum value.
* The Minimizer type must provide the following members: \code
typedef Scalar //the numeric type of what is being minimized--not necessarily the Scalar type of the BVH (if it has one)
Scalar minimumOnVolumeVolume(const BVH1::Volume &v1, const BVH2::Volume &v2)
Scalar minimumOnVolumeObject(const BVH1::Volume &v1, const BVH2::Object &o2)
Scalar minimumOnObjectVolume(const BVH1::Object &o1, const BVH2::Volume &v2)
Scalar minimumOnObjectObject(const BVH1::Object &o1, const BVH2::Object &o2)
\endcode
*/
template<typename BVH1, typename BVH2, typename Minimizer>
typename Minimizer::Scalar BVMinimize(const BVH1 &tree1, const BVH2 &tree2, Minimizer &minimizer)
{
typedef typename Minimizer::Scalar Scalar;
typedef typename BVH1::Index Index1;
typedef typename BVH2::Index Index2;
typedef internal::minimizer_helper1<typename BVH1::Volume, typename BVH1::Object, typename BVH2::Object, Minimizer> Helper1;
typedef internal::minimizer_helper2<typename BVH2::Volume, typename BVH2::Object, typename BVH1::Object, Minimizer> Helper2;
typedef std::pair<Scalar, std::pair<Index1, Index2> > QueueElement; //first element is priority
typedef typename BVH1::VolumeIterator VolIter1;
typedef typename BVH1::ObjectIterator ObjIter1;
typedef typename BVH2::VolumeIterator VolIter2;
typedef typename BVH2::ObjectIterator ObjIter2;
VolIter1 vBegin1 = VolIter1(), vEnd1 = VolIter1();
ObjIter1 oBegin1 = ObjIter1(), oEnd1 = ObjIter1();
VolIter2 vBegin2 = VolIter2(), vEnd2 = VolIter2(), vCur2 = VolIter2();
ObjIter2 oBegin2 = ObjIter2(), oEnd2 = ObjIter2(), oCur2 = ObjIter2();
std::priority_queue<QueueElement, std::vector<QueueElement>, std::greater<QueueElement> > todo; //smallest is at the top
Scalar minimum = (std::numeric_limits<Scalar>::max)();
todo.push(std::make_pair(Scalar(), std::make_pair(tree1.getRootIndex(), tree2.getRootIndex())));
while(!todo.empty()) {
tree1.getChildren(todo.top().second.first, vBegin1, vEnd1, oBegin1, oEnd1);
tree2.getChildren(todo.top().second.second, vBegin2, vEnd2, oBegin2, oEnd2);
todo.pop();
for(; oBegin1 != oEnd1; ++oBegin1) { //go through child objects of first tree
for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree
minimum = (std::min)(minimum, minimizer.minimumOnObjectObject(*oBegin1, *oCur2));
}
for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree
Helper2 helper(*oBegin1, minimizer);
minimum = (std::min)(minimum, internal::minimize_helper(tree2, helper, *vCur2, minimum));
}
}
for(; vBegin1 != vEnd1; ++vBegin1) { //go through child volumes of first tree
const typename BVH1::Volume &vol1 = tree1.getVolume(*vBegin1);
for(oCur2 = oBegin2; oCur2 != oEnd2; ++oCur2) {//go through child objects of second tree
Helper1 helper(*oCur2, minimizer);
minimum = (std::min)(minimum, internal::minimize_helper(tree1, helper, *vBegin1, minimum));
}
for(vCur2 = vBegin2; vCur2 != vEnd2; ++vCur2) { //go through child volumes of second tree
Scalar val = minimizer.minimumOnVolumeVolume(vol1, tree2.getVolume(*vCur2));
if(val < minimum)
todo.push(std::make_pair(val, std::make_pair(*vBegin1, *vCur2)));
}
}
}
return minimum;
}
} // end namespace Eigen
#endif // EIGEN_BVALGORITHMS_H
|
{
"pile_set_name": "Github"
}
|
// This file has been autogenerated from a class added in the UI designer.
using System;
using Foundation;
using AppKit;
namespace MacControls
{
public partial class TextViewController : NSViewController
{
#region Constructors
public TextViewController (IntPtr handle) : base (handle)
{
}
#endregion
#region Override Methods
public override void ViewWillAppear ()
{
base.ViewWillAppear ();
// Wire-up controls
UserField.EditingEnded += (sender, e) => {
FeedbackLabel.StringValue = string.Format("User ID: {0}",UserField.StringValue);
};
PasswordField.EditingEnded += (sender, e) => {
FeedbackLabel.StringValue = string.Format("Password: {0}",PasswordField.StringValue);
};
NumberField.EditingEnded+= (sender, e) => {
FeedbackLabel.StringValue = string.Format("Number: {0}",NumberField.IntValue);
};
}
#endregion
}
}
|
{
"pile_set_name": "Github"
}
|
# This file is part of the Sylius package.
# (c) Paweł Jędrzejewski
default:
suites:
ui_applying_shipping_method_rules:
contexts:
- sylius.behat.context.hook.doctrine_orm
- sylius.behat.context.transform.address
- sylius.behat.context.transform.channel
- sylius.behat.context.transform.country
- sylius.behat.context.transform.lexical
- sylius.behat.context.transform.product
- sylius.behat.context.transform.shipping_method
- sylius.behat.context.transform.tax_category
- sylius.behat.context.transform.zone
- sylius.behat.context.transform.shared_storage
- sylius.behat.context.setup.channel
- sylius.behat.context.setup.currency
- sylius.behat.context.setup.geographical
- sylius.behat.context.setup.payment
- sylius.behat.context.setup.product
- sylius.behat.context.setup.shop_security
- sylius.behat.context.setup.shipping
- sylius.behat.context.setup.taxation
- sylius.behat.context.setup.zone
- sylius.behat.context.ui.shop.cart
- sylius.behat.context.ui.shop.checkout
- sylius.behat.context.ui.shop.checkout.addressing
- sylius.behat.context.ui.shop.checkout.payment
- sylius.behat.context.ui.shop.checkout.shipping
filters:
tags: "@applying_shipping_method_rules && @ui"
|
{
"pile_set_name": "Github"
}
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Neural Machine Translation\n",
"\n",
"Welcome to your first programming assignment for this week! \n",
"\n",
"You will build a Neural Machine Translation (NMT) model to translate human readable dates (\"25th of June, 2009\") into machine readable dates (\"2009-06-25\"). You will do this using an attention model, one of the most sophisticated sequence to sequence models. \n",
"\n",
"This notebook was produced together with NVIDIA's Deep Learning Institute. \n",
"\n",
"Let's load all the packages you will need for this assignment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from keras.layers import Bidirectional, Concatenate, Permute, Dot, Input, LSTM, Multiply\n",
"from keras.layers import RepeatVector, Dense, Activation, Lambda\n",
"from keras.optimizers import Adam\n",
"from keras.utils import to_categorical\n",
"from keras.models import load_model, Model\n",
"import keras.backend as K\n",
"import numpy as np\n",
"\n",
"from faker import Faker\n",
"import random\n",
"from tqdm import tqdm\n",
"from babel.dates import format_date\n",
"from nmt_utils import *\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1 - Translating human readable dates into machine readable dates\n",
"\n",
"The model you will build here could be used to translate from one language to another, such as translating from English to Hindi. However, language translation requires massive datasets and usually takes days of training on GPUs. To give you a place to experiment with these models even without using massive datasets, we will instead use a simpler \"date translation\" task. \n",
"\n",
"The network will input a date written in a variety of possible formats (*e.g. \"the 29th of August 1958\", \"03/30/1968\", \"24 JUNE 1987\"*) and translate them into standardized, machine readable dates (*e.g. \"1958-08-29\", \"1968-03-30\", \"1987-06-24\"*). We will have the network learn to output dates in the common machine-readable format YYYY-MM-DD. \n",
"\n",
"\n",
"\n",
"<!-- \n",
"Take a look at [nmt_utils.py](./nmt_utils.py) to see all the formatting. Count and figure out how the formats work, you will need this knowledge later. !--> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1.1 - Dataset\n",
"\n",
"We will train the model on a dataset of 10000 human readable dates and their equivalent, standardized, machine readable dates. Let's run the following cells to load the dataset and print some examples. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"m = 10000\n",
"dataset, human_vocab, machine_vocab, inv_machine_vocab = load_dataset(m)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"dataset[:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You've loaded:\n",
"- `dataset`: a list of tuples of (human readable date, machine readable date)\n",
"- `human_vocab`: a python dictionary mapping all characters used in the human readable dates to an integer-valued index \n",
"- `machine_vocab`: a python dictionary mapping all characters used in machine readable dates to an integer-valued index. These indices are not necessarily consistent with `human_vocab`. \n",
"- `inv_machine_vocab`: the inverse dictionary of `machine_vocab`, mapping from indices back to characters. \n",
"\n",
"Let's preprocess the data and map the raw text data into the index values. We will also use Tx=30 (which we assume is the maximum length of the human readable date; if we get a longer input, we would have to truncate it) and Ty=10 (since \"YYYY-MM-DD\" is 10 characters long). "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"Tx = 30\n",
"Ty = 10\n",
"X, Y, Xoh, Yoh = preprocess_data(dataset, human_vocab, machine_vocab, Tx, Ty)\n",
"\n",
"print(\"X.shape:\", X.shape)\n",
"print(\"Y.shape:\", Y.shape)\n",
"print(\"Xoh.shape:\", Xoh.shape)\n",
"print(\"Yoh.shape:\", Yoh.shape)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You now have:\n",
"- `X`: a processed version of the human readable dates in the training set, where each character is replaced by an index mapped to the character via `human_vocab`. Each date is further padded to $T_x$ values with a special character (< pad >). `X.shape = (m, Tx)`\n",
"- `Y`: a processed version of the machine readable dates in the training set, where each character is replaced by the index it is mapped to in `machine_vocab`. You should have `Y.shape = (m, Ty)`. \n",
"- `Xoh`: one-hot version of `X`, the \"1\" entry's index is mapped to the character thanks to `human_vocab`. `Xoh.shape = (m, Tx, len(human_vocab))`\n",
"- `Yoh`: one-hot version of `Y`, the \"1\" entry's index is mapped to the character thanks to `machine_vocab`. `Yoh.shape = (m, Tx, len(machine_vocab))`. Here, `len(machine_vocab) = 11` since there are 11 characters ('-' as well as 0-9). \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lets also look at some examples of preprocessed training examples. Feel free to play with `index` in the cell below to navigate the dataset and see how source/target dates are preprocessed. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"index = 0\n",
"print(\"Source date:\", dataset[index][0])\n",
"print(\"Target date:\", dataset[index][1])\n",
"print()\n",
"print(\"Source after preprocessing (indices):\", X[index])\n",
"print(\"Target after preprocessing (indices):\", Y[index])\n",
"print()\n",
"print(\"Source after preprocessing (one-hot):\", Xoh[index])\n",
"print(\"Target after preprocessing (one-hot):\", Yoh[index])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2 - Neural machine translation with attention\n",
"\n",
"If you had to translate a book's paragraph from French to English, you would not read the whole paragraph, then close the book and translate. Even during the translation process, you would read/re-read and focus on the parts of the French paragraph corresponding to the parts of the English you are writing down. \n",
"\n",
"The attention mechanism tells a Neural Machine Translation model where it should pay attention to at any step. \n",
"\n",
"\n",
"### 2.1 - Attention mechanism\n",
"\n",
"In this part, you will implement the attention mechanism presented in the lecture videos. Here is a figure to remind you how the model works. The diagram on the left shows the attention model. The diagram on the right shows what one \"Attention\" step does to calculate the attention variables $\\alpha^{\\langle t, t' \\rangle}$, which are used to compute the context variable $context^{\\langle t \\rangle}$ for each timestep in the output ($t=1, \\ldots, T_y$). \n",
"\n",
"<table>\n",
"<td> \n",
"<img src=\"images/attn_model.png\" style=\"width:500;height:500px;\"> <br>\n",
"</td> \n",
"<td> \n",
"<img src=\"images/attn_mechanism.png\" style=\"width:500;height:500px;\"> <br>\n",
"</td> \n",
"</table>\n",
"<caption><center> **Figure 1**: Neural machine translation with attention</center></caption>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Here are some properties of the model that you may notice: \n",
"\n",
"- There are two separate LSTMs in this model (see diagram on the left). Because the one at the bottom of the picture is a Bi-directional LSTM and comes *before* the attention mechanism, we will call it *pre-attention* Bi-LSTM. The LSTM at the top of the diagram comes *after* the attention mechanism, so we will call it the *post-attention* LSTM. The pre-attention Bi-LSTM goes through $T_x$ time steps; the post-attention LSTM goes through $T_y$ time steps. \n",
"\n",
"- The post-attention LSTM passes $s^{\\langle t \\rangle}, c^{\\langle t \\rangle}$ from one time step to the next. In the lecture videos, we were using only a basic RNN for the post-activation sequence model, so the state captured by the RNN output activations $s^{\\langle t\\rangle}$. But since we are using an LSTM here, the LSTM has both the output activation $s^{\\langle t\\rangle}$ and the hidden cell state $c^{\\langle t\\rangle}$. However, unlike previous text generation examples (such as Dinosaurus in week 1), in this model the post-activation LSTM at time $t$ does will not take the specific generated $y^{\\langle t-1 \\rangle}$ as input; it only takes $s^{\\langle t\\rangle}$ and $c^{\\langle t\\rangle}$ as input. We have designed the model this way, because (unlike language generation where adjacent characters are highly correlated) there isn't as strong a dependency between the previous character and the next character in a YYYY-MM-DD date. \n",
"\n",
"- We use $a^{\\langle t \\rangle} = [\\overrightarrow{a}^{\\langle t \\rangle}; \\overleftarrow{a}^{\\langle t \\rangle}]$ to represent the concatenation of the activations of both the forward-direction and backward-directions of the pre-attention Bi-LSTM. \n",
"\n",
"- The diagram on the right uses a `RepeatVector` node to copy $s^{\\langle t-1 \\rangle}$'s value $T_x$ times, and then `Concatenation` to concatenate $s^{\\langle t-1 \\rangle}$ and $a^{\\langle t \\rangle}$ to compute $e^{\\langle t, t'}$, which is then passed through a softmax to compute $\\alpha^{\\langle t, t' \\rangle}$. We'll explain how to use `RepeatVector` and `Concatenation` in Keras below. \n",
"\n",
"Lets implement this model. You will start by implementing two functions: `one_step_attention()` and `model()`.\n",
"\n",
"**1) `one_step_attention()`**: At step $t$, given all the hidden states of the Bi-LSTM ($[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$) and the previous hidden state of the second LSTM ($s^{<t-1>}$), `one_step_attention()` will compute the attention weights ($[\\alpha^{<t,1>},\\alpha^{<t,2>}, ..., \\alpha^{<t,T_x>}]$) and output the context vector (see Figure 1 (right) for details):\n",
"$$context^{<t>} = \\sum_{t' = 0}^{T_x} \\alpha^{<t,t'>}a^{<t'>}\\tag{1}$$ \n",
"\n",
"Note that we are denoting the attention in this notebook $context^{\\langle t \\rangle}$. In the lecture videos, the context was denoted $c^{\\langle t \\rangle}$, but here we are calling it $context^{\\langle t \\rangle}$ to avoid confusion with the (post-attention) LSTM's internal memory cell variable, which is sometimes also denoted $c^{\\langle t \\rangle}$. \n",
" \n",
"**2) `model()`**: Implements the entire model. It first runs the input through a Bi-LSTM to get back $[a^{<1>},a^{<2>}, ..., a^{<T_x>}]$. Then, it calls `one_step_attention()` $T_y$ times (`for` loop). At each iteration of this loop, it gives the computed context vector $c^{<t>}$ to the second LSTM, and runs the output of the LSTM through a dense layer with softmax activation to generate a prediction $\\hat{y}^{<t>}$. \n",
"\n",
"\n",
"\n",
"**Exercise**: Implement `one_step_attention()`. The function `model()` will call the layers in `one_step_attention()` $T_y$ using a for-loop, and it is important that all $T_y$ copies have the same weights. I.e., it should not re-initiaiize the weights every time. In other words, all $T_y$ steps should have shared weights. Here's how you can implement layers with shareable weights in Keras:\n",
"1. Define the layer objects (as global variables for examples).\n",
"2. Call these objects when propagating the input.\n",
"\n",
"We have defined the layers you need as global variables. Please run the following cells to create them. Please check the Keras documentation to make sure you understand what these layers are: [RepeatVector()](https://keras.io/layers/core/#repeatvector), [Concatenate()](https://keras.io/layers/merge/#concatenate), [Dense()](https://keras.io/layers/core/#dense), [Activation()](https://keras.io/layers/core/#activation), [Dot()](https://keras.io/layers/merge/#dot)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Defined shared layers as global variables\n",
"repeator = RepeatVector(Tx)\n",
"concatenator = Concatenate(axis=-1)\n",
"densor = Dense(1, activation = \"relu\")\n",
"activator = Activation(softmax, name='attention_weights') # We are using a custom softmax(axis = 1) loaded in this notebook\n",
"dotor = Dot(axes = 1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you can use these layers to implement `one_step_attention()`. In order to propagate a Keras tensor object X through one of these layers, use `layer(X)` (or `layer([X,Y])` if it requires multiple inputs.), e.g. `densor(X)` will propagate X through the `Dense(1)` layer defined above."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# GRADED FUNCTION: one_step_attention\n",
"\n",
"def one_step_attention(a, s_prev):\n",
" \"\"\"\n",
" Performs one step of attention: Outputs a context vector computed as a dot product of the attention weights\n",
" \"alphas\" and the hidden states \"a\" of the Bi-LSTM.\n",
" \n",
" Arguments:\n",
" a -- hidden state output of the Bi-LSTM, numpy-array of shape (m, Tx, 2*n_a)\n",
" s_prev -- previous hidden state of the (post-attention) LSTM, numpy-array of shape (m, n_s)\n",
" \n",
" Returns:\n",
" context -- context vector, input of the next (post-attetion) LSTM cell\n",
" \"\"\"\n",
" \n",
" ### START CODE HERE ###\n",
" # Use repeator to repeat s_prev to be of shape (m, Tx, n_s) so that you can concatenate it with all hidden states \"a\" (≈ 1 line)\n",
" s_prev = None\n",
" # Use concatenator to concatenate a and s_prev on the last axis (≈ 1 line)\n",
" concat = None\n",
" # Use densor to propagate concat through a small fully-connected neural network to compute the \"energies\" variable e. (≈1 lines)\n",
" e = None\n",
" # Use activator and e to compute the attention weights \"alphas\" (≈ 1 line)\n",
" alphas = None\n",
" # Use dotor together with \"alphas\" and \"a\" to compute the context vector to be given to the next (post-attention) LSTM-cell (≈ 1 line)\n",
" context = None\n",
" ### END CODE HERE ###\n",
" \n",
" return context"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You will be able to check the expected output of `one_step_attention()` after you've coded the `model()` function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Exercise**: Implement `model()` as explained in figure 2 and the text above. Again, we have defined global layers that will share weights to be used in `model()`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"n_a = 64\n",
"n_s = 128\n",
"post_activation_LSTM_cell = LSTM(n_s, return_state = True)\n",
"output_layer = Dense(len(machine_vocab), activation=softmax)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now you can use these layers $T_y$ times in a `for` loop to generate the outputs, and their parameters will not be reinitialized. You will have to carry out the following steps: \n",
"\n",
"1. Propagate the input into a [Bidirectional](https://keras.io/layers/wrappers/#bidirectional) [LSTM](https://keras.io/layers/recurrent/#lstm)\n",
"2. Iterate for $t = 0, \\dots, T_y-1$: \n",
" 1. Call `one_step_attention()` on $[\\alpha^{<t,1>},\\alpha^{<t,2>}, ..., \\alpha^{<t,T_x>}]$ and $s^{<t-1>}$ to get the context vector $context^{<t>}$.\n",
" 2. Give $context^{<t>}$ to the post-attention LSTM cell. Remember pass in the previous hidden-state $s^{\\langle t-1\\rangle}$ and cell-states $c^{\\langle t-1\\rangle}$ of this LSTM using `initial_state= [previous hidden state, previous cell state]`. Get back the new hidden state $s^{<t>}$ and the new cell state $c^{<t>}$.\n",
" 3. Apply a softmax layer to $s^{<t>}$, get the output. \n",
" 4. Save the output by adding it to the list of outputs.\n",
"\n",
"3. Create your Keras model instance, it should have three inputs (\"inputs\", $s^{<0>}$ and $c^{<0>}$) and output the list of \"outputs\"."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# GRADED FUNCTION: model\n",
"\n",
"def model(Tx, Ty, n_a, n_s, human_vocab_size, machine_vocab_size):\n",
" \"\"\"\n",
" Arguments:\n",
" Tx -- length of the input sequence\n",
" Ty -- length of the output sequence\n",
" n_a -- hidden state size of the Bi-LSTM\n",
" n_s -- hidden state size of the post-attention LSTM\n",
" human_vocab_size -- size of the python dictionary \"human_vocab\"\n",
" machine_vocab_size -- size of the python dictionary \"machine_vocab\"\n",
"\n",
" Returns:\n",
" model -- Keras model instance\n",
" \"\"\"\n",
" \n",
" # Define the inputs of your model with a shape (Tx,)\n",
" # Define s0 and c0, initial hidden state for the decoder LSTM of shape (n_s,)\n",
" X = Input(shape=(Tx, human_vocab_size))\n",
" s0 = Input(shape=(n_s,), name='s0')\n",
" c0 = Input(shape=(n_s,), name='c0')\n",
" s = s0\n",
" c = c0\n",
" \n",
" # Initialize empty list of outputs\n",
" outputs = []\n",
" \n",
" ### START CODE HERE ###\n",
" \n",
" # Step 1: Define your pre-attention Bi-LSTM. Remember to use return_sequences=True. (≈ 1 line)\n",
" a = None\n",
" \n",
" # Step 2: Iterate for Ty steps\n",
" for t in range(None):\n",
" \n",
" # Step 2.A: Perform one step of the attention mechanism to get back the context vector at step t (≈ 1 line)\n",
" context = None\n",
" \n",
" # Step 2.B: Apply the post-attention LSTM cell to the \"context\" vector.\n",
" # Don't forget to pass: initial_state = [hidden state, cell state] (≈ 1 line)\n",
" s, _, c = None\n",
" \n",
" # Step 2.C: Apply Dense layer to the hidden state output of the post-attention LSTM (≈ 1 line)\n",
" out = None\n",
" \n",
" # Step 2.D: Append \"out\" to the \"outputs\" list (≈ 1 line)\n",
" None\n",
" \n",
" # Step 3: Create model instance taking three inputs and returning the list of outputs. (≈ 1 line)\n",
" model = None\n",
" \n",
" ### END CODE HERE ###\n",
" \n",
" return model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Run the following cell to create your model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"model = model(Tx, Ty, n_a, n_s, len(human_vocab), len(machine_vocab))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's get a summary of the model to check if it matches the expected output."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Expected Output**:\n",
"\n",
"Here is the summary you should see\n",
"<table>\n",
" <tr>\n",
" <td>\n",
" **Total params:**\n",
" </td>\n",
" <td>\n",
" 185,484\n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **Trainable params:**\n",
" </td>\n",
" <td>\n",
" 185,484\n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **Non-trainable params:**\n",
" </td>\n",
" <td>\n",
" 0\n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **bidirectional_1's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 30, 128) \n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **repeat_vector_1's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 30, 128) \n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **concatenate_1's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 30, 256) \n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **attention_weights's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 30, 1) \n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **dot_1's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 1, 128) \n",
" </td>\n",
" </tr>\n",
" <tr>\n",
" <td>\n",
" **dense_2's output shape **\n",
" </td>\n",
" <td>\n",
" (None, 11) \n",
" </td>\n",
" </tr>\n",
"</table>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As usual, after creating your model in Keras, you need to compile it and define what loss, optimizer and metrics your are want to use. Compile your model using `categorical_crossentropy` loss, a custom [Adam](https://keras.io/optimizers/#adam) [optimizer](https://keras.io/optimizers/#usage-of-optimizers) (`learning rate = 0.005`, $\\beta_1 = 0.9$, $\\beta_2 = 0.999$, `decay = 0.01`) and `['accuracy']` metrics:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"### START CODE HERE ### (≈2 lines)\n",
"opt = None\n",
"None\n",
"### END CODE HERE ###"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The last step is to define all your inputs and outputs to fit the model:\n",
"- You already have X of shape $(m = 10000, T_x = 30)$ containing the training examples.\n",
"- You need to create `s0` and `c0` to initialize your `post_activation_LSTM_cell` with 0s.\n",
"- Given the `model()` you coded, you need the \"outputs\" to be a list of 11 elements of shape (m, T_y). So that: `outputs[i][0], ..., outputs[i][Ty]` represent the true labels (characters) corresponding to the $i^{th}$ training example (`X[i]`). More generally, `outputs[i][j]` is the true label of the $j^{th}$ character in the $i^{th}$ training example."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"s0 = np.zeros((m, n_s))\n",
"c0 = np.zeros((m, n_s))\n",
"outputs = list(Yoh.swapaxes(0,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let's now fit the model and run it for one epoch."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"model.fit([Xoh, s0, c0], outputs, epochs=1, batch_size=100)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"While training you can see the loss as well as the accuracy on each of the 10 positions of the output. The table below gives you an example of what the accuracies could be if the batch had 2 examples: \n",
"\n",
"<img src=\"images/table.png\" style=\"width:700;height:200px;\"> <br>\n",
"<caption><center>Thus, `dense_2_acc_8: 0.89` means that you are predicting the 7th character of the output correctly 89% of the time in the current batch of data. </center></caption>\n",
"\n",
"\n",
"We have run this model for longer, and saved the weights. Run the next cell to load our weights. (By training a model for several minutes, you should be able to obtain a model of similar accuracy, but loading our model will save you time.) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"model.load_weights('models/model.h5')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can now see the results on new examples."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"EXAMPLES = ['3 May 1979', '5 April 09', '21th of August 2016', 'Tue 10 Jul 2007', 'Saturday May 9 2018', 'March 3 2001', 'March 3rd 2001', '1 March 2001']\n",
"for example in EXAMPLES:\n",
" \n",
" source = string_to_int(example, Tx, human_vocab)\n",
" source = np.array(list(map(lambda x: to_categorical(x, num_classes=len(human_vocab)), source))).swapaxes(0,1)\n",
" prediction = model.predict([source, s0, c0])\n",
" prediction = np.argmax(prediction, axis = -1)\n",
" output = [inv_machine_vocab[int(i)] for i in prediction]\n",
" \n",
" print(\"source:\", example)\n",
" print(\"output:\", ''.join(output))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also change these examples to test with your own examples. The next part will give you a better sense on what the attention mechanism is doing--i.e., what part of the input the network is paying attention to when generating a particular output character. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3 - Visualizing Attention (Optional / Ungraded)\n",
"\n",
"Since the problem has a fixed output length of 10, it is also possible to carry out this task using 10 different softmax units to generate the 10 characters of the output. But one advantage of the attention model is that each part of the output (say the month) knows it needs to depend only on a small part of the input (the characters in the input giving the month). We can visualize what part of the output is looking at what part of the input.\n",
"\n",
"Consider the task of translating \"Saturday 9 May 2018\" to \"2018-05-09\". If we visualize the computed $\\alpha^{\\langle t, t' \\rangle}$ we get this: \n",
"\n",
"<img src=\"images/date_attention.png\" style=\"width:600;height:300px;\"> <br>\n",
"<caption><center> **Figure 8**: Full Attention Map</center></caption>\n",
"\n",
"Notice how the output ignores the \"Saturday\" portion of the input. None of the output timesteps are paying much attention to that portion of the input. We see also that 9 has been translated as 09 and May has been correctly translated into 05, with the output paying attention to the parts of the input it needs to to make the translation. The year mostly requires it to pay attention to the input's \"18\" in order to generate \"2018.\" \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 3.1 - Getting the activations from the network\n",
"\n",
"Lets now visualize the attention values in your network. We'll propagate an example through the network, then visualize the values of $\\alpha^{\\langle t, t' \\rangle}$. \n",
"\n",
"To figure out where the attention values are located, let's start by printing a summary of the model ."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Navigate through the output of `model.summary()` above. You can see that the layer named `attention_weights` outputs the `alphas` of shape (m, 30, 1) before `dot_2` computes the context vector for every time step $t = 0, \\ldots, T_y-1$. Lets get the activations from this layer.\n",
"\n",
"The function `attention_map()` pulls out the attention values from your model and plots them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": false
},
"outputs": [],
"source": [
"attention_map = plot_attention_map(model, human_vocab, inv_machine_vocab, \"Tuesday April 08 1993\", num = 6, n_s = 128)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the generated plot you can observe the values of the attention weights for each character of the predicted output. Examine this plot and check that where the network is paying attention makes sense to you.\n",
"\n",
"In the date translation application, you will observe that most of the time attention helps predict the year, and hasn't much impact on predicting the day/month."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Congratulations!\n",
"\n",
"\n",
"You have come to the end of this assignment \n",
"\n",
"<font color='blue'> **Here's what you should remember from this notebook**:\n",
"\n",
"- Machine translation models can be used to map from one sequence to another. They are useful not just for translating human languages (like French->English) but also for tasks like date format translation. \n",
"- An attention mechanism allows a network to focus on the most relevant parts of the input when producing a specific part of the output. \n",
"- A network using an attention mechanism can translate from inputs of length $T_x$ to outputs of length $T_y$, where $T_x$ and $T_y$ can be different. \n",
"- You can visualize attention weights $\\alpha^{\\langle t,t' \\rangle}$ to see what the network is paying attention to while generating each output."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Congratulations on finishing this assignment! You are now able to implement an attention model and use it to learn complex mappings from one sequence to another. "
]
}
],
"metadata": {
"coursera": {
"course_slug": "nlp-sequence-models",
"graded_item_id": "n16CQ",
"launcher_item_id": "npjGi"
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
{
"pile_set_name": "Github"
}
|
/*
* This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
* MD5 Message-Digest Algorithm (RFC 1321).
*
* Homepage:
* http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5
*
* Author:
* Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
*
* This software was written by Alexander Peslyak in 2001. No copyright is
* claimed, and the software is hereby placed in the public domain.
* In case this attempt to disclaim copyright and place the software in the
* public domain is deemed null and void, then the software is
* Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
* general public under the following terms:
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* There's ABSOLUTELY NO WARRANTY, express or implied.
*
* (This is a heavily cut-down "BSD license".)
*
* This differs from Colin Plumb's older public domain implementation in that
* no exactly 32-bit integer data type is required (any 32-bit or wider
* unsigned integer data type will do), there's no compile-time endianness
* configuration, and the function prototypes match OpenSSL's. No code from
* Colin Plumb's implementation has been reused; this comment merely compares
* the properties of the two independent implementations.
*
* The primary goals of this implementation are portability and ease of use.
* It is meant to be fast, but not as fast as possible. Some known
* optimizations are not included to reduce source code size and avoid
* compile-time configuration.
*/
#ifndef HAVE_OPENSSL
#include <string.h>
#include "md5.h"
/*
* The basic MD5 functions.
*
* F and G are optimized compared to their RFC 1321 definitions for
* architectures that lack an AND-NOT instruction, just like in Colin Plumb's
* implementation.
*/
#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z))))
#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y))))
#define H(x, y, z) (((x) ^ (y)) ^ (z))
#define H2(x, y, z) ((x) ^ ((y) ^ (z)))
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
/*
* The MD5 transformation for all four rounds.
*/
#define STEP(f, a, b, c, d, x, t, s) \
(a) += f((b), (c), (d)) + (x) + (t); \
(a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \
(a) += (b);
/*
* SET reads 4 input bytes in little-endian byte order and stores them in a
* properly aligned word in host byte order.
*
* The check for little-endian architectures that tolerate unaligned memory
* accesses is just an optimization. Nothing will break if it fails to detect
* a suitable architecture.
*
* Unfortunately, this optimization may be a C strict aliasing rules violation
* if the caller's data buffer has effective type that cannot be aliased by
* MD5_u32plus. In practice, this problem may occur if these MD5 routines are
* inlined into a calling function, or with future and dangerously advanced
* link-time optimizations. For the time being, keeping these MD5 routines in
* their own translation unit avoids the problem.
*/
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
#define SET(n) \
(*(MD5_u32plus *)&ptr[(n) * 4])
#define GET(n) \
SET(n)
#else
#define SET(n) \
(ctx->block[(n)] = \
(MD5_u32plus)ptr[(n) * 4] | \
((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \
((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \
((MD5_u32plus)ptr[(n) * 4 + 3] << 24))
#define GET(n) \
(ctx->block[(n)])
#endif
/*
* This processes one or more 64-byte data blocks, but does NOT update the bit
* counters. There are no alignment requirements.
*/
static const void *body(MD5_CTX *ctx, const void *data, unsigned long size)
{
const unsigned char *ptr;
MD5_u32plus a, b, c, d;
MD5_u32plus saved_a, saved_b, saved_c, saved_d;
ptr = (const unsigned char *)data;
a = ctx->a;
b = ctx->b;
c = ctx->c;
d = ctx->d;
do {
saved_a = a;
saved_b = b;
saved_c = c;
saved_d = d;
/* Round 1 */
STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7)
STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12)
STEP(F, c, d, a, b, SET(2), 0x242070db, 17)
STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22)
STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7)
STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12)
STEP(F, c, d, a, b, SET(6), 0xa8304613, 17)
STEP(F, b, c, d, a, SET(7), 0xfd469501, 22)
STEP(F, a, b, c, d, SET(8), 0x698098d8, 7)
STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12)
STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17)
STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22)
STEP(F, a, b, c, d, SET(12), 0x6b901122, 7)
STEP(F, d, a, b, c, SET(13), 0xfd987193, 12)
STEP(F, c, d, a, b, SET(14), 0xa679438e, 17)
STEP(F, b, c, d, a, SET(15), 0x49b40821, 22)
/* Round 2 */
STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5)
STEP(G, d, a, b, c, GET(6), 0xc040b340, 9)
STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14)
STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20)
STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5)
STEP(G, d, a, b, c, GET(10), 0x02441453, 9)
STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14)
STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20)
STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5)
STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9)
STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14)
STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20)
STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5)
STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9)
STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14)
STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20)
/* Round 3 */
STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4)
STEP(H2, d, a, b, c, GET(8), 0x8771f681, 11)
STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16)
STEP(H2, b, c, d, a, GET(14), 0xfde5380c, 23)
STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4)
STEP(H2, d, a, b, c, GET(4), 0x4bdecfa9, 11)
STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16)
STEP(H2, b, c, d, a, GET(10), 0xbebfbc70, 23)
STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4)
STEP(H2, d, a, b, c, GET(0), 0xeaa127fa, 11)
STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16)
STEP(H2, b, c, d, a, GET(6), 0x04881d05, 23)
STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4)
STEP(H2, d, a, b, c, GET(12), 0xe6db99e5, 11)
STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16)
STEP(H2, b, c, d, a, GET(2), 0xc4ac5665, 23)
/* Round 4 */
STEP(I, a, b, c, d, GET(0), 0xf4292244, 6)
STEP(I, d, a, b, c, GET(7), 0x432aff97, 10)
STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15)
STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21)
STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6)
STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10)
STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15)
STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21)
STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6)
STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10)
STEP(I, c, d, a, b, GET(6), 0xa3014314, 15)
STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21)
STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6)
STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10)
STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15)
STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21)
a += saved_a;
b += saved_b;
c += saved_c;
d += saved_d;
ptr += 64;
} while (size -= 64);
ctx->a = a;
ctx->b = b;
ctx->c = c;
ctx->d = d;
return ptr;
}
void MD5_Init(MD5_CTX *ctx)
{
ctx->a = 0x67452301;
ctx->b = 0xefcdab89;
ctx->c = 0x98badcfe;
ctx->d = 0x10325476;
ctx->lo = 0;
ctx->hi = 0;
}
void MD5_Update(MD5_CTX *ctx, const void *data, unsigned long size)
{
MD5_u32plus saved_lo;
unsigned long used, available;
saved_lo = ctx->lo;
if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo)
ctx->hi++;
ctx->hi += size >> 29;
used = saved_lo & 0x3f;
if (used) {
available = 64 - used;
if (size < available) {
memcpy(&ctx->buffer[used], data, size);
return;
}
memcpy(&ctx->buffer[used], data, available);
data = (const unsigned char *)data + available;
size -= available;
body(ctx, ctx->buffer, 64);
}
if (size >= 64) {
data = body(ctx, data, size & ~(unsigned long)0x3f);
size &= 0x3f;
}
memcpy(ctx->buffer, data, size);
}
#define OUT(dst, src) \
(dst)[0] = (unsigned char)(src); \
(dst)[1] = (unsigned char)((src) >> 8); \
(dst)[2] = (unsigned char)((src) >> 16); \
(dst)[3] = (unsigned char)((src) >> 24);
void MD5_Final(unsigned char *result, MD5_CTX *ctx)
{
unsigned long used, available;
used = ctx->lo & 0x3f;
ctx->buffer[used++] = 0x80;
available = 64 - used;
if (available < 8) {
memset(&ctx->buffer[used], 0, available);
body(ctx, ctx->buffer, 64);
used = 0;
available = 64;
}
memset(&ctx->buffer[used], 0, available - 8);
ctx->lo <<= 3;
OUT(&ctx->buffer[56], ctx->lo)
OUT(&ctx->buffer[60], ctx->hi)
body(ctx, ctx->buffer, 64);
OUT(&result[0], ctx->a)
OUT(&result[4], ctx->b)
OUT(&result[8], ctx->c)
OUT(&result[12], ctx->d)
memset(ctx, 0, sizeof(*ctx));
}
#endif
|
{
"pile_set_name": "Github"
}
|
# Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
# process all database filter
module Channel::Filter::Database
def self.run(_channel, mail)
# process postmaster filter
filters = PostmasterFilter.where(active: true, channel: 'email').order(:name, :created_at)
filters.each do |filter|
Rails.logger.info " process filter #{filter.name} ..."
all_matches_ok = true
min_one_rule_exists = false
filter[:match].each do |key, meta|
next if meta.blank? || meta['value'].blank?
value = mail[ key.downcase.to_sym ]
match_rule = meta['value']
min_one_rule_exists = true
case meta[:operator]
when 'contains not'
if value.present? && Channel::Filter::Match::EmailRegex.match(value: value, match_rule: match_rule)
all_matches_ok = false
Rails.logger.info " matching #{key.downcase}:'#{value}' on #{match_rule}, but shoud not"
end
when 'contains'
if value.blank? || !Channel::Filter::Match::EmailRegex.match(value: value, match_rule: match_rule)
all_matches_ok = false
Rails.logger.info " not matching #{key.downcase}:'#{value}' on #{match_rule}, but should"
end
else
all_matches_ok = false
Rails.logger.info " Invalid operator in match #{meta.inspect}"
end
break if !all_matches_ok
rescue => e
all_matches_ok = false
Rails.logger.error "can't use match rule #{match_rule} on #{value}"
Rails.logger.error e.inspect
end
next if !min_one_rule_exists
next if !all_matches_ok
filter[:perform].each do |key, meta|
next if !Channel::EmailParser.check_attributes_by_x_headers(key, meta['value'])
Rails.logger.info " perform '#{key.downcase}' = '#{meta.inspect}'"
if key.casecmp('x-zammad-ticket-tags').zero? && meta['value'].present? && meta['operator'].present?
mail[ 'x-zammad-ticket-tags'.downcase.to_sym ] ||= []
tags = meta['value'].split(',')
case meta['operator']
when 'add'
tags.each do |tag|
next if tag.blank?
tag.strip!
next if mail[ 'x-zammad-ticket-tags'.downcase.to_sym ].include?(tag)
mail[ 'x-zammad-ticket-tags'.downcase.to_sym ].push tag
end
when 'remove'
tags.each do |tag|
next if tag.blank?
tag.strip!
mail[ 'x-zammad-ticket-tags'.downcase.to_sym ] -= [tag]
end
end
next
end
mail[ key.downcase.to_sym ] = meta['value']
end
end
end
end
|
{
"pile_set_name": "Github"
}
|
((output
(((f.ml (1 0) (1 30))
(paragraph
(((f.ml (1 0) (1 30)) (code_span Foo.extension-Bar.field-baz)))))))
(warnings
( "File \"f.ml\", line 1, characters 6-19:\
\nExpected 'module-', 'module-type-', 'type-', 'class-', 'class-type-', or an unqualified reference.")))
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="7.10">
<data>
<int key="IBDocument.SystemTarget">1060</int>
<string key="IBDocument.SystemVersion">10J567</string>
<string key="IBDocument.InterfaceBuilderVersion">823</string>
<string key="IBDocument.AppKitVersion">1038.35</string>
<string key="IBDocument.HIToolboxVersion">462.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.imagekit.ibplugin</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>823</string>
<string>1.1</string>
</object>
</object>
<object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
<bool key="EncodedWithXMLCoder">YES</bool>
<integer value="2"/>
</object>
<object class="NSArray" key="IBDocument.PluginDependencies">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>com.apple.imagekit.ibplugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
</object>
<object class="NSMutableDictionary" key="IBDocument.Metadata">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys" id="0">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<object class="NSMutableArray" key="IBDocument.RootObjects" id="1000">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSCustomObject" id="1001">
<string key="NSClassName">MainWindowController</string>
</object>
<object class="NSCustomObject" id="1003">
<string key="NSClassName">FirstResponder</string>
</object>
<object class="NSCustomObject" id="1004">
<string key="NSClassName">NSApplication</string>
</object>
<object class="NSWindowTemplate" id="748157544">
<int key="NSWindowStyleMask">15</int>
<int key="NSWindowBacking">2</int>
<string key="NSWindowRect">{{54, 739}, {754, 652}}</string>
<int key="NSWTFlags">1948778496</int>
<string key="NSWindowTitle">Image Kit Demo (part1)</string>
<string key="NSWindowClass">MainWindow</string>
<nil key="NSViewClass"/>
<string key="NSWindowContentMaxSize">{1.79769e+308, 1.79769e+308}</string>
<string key="NSWindowContentMinSize">{250, 150}</string>
<object class="NSView" key="NSWindowView" id="312036702">
<reference key="NSNextResponder"/>
<int key="NSvFlags">256</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSButton" id="886782147">
<reference key="NSNextResponder" ref="312036702"/>
<int key="NSvFlags">292</int>
<string key="NSFrame">{{6, 19}, {27, 25}}</string>
<reference key="NSSuperview" ref="312036702"/>
<bool key="NSEnabled">YES</bool>
<object class="NSButtonCell" key="NSCell" id="805436884">
<int key="NSCellFlags">67239424</int>
<int key="NSCellFlags2">134217728</int>
<string key="NSContents">+</string>
<object class="NSFont" key="NSSupport" id="13567">
<string key="NSName">LucidaGrande</string>
<double key="NSSize">13</double>
<int key="NSfFlags">1044</int>
</object>
<reference key="NSControlView" ref="886782147"/>
<int key="NSButtonFlags">-2038152961</int>
<int key="NSButtonFlags2">34</int>
<string key="NSAlternateContents"/>
<string key="NSKeyEquivalent"/>
<int key="NSPeriodicDelay">400</int>
<int key="NSPeriodicInterval">75</int>
</object>
</object>
<object class="NSSlider" id="654159011">
<reference key="NSNextResponder" ref="312036702"/>
<int key="NSvFlags">289</int>
<string key="NSFrame">{{574, 25}, {160, 16}}</string>
<reference key="NSSuperview" ref="312036702"/>
<bool key="NSEnabled">YES</bool>
<object class="NSSliderCell" key="NSCell" id="884284458">
<int key="NSCellFlags">-2079981824</int>
<int key="NSCellFlags2">262144</int>
<string key="NSContents"/>
<reference key="NSControlView" ref="654159011"/>
<double key="NSMaxValue">1</double>
<double key="NSMinValue">0.0</double>
<double key="NSValue">0.32999999999999996</double>
<double key="NSAltIncValue">0.0</double>
<int key="NSNumberOfTickMarks">11</int>
<int key="NSTickMarkPosition">1</int>
<bool key="NSAllowsTickMarkValuesOnly">NO</bool>
<bool key="NSVertical">NO</bool>
</object>
</object>
<object class="NSSearchField" id="706241784">
<reference key="NSNextResponder" ref="312036702"/>
<int key="NSvFlags">292</int>
<string key="NSFrame">{{41, 21}, {204, 22}}</string>
<reference key="NSSuperview" ref="312036702"/>
<bool key="NSEnabled">YES</bool>
<object class="NSSearchFieldCell" key="NSCell" id="603874259">
<int key="NSCellFlags">343014976</int>
<int key="NSCellFlags2">268436480</int>
<string key="NSContents"/>
<reference key="NSSupport" ref="13567"/>
<reference key="NSControlView" ref="706241784"/>
<bool key="NSDrawsBackground">YES</bool>
<int key="NSTextBezelStyle">1</int>
<object class="NSColor" key="NSBackgroundColor">
<int key="NSColorSpace">6</int>
<string key="NSCatalogName">System</string>
<string key="NSColorName">textBackgroundColor</string>
<object class="NSColor" key="NSColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MQA</bytes>
</object>
</object>
<object class="NSColor" key="NSTextColor">
<int key="NSColorSpace">6</int>
<string key="NSCatalogName">System</string>
<string key="NSColorName">controlTextColor</string>
<object class="NSColor" key="NSColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MAA</bytes>
</object>
</object>
<object class="NSButtonCell" key="NSSearchButtonCell">
<int key="NSCellFlags">130560</int>
<int key="NSCellFlags2">0</int>
<string key="NSContents">search</string>
<reference key="NSControlView" ref="706241784"/>
<string key="NSAction">_searchFieldSearch:</string>
<reference key="NSTarget" ref="603874259"/>
<int key="NSButtonFlags">138690815</int>
<int key="NSButtonFlags2">0</int>
<string key="NSKeyEquivalent"/>
<int key="NSPeriodicDelay">400</int>
<int key="NSPeriodicInterval">75</int>
</object>
<object class="NSButtonCell" key="NSCancelButtonCell">
<int key="NSCellFlags">130560</int>
<int key="NSCellFlags2">0</int>
<string key="NSContents">clear</string>
<object class="NSMutableArray" key="NSAccessibilityOverriddenAttributes">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSMutableDictionary">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>AXDescription</string>
<string>NSAccessibilityEncodedAttributesValueType</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>cancel</string>
<integer value="1"/>
</object>
</object>
</object>
<reference key="NSControlView" ref="706241784"/>
<string key="NSAction">_searchFieldCancel:</string>
<reference key="NSTarget" ref="603874259"/>
<int key="NSButtonFlags">138690815</int>
<int key="NSButtonFlags2">0</int>
<string key="NSKeyEquivalent"/>
<int key="NSPeriodicDelay">400</int>
<int key="NSPeriodicInterval">75</int>
</object>
<int key="NSMaximumRecents">255</int>
</object>
</object>
<object class="NSScrollView" id="47454751">
<reference key="NSNextResponder" ref="312036702"/>
<int key="NSvFlags">274</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSClipView" id="788685626">
<reference key="NSNextResponder" ref="47454751"/>
<int key="NSvFlags">2304</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IKImageBrowserView" id="187613647">
<reference key="NSNextResponder" ref="788685626"/>
<int key="NSvFlags">45</int>
<object class="NSMutableSet" key="NSDragTypes">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="set.sortedObjects">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>Apple PDF pasteboard type</string>
<string>Apple PICT pasteboard type</string>
<string>Apple PNG pasteboard type</string>
<string>Apple URL pasteboard type</string>
<string>NSFilenamesPboardType</string>
<string>NSTypedFilenamesPboardType:'.SGI'</string>
<string>NSTypedFilenamesPboardType:'8BPS'</string>
<string>NSTypedFilenamesPboardType:'BMP '</string>
<string>NSTypedFilenamesPboardType:'BMPf'</string>
<string>NSTypedFilenamesPboardType:'EPSF'</string>
<string>NSTypedFilenamesPboardType:'FPix'</string>
<string>NSTypedFilenamesPboardType:'GIFf'</string>
<string>NSTypedFilenamesPboardType:'ICO '</string>
<string>NSTypedFilenamesPboardType:'JPEG'</string>
<string>NSTypedFilenamesPboardType:'PDF '</string>
<string>NSTypedFilenamesPboardType:'PICT'</string>
<string>NSTypedFilenamesPboardType:'PNGf'</string>
<string>NSTypedFilenamesPboardType:'PNTG'</string>
<string>NSTypedFilenamesPboardType:'TIFF'</string>
<string>NSTypedFilenamesPboardType:'TPIC'</string>
<string>NSTypedFilenamesPboardType:'icns'</string>
<string>NSTypedFilenamesPboardType:'jp2 '</string>
<string>NSTypedFilenamesPboardType:'qtif'</string>
<string>NSTypedFilenamesPboardType:3FR</string>
<string>NSTypedFilenamesPboardType:3fr</string>
<string>NSTypedFilenamesPboardType:ARW</string>
<string>NSTypedFilenamesPboardType:BMP</string>
<string>NSTypedFilenamesPboardType:CR2</string>
<string>NSTypedFilenamesPboardType:CRW</string>
<string>NSTypedFilenamesPboardType:CUR</string>
<string>NSTypedFilenamesPboardType:DCR</string>
<string>NSTypedFilenamesPboardType:DNG</string>
<string>NSTypedFilenamesPboardType:EFX</string>
<string>NSTypedFilenamesPboardType:EPI</string>
<string>NSTypedFilenamesPboardType:EPS</string>
<string>NSTypedFilenamesPboardType:EPSF</string>
<string>NSTypedFilenamesPboardType:EPSI</string>
<string>NSTypedFilenamesPboardType:ERF</string>
<string>NSTypedFilenamesPboardType:EXR</string>
<string>NSTypedFilenamesPboardType:FAX</string>
<string>NSTypedFilenamesPboardType:FFF</string>
<string>NSTypedFilenamesPboardType:FPIX</string>
<string>NSTypedFilenamesPboardType:FPX</string>
<string>NSTypedFilenamesPboardType:G3</string>
<string>NSTypedFilenamesPboardType:GIF</string>
<string>NSTypedFilenamesPboardType:HDR</string>
<string>NSTypedFilenamesPboardType:ICNS</string>
<string>NSTypedFilenamesPboardType:ICO</string>
<string>NSTypedFilenamesPboardType:JFAX</string>
<string>NSTypedFilenamesPboardType:JFX</string>
<string>NSTypedFilenamesPboardType:JP2</string>
<string>NSTypedFilenamesPboardType:JPE</string>
<string>NSTypedFilenamesPboardType:JPEG</string>
<string>NSTypedFilenamesPboardType:JPF</string>
<string>NSTypedFilenamesPboardType:JPG</string>
<string>NSTypedFilenamesPboardType:MAC</string>
<string>NSTypedFilenamesPboardType:MOS</string>
<string>NSTypedFilenamesPboardType:MRW</string>
<string>NSTypedFilenamesPboardType:NEF</string>
<string>NSTypedFilenamesPboardType:NRW</string>
<string>NSTypedFilenamesPboardType:ORF</string>
<string>NSTypedFilenamesPboardType:PCT</string>
<string>NSTypedFilenamesPboardType:PDF</string>
<string>NSTypedFilenamesPboardType:PEF</string>
<string>NSTypedFilenamesPboardType:PIC</string>
<string>NSTypedFilenamesPboardType:PICT</string>
<string>NSTypedFilenamesPboardType:PNG</string>
<string>NSTypedFilenamesPboardType:PNT</string>
<string>NSTypedFilenamesPboardType:PNTG</string>
<string>NSTypedFilenamesPboardType:PS</string>
<string>NSTypedFilenamesPboardType:PSD</string>
<string>NSTypedFilenamesPboardType:QTI</string>
<string>NSTypedFilenamesPboardType:QTIF</string>
<string>NSTypedFilenamesPboardType:RAF</string>
<string>NSTypedFilenamesPboardType:RAW</string>
<string>NSTypedFilenamesPboardType:RGB</string>
<string>NSTypedFilenamesPboardType:RW2</string>
<string>NSTypedFilenamesPboardType:RWL</string>
<string>NSTypedFilenamesPboardType:SGI</string>
<string>NSTypedFilenamesPboardType:SR2</string>
<string>NSTypedFilenamesPboardType:SRF</string>
<string>NSTypedFilenamesPboardType:SRW</string>
<string>NSTypedFilenamesPboardType:TARGA</string>
<string>NSTypedFilenamesPboardType:TGA</string>
<string>NSTypedFilenamesPboardType:TIF</string>
<string>NSTypedFilenamesPboardType:TIFF</string>
<string>NSTypedFilenamesPboardType:XBM</string>
<string>NSTypedFilenamesPboardType:arw</string>
<string>NSTypedFilenamesPboardType:bmp</string>
<string>NSTypedFilenamesPboardType:cr2</string>
<string>NSTypedFilenamesPboardType:crw</string>
<string>NSTypedFilenamesPboardType:cur</string>
<string>NSTypedFilenamesPboardType:dcr</string>
<string>NSTypedFilenamesPboardType:dng</string>
<string>NSTypedFilenamesPboardType:efx</string>
<string>NSTypedFilenamesPboardType:epi</string>
<string>NSTypedFilenamesPboardType:eps</string>
<string>NSTypedFilenamesPboardType:epsf</string>
<string>NSTypedFilenamesPboardType:epsi</string>
<string>NSTypedFilenamesPboardType:erf</string>
<string>NSTypedFilenamesPboardType:exr</string>
<string>NSTypedFilenamesPboardType:fax</string>
<string>NSTypedFilenamesPboardType:fff</string>
<string>NSTypedFilenamesPboardType:fpix</string>
<string>NSTypedFilenamesPboardType:fpx</string>
<string>NSTypedFilenamesPboardType:g3</string>
<string>NSTypedFilenamesPboardType:gif</string>
<string>NSTypedFilenamesPboardType:hdr</string>
<string>NSTypedFilenamesPboardType:icns</string>
<string>NSTypedFilenamesPboardType:ico</string>
<string>NSTypedFilenamesPboardType:jfax</string>
<string>NSTypedFilenamesPboardType:jfx</string>
<string>NSTypedFilenamesPboardType:jp2</string>
<string>NSTypedFilenamesPboardType:jpe</string>
<string>NSTypedFilenamesPboardType:jpeg</string>
<string>NSTypedFilenamesPboardType:jpf</string>
<string>NSTypedFilenamesPboardType:jpg</string>
<string>NSTypedFilenamesPboardType:mac</string>
<string>NSTypedFilenamesPboardType:mos</string>
<string>NSTypedFilenamesPboardType:mrw</string>
<string>NSTypedFilenamesPboardType:nef</string>
<string>NSTypedFilenamesPboardType:nrw</string>
<string>NSTypedFilenamesPboardType:orf</string>
<string>NSTypedFilenamesPboardType:pct</string>
<string>NSTypedFilenamesPboardType:pdf</string>
<string>NSTypedFilenamesPboardType:pef</string>
<string>NSTypedFilenamesPboardType:pic</string>
<string>NSTypedFilenamesPboardType:pict</string>
<string>NSTypedFilenamesPboardType:png</string>
<string>NSTypedFilenamesPboardType:pnt</string>
<string>NSTypedFilenamesPboardType:pntg</string>
<string>NSTypedFilenamesPboardType:ps</string>
<string>NSTypedFilenamesPboardType:psd</string>
<string>NSTypedFilenamesPboardType:qti</string>
<string>NSTypedFilenamesPboardType:qtif</string>
<string>NSTypedFilenamesPboardType:raf</string>
<string>NSTypedFilenamesPboardType:raw</string>
<string>NSTypedFilenamesPboardType:rgb</string>
<string>NSTypedFilenamesPboardType:rw2</string>
<string>NSTypedFilenamesPboardType:rwl</string>
<string>NSTypedFilenamesPboardType:sgi</string>
<string>NSTypedFilenamesPboardType:sr2</string>
<string>NSTypedFilenamesPboardType:srf</string>
<string>NSTypedFilenamesPboardType:srw</string>
<string>NSTypedFilenamesPboardType:targa</string>
<string>NSTypedFilenamesPboardType:tga</string>
<string>NSTypedFilenamesPboardType:tif</string>
<string>NSTypedFilenamesPboardType:tiff</string>
<string>NSTypedFilenamesPboardType:xbm</string>
<string>NeXT Encapsulated PostScript v1.2 pasteboard type</string>
<string>NeXT TIFF v4.0 pasteboard type</string>
</object>
</object>
<string key="NSFrameSize">{739, 600}</string>
<reference key="NSSuperview" ref="788685626"/>
<bool key="constrainsToOriginalSize">NO</bool>
<bool key="cellsHaveSubtitle">NO</bool>
<bool key="cellsHaveTitle">YES</bool>
<bool key="outlinesCells">YES</bool>
<bool key="shadowsCells">YES</bool>
<bool key="animates">YES</bool>
<bool key="allowsReordering">YES</bool>
<bool key="allowsMultipleSelection">YES</bool>
<float key="cellWidth">100</float>
<float key="cellHeight">100</float>
<reference key="dataSource"/>
<reference key="delegate"/>
</object>
</object>
<string key="NSFrame">{{1, 1}, {739, 600}}</string>
<reference key="NSSuperview" ref="47454751"/>
<reference key="NSNextKeyView" ref="187613647"/>
<reference key="NSDocView" ref="187613647"/>
<object class="NSColor" key="NSBGColor">
<int key="NSColorSpace">6</int>
<string key="NSCatalogName">System</string>
<string key="NSColorName">controlColor</string>
<object class="NSColor" key="NSColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MC42NjY2NjY2NjY3AA</bytes>
</object>
</object>
<int key="NScvFlags">6</int>
</object>
<object class="NSScroller" id="609598685">
<reference key="NSNextResponder" ref="47454751"/>
<int key="NSvFlags">256</int>
<string key="NSFrame">{{740, 1}, {15, 600}}</string>
<reference key="NSSuperview" ref="47454751"/>
<reference key="NSTarget" ref="47454751"/>
<string key="NSAction">_doScroller:</string>
<double key="NSCurValue">1</double>
<double key="NSPercent">0.96363627910614014</double>
</object>
<object class="NSScroller" id="41567237">
<reference key="NSNextResponder" ref="47454751"/>
<int key="NSvFlags">-2147483392</int>
<string key="NSFrame">{{-100, -100}, {739, 15}}</string>
<reference key="NSSuperview" ref="47454751"/>
<int key="NSsFlags">1</int>
<reference key="NSTarget" ref="47454751"/>
<string key="NSAction">_doScroller:</string>
<double key="NSPercent">0.50602412223815918</double>
</object>
</object>
<string key="NSFrame">{{-1, 51}, {756, 602}}</string>
<reference key="NSSuperview" ref="312036702"/>
<reference key="NSNextKeyView" ref="788685626"/>
<int key="NSsFlags">18</int>
<reference key="NSVScroller" ref="609598685"/>
<reference key="NSHScroller" ref="41567237"/>
<reference key="NSContentView" ref="788685626"/>
<bytes key="NSScrollAmts">QSAAAEEgAABCzQAAQvAAAA</bytes>
</object>
</object>
<string key="NSFrameSize">{754, 652}</string>
<reference key="NSSuperview"/>
</object>
<string key="NSScreenRect">{{0, 0}, {2560, 1418}}</string>
<string key="NSMinSize">{250, 172}</string>
<string key="NSMaxSize">{1.79769e+308, 1.79769e+308}</string>
</object>
</object>
<object class="IBObjectContainer" key="IBDocument.Objects">
<object class="NSMutableArray" key="connectionRecords">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">window</string>
<reference key="source" ref="1001"/>
<reference key="destination" ref="748157544"/>
</object>
<int key="connectionID">6</int>
</object>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">initialFirstResponder</string>
<reference key="source" ref="748157544"/>
<reference key="destination" ref="706241784"/>
</object>
<int key="connectionID">20</int>
</object>
<object class="IBConnectionRecord">
<object class="IBOutletConnection" key="connection">
<string key="label">browserView</string>
<reference key="source" ref="1001"/>
<reference key="destination" ref="187613647"/>
</object>
<int key="connectionID">29</int>
</object>
<object class="IBConnectionRecord">
<object class="IBActionConnection" key="connection">
<string key="label">AddButtonClicked:</string>
<reference key="source" ref="1001"/>
<reference key="destination" ref="886782147"/>
</object>
<int key="connectionID">30</int>
</object>
<object class="IBConnectionRecord">
<object class="IBActionConnection" key="connection">
<string key="label">SearchTextChanged:</string>
<reference key="source" ref="1001"/>
<reference key="destination" ref="706241784"/>
</object>
<int key="connectionID">31</int>
</object>
<object class="IBConnectionRecord">
<object class="IBActionConnection" key="connection">
<string key="label">SliderChanged:</string>
<reference key="source" ref="1001"/>
<reference key="destination" ref="654159011"/>
</object>
<int key="connectionID">32</int>
</object>
</object>
<object class="IBMutableOrderedSet" key="objectRecords">
<object class="NSArray" key="orderedObjects">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBObjectRecord">
<int key="objectID">0</int>
<reference key="object" ref="0"/>
<reference key="children" ref="1000"/>
<nil key="parent"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">-2</int>
<reference key="object" ref="1001"/>
<reference key="parent" ref="0"/>
<string key="objectName">File's Owner</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">-1</int>
<reference key="object" ref="1003"/>
<reference key="parent" ref="0"/>
<string key="objectName">First Responder</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">-3</int>
<reference key="object" ref="1004"/>
<reference key="parent" ref="0"/>
<string key="objectName">Application</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">2</int>
<reference key="object" ref="748157544"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="312036702"/>
</object>
<reference key="parent" ref="0"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">3</int>
<reference key="object" ref="312036702"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="886782147"/>
<reference ref="706241784"/>
<reference ref="654159011"/>
<reference ref="47454751"/>
</object>
<reference key="parent" ref="748157544"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">7</int>
<reference key="object" ref="886782147"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="805436884"/>
</object>
<reference key="parent" ref="312036702"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">8</int>
<reference key="object" ref="805436884"/>
<reference key="parent" ref="886782147"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">13</int>
<reference key="object" ref="654159011"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="884284458"/>
</object>
<reference key="parent" ref="312036702"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">14</int>
<reference key="object" ref="884284458"/>
<reference key="parent" ref="654159011"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">17</int>
<reference key="object" ref="706241784"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="603874259"/>
</object>
<reference key="parent" ref="312036702"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">18</int>
<reference key="object" ref="603874259"/>
<reference key="parent" ref="706241784"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">25</int>
<reference key="object" ref="47454751"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="609598685"/>
<reference ref="41567237"/>
<reference ref="187613647"/>
</object>
<reference key="parent" ref="312036702"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">26</int>
<reference key="object" ref="609598685"/>
<reference key="parent" ref="47454751"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">27</int>
<reference key="object" ref="41567237"/>
<reference key="parent" ref="47454751"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">24</int>
<reference key="object" ref="187613647"/>
<reference key="parent" ref="47454751"/>
</object>
</object>
</object>
<object class="NSMutableDictionary" key="flattenedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>-1.IBPluginDependency</string>
<string>-2.IBPluginDependency</string>
<string>-3.IBPluginDependency</string>
<string>13.IBPluginDependency</string>
<string>13.IBViewBoundsToFrameTransform</string>
<string>14.IBPluginDependency</string>
<string>17.IBPluginDependency</string>
<string>18.IBPluginDependency</string>
<string>2.IBEditorWindowLastContentRect</string>
<string>2.IBPluginDependency</string>
<string>2.IBWindowTemplateEditedContentRect</string>
<string>2.NSWindowTemplate.visibleAtLaunch</string>
<string>2.windowTemplate.hasMinSize</string>
<string>2.windowTemplate.minSize</string>
<string>24.IBPluginDependency</string>
<string>25.IBViewBoundsToFrameTransform</string>
<string>3.IBPluginDependency</string>
<string>7.IBPluginDependency</string>
<string>8.IBPluginDependency</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<object class="NSAffineTransform">
<bytes key="NSTransformStruct">P4AAAL+AAABECoAAwhwAAA</bytes>
</object>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>{{1326, 237}, {754, 652}}</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>{{1326, 237}, {754, 652}}</string>
<boolean value="YES"/>
<boolean value="YES"/>
<string>{250, 150}</string>
<string>com.apple.imagekit.ibplugin</string>
<object class="NSAffineTransform">
<bytes key="NSTransformStruct">P4AAAL+AAAAAAAAAxCLAAA</bytes>
</object>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
<string>com.apple.InterfaceBuilder.CocoaPlugin</string>
</object>
</object>
<object class="NSMutableDictionary" key="unlocalizedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="activeLocalization"/>
<object class="NSMutableDictionary" key="localizations">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="sourceID"/>
<int key="maxID">32</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes">
<object class="NSMutableArray" key="referencedPartialClassDescriptions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBPartialClassDescription">
<string key="className">MainWindow</string>
<string key="superclassName">NSWindow</string>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
<object class="IBPartialClassDescription">
<string key="className">MainWindowController</string>
<string key="superclassName">NSWindowController</string>
<object class="NSMutableDictionary" key="actions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>AddButtonClicked:</string>
<string>SearchTextChanged:</string>
<string>SliderChanged:</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>NSButton</string>
<string>NSSearchField</string>
<string>NSSlider</string>
</object>
</object>
<object class="NSMutableDictionary" key="actionInfosByName">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>AddButtonClicked:</string>
<string>SearchTextChanged:</string>
<string>SliderChanged:</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBActionInfo">
<string key="name">AddButtonClicked:</string>
<string key="candidateClassName">NSButton</string>
</object>
<object class="IBActionInfo">
<string key="name">SearchTextChanged:</string>
<string key="candidateClassName">NSSearchField</string>
</object>
<object class="IBActionInfo">
<string key="name">SliderChanged:</string>
<string key="candidateClassName">NSSlider</string>
</object>
</object>
</object>
<object class="NSMutableDictionary" key="outlets">
<string key="NS.key.0">browserView</string>
<string key="NS.object.0">IKImageBrowserView</string>
</object>
<object class="NSMutableDictionary" key="toOneOutletInfosByName">
<string key="NS.key.0">browserView</string>
<object class="IBToOneOutletInfo" key="NS.object.0">
<string key="name">browserView</string>
<string key="candidateClassName">IKImageBrowserView</string>
</object>
</object>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBUserSource</string>
<string key="minorKey"/>
</object>
</object>
</object>
</object>
<int key="IBDocument.localizationMode">0</int>
<string key="IBDocument.TargetRuntimeIdentifier">IBCocoaFramework</string>
<object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies">
<string key="NS.key.0">com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3</string>
<integer value="3000" key="NS.object.0"/>
</object>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<nil key="IBDocument.LastKnownRelativeProjectPath"/>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
</data>
</archive>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.artifact_cache;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.testutil.TemporaryPaths;
import com.google.common.base.Charsets;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Base64;
import java.util.Optional;
import javax.net.ssl.X509KeyManager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ClientCertificateHandlerTest {
private static final String SAMPLE_CLIENT_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDPzCCAicCAQIwDQYJKoZIhvcNAQEFBQAwZjELMAkGA1UEBhMCVVMxCzAJBgNV\n"
+ "BAgMAldBMRAwDgYDVQQHDAdTZWF0dGxlMRcwFQYDVQQKDA5GYWNlYm9vaywgSW5j\n"
+ "LjENMAsGA1UECwwEQnVjazEQMA4GA1UEAwwHVGVzdCBDQTAeFw0xOTA1MzAyMTA5\n"
+ "MzBaFw0yOTA1MjcyMTA5MzBaMGUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJXQTEQ\n"
+ "MA4GA1UEBwwHU2VhdHRsZTEXMBUGA1UECgwORmFjZWJvb2ssIEluYy4xDTALBgNV\n"
+ "BAsMBEJ1Y2sxDzANBgNVBAMMBkNsaWVudDCCASIwDQYJKoZIhvcNAQEBBQADggEP\n"
+ "ADCCAQoCggEBAKxHQe2R7+R4Drf/PwXXzKQl44vD6MZh7K8JgFSlQf3xPjeeRmPi\n"
+ "NI5WqnTiBXg6qGL0X6iBIDdXXymgJvppzJuXG3qGDlBM16dmlTXPjW9tXoCl12eL\n"
+ "iVGmlHTHz8OVmVdynpFLyoFeMsaAfB1LoHED32LIFkc4nhGpRTX4WfN2YK//uLpa\n"
+ "1CBO13/GHkctpPR7gVq/Z2WZup/4zDXBw/a41U0sFiIuj2r2nsXCr1sQUHEcNTSg\n"
+ "IUvTSuKX749qeQ9eA7waGyvcoUCzRh9rAvOcRewxMwttqM7kXQQe74HeGL8fh4pP\n"
+ "j17eRxOmKhXbklmtUE/DiPXCb+Qn2aDr62kCAwEAATANBgkqhkiG9w0BAQUFAAOC\n"
+ "AQEAjSRzjE6iFt1bow5tKq0UU+s6co543B6KIBtQg9a4XQokSOZCT3JzH9paZ+ah\n"
+ "7fm/zM/eryPfLLJ0kqzRdnztOZrMj6BnEw/fRV1g20UMfRc6pI0dfXwKlZh8M/Bi\n"
+ "W2q0w02JfSkxMwaVHrMgcET+y0C/yDU5ibLNp+kpFvNLNIdIR/io62gpxzuNjxet\n"
+ "SWRFHNIhkVrB/jkqPnazb8iyHpOSvIMpK1FRbiFpRFiSSeaUsAzHzPoFBjxWe80x\n"
+ "Dvwzy7Sk9viscdMZxaAPcsKxI+5/pZG7NI+7XKiiCfMyoqVFWHesf/4qJ5UydO8Q\n"
+ "L9LdcqcDD0ZZNd/QUK9Qa2bzpw==\n"
+ "-----END CERTIFICATE-----";
private static final String SAMPLE_CLIENT_KEY =
"-----BEGIN PRIVATE KEY-----\n"
+ "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCsR0Htke/keA63\n"
+ "/z8F18ykJeOLw+jGYeyvCYBUpUH98T43nkZj4jSOVqp04gV4Oqhi9F+ogSA3V18p\n"
+ "oCb6acyblxt6hg5QTNenZpU1z41vbV6Apddni4lRppR0x8/DlZlXcp6RS8qBXjLG\n"
+ "gHwdS6BxA99iyBZHOJ4RqUU1+FnzdmCv/7i6WtQgTtd/xh5HLaT0e4Fav2dlmbqf\n"
+ "+Mw1wcP2uNVNLBYiLo9q9p7Fwq9bEFBxHDU0oCFL00ril++PankPXgO8Ghsr3KFA\n"
+ "s0YfawLznEXsMTMLbajO5F0EHu+B3hi/H4eKT49e3kcTpioV25JZrVBPw4j1wm/k\n"
+ "J9mg6+tpAgMBAAECggEAYMFYdpu61l7TLWVuONLdPOeGp21s41YF/rxgVanGqV9+\n"
+ "6O+8asaVa8eizihOmBqhjYnf25xBwrMQYClxGrymzE+OgD6f9Vti1sKXVHRv47/S\n"
+ "DoCVvLKyeagLwpahyh/P0jwucD3XytZjv/ZTPoTF5BMft7PWR0O2Cwc9NrV3l3Ld\n"
+ "ZjHLQAWBhSsvrRFao8e5//awv5PC9xz53RM6Mf3Fth/MIZfD8KTrWQ+/nUyg9LT3\n"
+ "IexJwKJZNFKyiC6UCjoka6RTW5oJxDkfeeicycUFrip1/mpm4zwq1C5oAMccZqPz\n"
+ "DDer4PxDdj0SMnnqHdoOkk2d6UlTsgDBE6poSzmT8QKBgQDcpHf+rHt1UzQ7bSUF\n"
+ "/29BeT4whk8kHr0hOekGMEPj80S150ojsAHohPHz7UOHQn/79EHRR65cEQ1UJTl4\n"
+ "9uRwN+XO3xrmb7XBUigE7fs0S32DmeknviNtqnw4T0QiSuXOicHoV32ZYnqvPNnZ\n"
+ "0Je6pNTDA3Ea6acJmz8O6WNQPQKBgQDH4rkCGrhx/GMuaIvwbRAQpasbBcZw3nbv\n"
+ "a5OSmaM9jf9kSyBtyWEy0sXETSeRaouWc5tQ3m2fbixDC8nAq4Ye1eR6Y1Ac/rwX\n"
+ "+gFpZDmU1jttYqh9YjQwhrIv6PZWBKyltbuZj2uyC0T68mN7Dbn+nH6T+AX4tC7o\n"
+ "iCnbp8funQKBgAh/XQ+13Ntb5PsU7QQaHlLLNJXx1kJx3J7W+B6A5Vx2FgNbcQOG\n"
+ "18v4ssjOLnebHAq8EXzZ4eEx1u2SsW/zMkEQJg2dkg+l5b4YR+pIsBAHiEH1P4GE\n"
+ "VSD4G+ifROR9NfSKYaltFS0/GbJ+CXXWDsHlbzxDeaurq/82t2r/mg+RAoGBALQf\n"
+ "Mdqcm5NT/UhHu7sHfM+TirIKLT1uqzyq80vLGRgSCo+lR27HZsh2uPJhGIPowCru\n"
+ "uIpSNfTSQh6U09TEfFLzKjXDouDOCE+O4ZDIWT8vIlQ68Fw0j5Ue/BlCVCFFixK0\n"
+ "xn3liQXjM+DzZgPwZafz+/h5K2BndlHiyd1/vyHdAoGBAJYSeQ2Ork8EdWxiXNTN\n"
+ "/OD5Jcysc7t3iiTJd/gUr8VTu2l40xCCdRXSwNZ/ku14rlLtoB9047sn7z0M0HMs\n"
+ "+EYga6BZ+trDW7+WtRA7vrVZWH99Xt4QySezuHuy0u7aH6/Zej6vaeV2+iNeG0jC\n"
+ "PJgKB+mYQdYHIBdbKvPFane1\n"
+ "-----END PRIVATE KEY-----";
private static final String SAMPLE_CLIENT_INTERMEDIATE_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDWTCCAkECAQEwDQYJKoZIhvcNAQEFBQAwczELMAkGA1UEBhMCVVMxCzAJBgNV\n"
+ "BAgMAldBMRAwDgYDVQQHDAdTZWF0dGxlMRcwFQYDVQQKDA5GYWNlYm9vaywgSW5j\n"
+ "LjENMAsGA1UECwwEQnVjazEdMBsGA1UEAwwUVGVzdCBDQSBJbnRlcm1lZGlhdGUw\n"
+ "HhcNMTkwNTMwMjEwOTMxWhcNMjkwNTI3MjEwOTMxWjByMQswCQYDVQQGEwJVUzEL\n"
+ "MAkGA1UECAwCV0ExEDAOBgNVBAcMB1NlYXR0bGUxFzAVBgNVBAoMDkZhY2Vib29r\n"
+ "LCBJbmMuMQ0wCwYDVQQLDARCdWNrMRwwGgYDVQQDDBNDbGllbnQgSW50ZXJtZWRp\n"
+ "YXRlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA00Kn8QHOZmUeOk82\n"
+ "gEwwagypwXV08LpnAgcIObBBwY7Y0S8yVxQQeOSjCK+UpWwewi6wktSTnGqiKCnJ\n"
+ "Lh0frikHUWc/RRrfU6qfzoLrxX08RT74hM+r/Az/6FzL0GBxz+vUN7fkrClhQwnG\n"
+ "AdlKaGsBHNfIvG4wlnpFcc1VE2aavtkhqLRY2PJxnJ6rQcxSgXS1PGpiOMl7u8qe\n"
+ "RV9CpbLdsvDj3ee7rKxavinKSJcjRWCduDnXq14BZEIR0pEUL4YXKiEZuMFDYXQe\n"
+ "iDJ+SZqqg9Z3Fgv9Pi/ZNTUYy1Zli+KWf1CHojv0QZbgjxw+2Y6lHr7j8dvCLf1m\n"
+ "y7RWNwIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQCdpK9qQUu1weiU8HM6E05p86k9\n"
+ "9hDUqGIo23dG6Qgj+qo7jS0xZHESyBCQVnjvp6OUxS68wLGflkQsBO+zXz+y+qXe\n"
+ "nPfyca6wei+DLHpzPcUyP70IG4aiFIzSNqvHO2fTaM12q+iUVklUG69Mz7w7/XvZ\n"
+ "DEoLNq9/EbN9OOKO0a4+V+Ix+aiFKbHJWpwtCoQl0RPEIes7VsGA0EF6dN7VI6uo\n"
+ "qEppg7YGxah5+UJQ9Iwo5KH1HPaAjyWoZryDzdwtmDw25dyQpW5ttbqPoiqUuxJu\n"
+ "eTFMKrAoadtD7cS+cB8RYmyYE89Vq+LjddJjFjvRKYgI/8apY3HSX+klWfsq\n"
+ "-----END CERTIFICATE-----";
private static final String SAMPLE_CLIENT_INTERMEDIATE_KEY =
"-----BEGIN PRIVATE KEY-----\n"
+ "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDTQqfxAc5mZR46\n"
+ "TzaATDBqDKnBdXTwumcCBwg5sEHBjtjRLzJXFBB45KMIr5SlbB7CLrCS1JOcaqIo\n"
+ "KckuHR+uKQdRZz9FGt9Tqp/OguvFfTxFPviEz6v8DP/oXMvQYHHP69Q3t+SsKWFD\n"
+ "CcYB2UpoawEc18i8bjCWekVxzVUTZpq+2SGotFjY8nGcnqtBzFKBdLU8amI4yXu7\n"
+ "yp5FX0Klst2y8OPd57usrFq+KcpIlyNFYJ24OderXgFkQhHSkRQvhhcqIRm4wUNh\n"
+ "dB6IMn5JmqqD1ncWC/0+L9k1NRjLVmWL4pZ/UIeiO/RBluCPHD7ZjqUevuPx28It\n"
+ "/WbLtFY3AgMBAAECggEBAL3Kq0/kfIYXH+HomiEG0ZPkjnlDyWwfOj1jDeutwlVe\n"
+ "vMCpMwNx/h5t4V4DR3qZuMRg57bxjS8/yTBl4dwww+5V48IpDHlL3AixR+JiUehZ\n"
+ "S1U2blP6shq9nwYkn+IzUuwlhMENzz0v67YrSJ0Olj9aqmQ8I5XNNI9rh4nmmyDS\n"
+ "MfSkBp+rzxWFPHjl1TVptcG6RXzHeoeda0cDHNfLdnkviljHCYK/yuIBK2N+Bfmc\n"
+ "W3rH76/BzUzryx0wuCwmxt8kmGi6Pau3Ma3/f7HllOgBv5ZUJqqvzHoT6HQHp8Ia\n"
+ "0gKdeCcvb0W7/oKNfTt83lohKFkgb7DNRhiGeI08sAECgYEA78mdls9qb6Ir0CGA\n"
+ "nWIsF76iKoRe4Y/NJ2iM40DMhob01dFv5nGFAlq4LWefjZHyradHyFNgafM57bea\n"
+ "664q37mGgG7pWft/s67QudXfKAbDSWsW1Xd0iLvjSKOOL4edEG/7Gmp6NXzETkLz\n"
+ "nKwjQGHdrgTYRCremNBJWHM0qAECgYEA4YtGbKTrQC6jqe/yt3xHGASqL8vzUCPL\n"
+ "5rwvFSUEWSEudvIuajeA3KCNoYuh2FPK3qTgzpPZf3cC2DXprmXDfxznpWMegKLh\n"
+ "pWF0gEC21Y1Ot7JHfY2bKuoaSlA/iYsXHXBl07ETzxmNdQiFV8U0mQXz7E/7mrBl\n"
+ "iFZC6Sq0PjcCgYADUJw3G4LzLCDC7dOjWVoWsfH3+IB/SceiRdW8xoaNTYxQ8GZF\n"
+ "n0ghcjOdnRMdl+js8aUSZeStUkl4udMQcwXwtdXgLKhZMBrh1wbXqtc87GsCttJH\n"
+ "/TDFOyO3O1uZ2JwZQBMOmG48Ew97rX1EqzSJjVDNOQ/sUVNmdWquKFmQAQKBgHv/\n"
+ "9Wz/0rLLsYFZgWjtc6y5y9NRXuj9dTna1kvauSRDgOc2SNxuvXMO9i8NtKJZlxyH\n"
+ "K22Hjbltdevm4B3Ypv24p4afEwMICeTByqpEagDImrGV24Ykl12lrWST8AqvpLqz\n"
+ "s9gJ7+kZlFL2p1DVBBDpW+zdIGgwePHW8xx8NPJLAoGBAKPksJgw63JAHORvBjpm\n"
+ "DMztlAHs1sIWawALsW4m2/46bHzFxzVOMYeV1kp1AsnMKBCcSGAyAL5BzYlkMR/1\n"
+ "qU+C+5w8m5H+BCwldZVPEjD1nAQLrn1KA5Wuk8WddkgtSAwZ2jaIAb/9lUK5FwJS\n"
+ "J92yynqcyBnCMO6bEomTkbQL\n"
+ "-----END PRIVATE KEY-----";
private static final String SAMPLE_CA_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDcjCCAlqgAwIBAgIJAPk81/DAFH4kMA0GCSqGSIb3DQEBCwUAMGYxCzAJBgNV\n"
+ "BAYTAlVTMQswCQYDVQQIDAJXQTEQMA4GA1UEBwwHU2VhdHRsZTEXMBUGA1UECgwO\n"
+ "RmFjZWJvb2ssIEluYy4xDTALBgNVBAsMBEJ1Y2sxEDAOBgNVBAMMB1Rlc3QgQ0Ew\n"
+ "HhcNMTkwNTMwMjEwOTI5WhcNMjkwNTI3MjEwOTI5WjBmMQswCQYDVQQGEwJVUzEL\n"
+ "MAkGA1UECAwCV0ExEDAOBgNVBAcMB1NlYXR0bGUxFzAVBgNVBAoMDkZhY2Vib29r\n"
+ "LCBJbmMuMQ0wCwYDVQQLDARCdWNrMRAwDgYDVQQDDAdUZXN0IENBMIIBIjANBgkq\n"
+ "hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl2GoXs05KCd8Li+RD08/7taZu2aZGr5f\n"
+ "netg9ToU4Kh/xEl7FvrxH5CgMnlCMMQspRqg0uKR5EmynYBYO0OmRIvwkeI+yDiC\n"
+ "V0NtyYO8/vlvLNRl01ndw8SF7ZJHaA/bNVVLd6CCWdzfZAW0w4U2LZvxSPRLOksR\n"
+ "Wke+yFcIrtEhV+BSL2Pdvr/SYn+aEKdrw6fyrZkJ5XJdilc9V/FuXLNF9i9Tt+e2\n"
+ "7tQD3qiIch8S9SQKjkHDnWJa0BwJ8fs5963+IDHbr9diURD/m8bGFV5Z63YufDx6\n"
+ "qphqv5p1FG6SzFvZlyX1mjsm58y2xpTKRTr3kymFe7kfiFVKcIieFQIDAQABoyMw\n"
+ "ITAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF\n"
+ "AAOCAQEAXDL3uaHg0nCVL/sfuNQeycGNvJuxAZfZ+nSZrTjBtxU4fcdzE+zA3T/c\n"
+ "VvUvwKQFHYgEoOI9N+uLUEIVbadVxTIxpKMVV3Py+MxcRpHAeUGfpICkIhWYBdNc\n"
+ "FeLsM65+0xzdl1XDGLp2z55jDY2ALU03VTOC/MLGSSkcdwRpZYWyFRVtQe+OwRk2\n"
+ "oRfSHkhyXFQNziCS3ieMlrEE14G4F9r78BvP3wbsEjmpfFMx8fjO/B9o3I/Rm2iE\n"
+ "VKCp6Mtor82AS/bWYewGrvA0nDAtN6ENesMUP5lahcfqtqHuoMhnKAKTXf1EJtdD\n"
+ "vIfkYFDxXoXOdC8qwAc5iw1R6etUEQ==\n"
+ "-----END CERTIFICATE-----";
private static final String SAMPLE_CA_INTERMEDIATE_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDejCCAmKgAwIBAgIBATANBgkqhkiG9w0BAQUFADBmMQswCQYDVQQGEwJVUzEL\n"
+ "MAkGA1UECAwCV0ExEDAOBgNVBAcMB1NlYXR0bGUxFzAVBgNVBAoMDkZhY2Vib29r\n"
+ "LCBJbmMuMQ0wCwYDVQQLDARCdWNrMRAwDgYDVQQDDAdUZXN0IENBMB4XDTE5MDUz\n"
+ "MDIxMDkzMFoXDTI5MDUyNzIxMDkzMFowczELMAkGA1UEBhMCVVMxCzAJBgNVBAgM\n"
+ "AldBMRAwDgYDVQQHDAdTZWF0dGxlMRcwFQYDVQQKDA5GYWNlYm9vaywgSW5jLjEN\n"
+ "MAsGA1UECwwEQnVjazEdMBsGA1UEAwwUVGVzdCBDQSBJbnRlcm1lZGlhdGUwggEi\n"
+ "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4GLZ5Z8uX17UuNkGpNmzhBcxX\n"
+ "bJpvQukUqzNDUG0YJNSgNLt1N83Y9j4tnxOb4hOVL6edKuFoBjw/SarKrP02Tq2I\n"
+ "bcwf0bfUZhj6lK3qDDEtRR3/n51StF5wTG1k/1/0nBSqzheYlkv1u2vY/vL5UVcy\n"
+ "WdE0TyQ032EoIbkUKxmZfqw18vzbI7X6uAFrvGfozbVK3N6y7Clra4xwV0g7hzWY\n"
+ "HKWh9YUkfaMmJShKa43BkjM5gjM9Fk1/Fmlh1zU0OKFqVQgjt6WHfmJ/Zpax20ko\n"
+ "1wDMep/3Az7OcSbNPMCc0t7cEN3Im4Bt+d4zkOOLTyihK+pxIeGfgcfaN8vPAgMB\n"
+ "AAGjJjAkMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGGMA0GCSqG\n"
+ "SIb3DQEBBQUAA4IBAQAP5M2776T1+avuo7qIbFRM/ZYVR3G7E+F2XA9I+XWgOqDZ\n"
+ "2rQRTL1wDqT8ozenDp/9erh5NHsZHdetVmAesxeX+1Br+qOFm0rJoPWwjjtTVbzg\n"
+ "+uMRrHdBvesOe6QgbaCcBlnhEb6pU5Jiu7na8spCmwAb92OTZEM1p/b8yI0OfpwE\n"
+ "0xcK9Zmaeku8G1pBtXouviyxo6f7fOw6TV2SzTz3QnV0hLAgpoA9wKtmqL5SS2mX\n"
+ "cwwKxryGtDtHJXV+8CdrOk3rIvOHEP8lz5quejRcD0oHrGnUd1mThYct0hlV5R9v\n"
+ "DJdD+9D54VS6uGsknVPNVUSf+GK0iQnY3jf2Yn1F\n"
+ "-----END CERTIFICATE-----";
@Rule public TemporaryPaths temporaryPaths = new TemporaryPaths();
@Rule public ExpectedException expected = ExpectedException.none();
ArtifactCacheBuckConfig config_required;
ArtifactCacheBuckConfig config_optional;
private Path clientCertPath;
private Path clientKeyPath;
@Before
public void setUp() throws IOException {
clientCertPath = temporaryPaths.newFile("client.crt");
clientKeyPath = temporaryPaths.newFile("client.key");
Files.write(clientCertPath, SAMPLE_CLIENT_CERT.getBytes(Charsets.UTF_8));
Files.write(clientKeyPath, SAMPLE_CLIENT_KEY.getBytes(Charsets.UTF_8));
config_required =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString(),
"http_client_tls_cert_required = yes");
config_optional =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString(),
"http_client_tls_cert_required = no");
}
@Test
public void throwsIfCertIsEmpty() throws IOException {
ArtifactCacheBuckConfig config =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]", "http_client_tls_cert_required = yes");
expected.expect(HumanReadableException.class);
expected.expectMessage("Required option for certificate unset");
ClientCertificateHandler.fromConfiguration(config);
}
@Test
public void ignoreIfCertIsEmpty() throws IOException {
ArtifactCacheBuckConfig config =
ArtifactCacheBuckConfigTest.createFromText("[cache]", "http_client_tls_cert_required = no");
Assert.assertFalse(ClientCertificateHandler.fromConfiguration(config).isPresent());
}
@Test
public void throwsIfCertIsMissing() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage(String.format("Cannot read certificate file %s", clientCertPath));
Files.delete(clientCertPath);
ClientCertificateHandler.fromConfiguration(config_required);
}
@Test
public void ignoreIfCertIsMissing() throws IOException {
Files.delete(clientCertPath);
Assert.assertFalse(ClientCertificateHandler.fromConfiguration(config_optional).isPresent());
}
@Test
public void throwsIfX509CertIsInvalid() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage("No parsable X509 certificates found in");
Files.write(clientCertPath, "INVALID CERT".getBytes(Charsets.UTF_8));
ClientCertificateHandler.fromConfiguration(config_optional);
}
@Test
public void throwsIfKeyIsMissing() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage(String.format("Cannot read private key file %s", clientKeyPath));
Files.delete(clientKeyPath);
ClientCertificateHandler.fromConfiguration(config_required);
}
@Test
public void ignoreIfKeyIsMissing() throws IOException {
Files.delete(clientKeyPath);
Assert.assertFalse(ClientCertificateHandler.fromConfiguration(config_optional).isPresent());
}
@Test
public void throwsIfKeyIsEmpty() throws IOException {
ArtifactCacheBuckConfig config =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"http_client_tls_cert = " + clientCertPath.toString(),
"http_client_tls_cert_required = yes");
expected.expect(HumanReadableException.class);
expected.expectMessage("Required option for private key unset");
ClientCertificateHandler.fromConfiguration(config);
}
@Test
public void ignoreIfKeyIsEmpty() throws IOException {
ArtifactCacheBuckConfig config =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"http_client_tls_cert = " + clientCertPath.toString(),
"http_client_tls_cert_required = no");
Assert.assertFalse(ClientCertificateHandler.fromConfiguration(config).isPresent());
}
@Test
public void throwsIfHeaderOrTrailerAreMissing() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage("Expected BEGIN PRIVATE KEY/END PRIVATE KEY ");
Files.write(clientKeyPath, "TESTING".getBytes(Charsets.UTF_8));
ClientCertificateHandler.fromConfiguration(config_optional);
}
@Test
public void throwsIfBase64DecodingKeyFailsAndRequired() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage("Expected base64-encoded PKCS#8 key");
Files.write(
clientKeyPath,
"-----BEGIN PRIVATE KEY-----\nNOT BASE64\n-----END PRIVATE KEY-----\n"
.getBytes(Charsets.UTF_8));
ClientCertificateHandler.fromConfiguration(config_optional);
}
@Test
public void throwsIfKeyIsInvalid() throws IOException {
expected.expect(HumanReadableException.class);
expected.expectMessage(String.format("Client key at %s was not valid", clientKeyPath));
Files.write(
clientKeyPath,
("-----BEGIN PRIVATE KEY-----\n"
+ "MIIJKQIBAAKCAgEAtqFSEuAK1CbaBiKfybnYMSQp1tXmgi+WdrxRT5B9MnPxe9oo\n"
+ "-----END PRIVATE KEY-----\n")
.getBytes(Charsets.UTF_8));
ClientCertificateHandler.fromConfiguration(config_optional);
}
@Test
public void handlesCombinedKeyAndCert() throws IOException {
Files.write(
clientKeyPath, (SAMPLE_CLIENT_CERT + "\n" + SAMPLE_CLIENT_KEY).getBytes(Charsets.UTF_8));
String[] keyLines = SAMPLE_CLIENT_KEY.split("\n");
byte[] expectedPrivateKey =
Base64.getDecoder()
.decode(String.join("", Arrays.copyOfRange(keyLines, 1, keyLines.length - 1)));
String expectedPublic = "CN=Client, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";
Optional<ClientCertificateHandler> handler =
ClientCertificateHandler.fromConfiguration(config_required);
X509KeyManager keyManager = handler.get().getHandshakeCertificates().keyManager();
String alias = keyManager.getClientAliases("RSA", null)[0];
PrivateKey privateKey = keyManager.getPrivateKey(alias);
String subjectName = keyManager.getCertificateChain(alias)[0].getSubjectDN().getName();
Assert.assertArrayEquals(expectedPrivateKey, privateKey.getEncoded());
Assert.assertEquals(expectedPublic, subjectName);
Assert.assertFalse(handler.get().getHostnameVerifier().isPresent());
}
@Test
public void handlesCombinedKeyAndCertAndIntermediateCA() throws IOException {
Path identityPath = temporaryPaths.newFile("client.pem");
Path identityPathReverse = temporaryPaths.newFile("client_reverse.pem");
Files.write(
identityPath,
(SAMPLE_CLIENT_INTERMEDIATE_CERT
+ "\n"
+ SAMPLE_CA_INTERMEDIATE_CERT
+ "\n"
+ SAMPLE_CLIENT_INTERMEDIATE_KEY)
.getBytes(Charsets.UTF_8));
Files.write(
identityPathReverse,
(SAMPLE_CLIENT_INTERMEDIATE_KEY
+ "\n"
+ SAMPLE_CLIENT_INTERMEDIATE_CERT
+ "\n"
+ SAMPLE_CA_INTERMEDIATE_CERT)
.getBytes(Charsets.UTF_8));
String[] keyLines = SAMPLE_CLIENT_INTERMEDIATE_KEY.split("\n");
byte[] expectedPrivateKey =
Base64.getDecoder()
.decode(String.join("", Arrays.copyOfRange(keyLines, 1, keyLines.length - 1)));
Path[] testPaths = {identityPath, identityPathReverse};
for (Path testPath : testPaths) {
ArtifactCacheBuckConfig config =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"http_client_tls_key = " + testPath.toString(),
"http_client_tls_cert = " + testPath.toString(),
"http_client_tls_cert_required = yes");
String expectedPublic =
"CN=Client Intermediate, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";
String expectedIntermediateCa =
"CN=Test CA Intermediate, OU=Buck, O=\"Facebook, Inc.\", L=Seattle, ST=WA, C=US";
Optional<ClientCertificateHandler> handler =
ClientCertificateHandler.fromConfiguration(config);
X509KeyManager keyManager = handler.get().getHandshakeCertificates().keyManager();
String alias = keyManager.getClientAliases("RSA", null)[0];
PrivateKey privateKey = keyManager.getPrivateKey(alias);
String subjectName = keyManager.getCertificateChain(alias)[0].getSubjectDN().getName();
String intermediateCaSubjectName =
keyManager.getCertificateChain(alias)[1].getSubjectDN().getName();
Assert.assertArrayEquals(expectedPrivateKey, privateKey.getEncoded());
Assert.assertEquals(expectedPublic, subjectName);
Assert.assertEquals(expectedIntermediateCa, intermediateCaSubjectName);
Assert.assertFalse(handler.get().getHostnameVerifier().isPresent());
}
}
@Test
public void handlesEmptyConfig() throws IOException {
Optional<ClientCertificateHandler> handler1 =
ClientCertificateHandler.fromConfiguration(ArtifactCacheBuckConfigTest.createFromText());
Optional<ClientCertificateHandler> handler2 =
ClientCertificateHandler.fromConfiguration(
ArtifactCacheBuckConfigTest.createFromText(
"[cache]", "http_client_tls_key = " + clientKeyPath.toString()));
Optional<ClientCertificateHandler> handler3 =
ClientCertificateHandler.fromConfiguration(
ArtifactCacheBuckConfigTest.createFromText(
"[cache]", "http_client_tls_cert = " + clientCertPath.toString()));
Assert.assertFalse(handler1.isPresent());
Assert.assertFalse(handler2.isPresent());
Assert.assertFalse(handler3.isPresent());
}
}
|
{
"pile_set_name": "Github"
}
|
package extensions
import (
"testing"
common "github.com/rackspace/gophercloud/openstack/common/extensions"
"github.com/rackspace/gophercloud/pagination"
th "github.com/rackspace/gophercloud/testhelper"
"github.com/rackspace/gophercloud/testhelper/client"
)
func TestList(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
HandleListExtensionsSuccessfully(t)
count := 0
err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {
count++
actual, err := ExtractExtensions(page)
th.AssertNoErr(t, err)
th.CheckDeepEquals(t, common.ExpectedExtensions, actual)
return true, nil
})
th.AssertNoErr(t, err)
th.CheckEquals(t, 1, count)
}
func TestGet(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
common.HandleGetExtensionSuccessfully(t)
actual, err := Get(client.ServiceClient(), "agent").Extract()
th.AssertNoErr(t, err)
th.CheckDeepEquals(t, common.SingleExtension, actual)
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<style>
div {width: 50px; height: 50px;}
table {border-collapse:separate;
border: outset 1px black;
}
td {border: inset 1px black;}
</style>
</head>
<body>
<table><tr><td><div/></td></tr></table>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" ?>
<annotation>
<folder>widerface</folder>
<filename>24--Soldier_Firing_24_Soldier_Firing_Soldier_Firing_24_664.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>612</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>914</xmin>
<ymin>295</ymin>
<xmax>945</xmax>
<ymax>331</ymax>
</bndbox>
<lm>
<x1>920.165</x1>
<y1>309.768</y1>
<x2>932.004</x2>
<y2>309.54</y2>
<x3>919.482</x3>
<y3>317.509</y3>
<x4>919.254</x4>
<y4>322.062</y4>
<x5>929.5</x5>
<y5>322.973</y5>
<visible>0</visible>
<blur>0.41</blur>
</lm>
<has_lm>1</has_lm>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>493</xmin>
<ymin>141</ymin>
<xmax>529</xmax>
<ymax>187</ymax>
</bndbox>
<lm>
<x1>495.0</x1>
<y1>160.0</y1>
<x2>501.0</x2>
<y2>161.0</y2>
<x3>497.0</x3>
<y3>170.0</y3>
<x4>499.0</x4>
<y4>177.0</y4>
<x5>504.0</x5>
<y5>177.0</y5>
<visible>1</visible>
<blur>0.32</blur>
</lm>
<has_lm>1</has_lm>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>142</xmin>
<ymin>139</ymin>
<xmax>171</xmax>
<ymax>173</ymax>
</bndbox>
<lm>
<x1>147.906</x1>
<y1>153.531</y1>
<x2>160.156</x2>
<y2>153.531</y2>
<x3>153.375</x3>
<y3>160.094</y3>
<x4>149.875</x4>
<y4>166.875</y4>
<x5>160.156</x5>
<y5>165.562</y5>
<visible>1</visible>
<blur>0.53</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation>
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "test/unittests/compiler/instruction-selector-unittest.h"
namespace v8 {
namespace internal {
namespace compiler {} // namespace compiler
} // namespace internal
} // namespace v8
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
"""
Setup commands for PyGraphviz.
"""
# Copyright (C) 2006-2014 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Manos Renieris, http://www.cs.brown.edu/~er/
# Distributed with BSD license.
# All rights reserved, see LICENSE for details.
#
# Derived from http://www.niteoweb.com/blog/setuptools-run-custom-code-during-install
# Author: Maksym Markov <maksym.markov@gmail.com>
from setuptools.command.develop import develop
from setuptools.command.install import install
from setup_extra import get_graphviz_dirs
def add_extensions(command_subclass):
"""A decorator for classes subclassing one of the setuptools commands.
It modifies the run() method so that it prints a friendly greeting.
"""
orig_init = command_subclass.__init__
orig_initialize_options = command_subclass.initialize_options
orig_run = command_subclass.run
command_subclass.user_options.extend([('include-path=', None, 'path to graphviz include files.'),
('library-path=', None, 'path to graphviz library files.')])
def __init__(self, *args, **kws):
orig_init(self, *args, **kws)
def modified_initialize_options(self):
self.include_path = None
self.library_path = None
orig_initialize_options(self)
def modified_run(self):
# Add extension here
# if there is no library_path and include_path passed form command line then try identify them
if (not self.include_path) or (not self.library_path):
self.include_path, self.library_path = get_graphviz_dirs()
if self.distribution and self.distribution.ext_modules:
for m in self.distribution.ext_modules:
if m.name == 'pygraphviz._graphviz':
if self.include_path:
m.include_dirs.append(self.include_path)
if self.library_path:
m.library_dirs.append(self.library_path)
orig_run(self)
command_subclass.__init__ = __init__
command_subclass.initialize_options = modified_initialize_options
command_subclass.run = modified_run
return command_subclass
@add_extensions
class AddExtensionDevelopCommand(develop):
pass
@add_extensions
class AddExtensionInstallCommand(install):
pass
|
{
"pile_set_name": "Github"
}
|
package MusicBrainz::Server::Entity::PartialDate;
use Moose;
use Date::Calc;
use MusicBrainz::Server::Data::Utils qw( take_while );
use overload '<=>' => \&_cmp, fallback => 1;
has 'year' => (
is => 'ro',
isa => 'Maybe[Int]',
predicate => 'has_year',
);
has 'month' => (
is => 'ro',
isa => 'Maybe[Int]'
);
has 'day' => (
is => 'ro',
isa => 'Maybe[Int]'
);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
return $class->$orig( @_ ) unless @_ == 1;
my $info = shift;
if (!ref($info) && defined($info)
&& $info =~ /^ (?: (-?\d{1,4} | \?\?\?\?) (?: -? (\d{1,2} | \?\?) (?: -? (\d{1,2}) )? )? )? $/x)
{
$info = {};
$info->{year} = $1 if (defined $1 && $1 ne '????');
$info->{month} = $2 if ($2 && $2 ne '??' && $2 > 0);
$info->{day} = $3 if ($3 && $3 > 0);
return $class->$orig( $info );
}
$info = {} if !ref($info); # if parsing failed
my %info = map { $_ => $info->{$_} }
grep { defined($info->{$_}) } keys %$info;
return $class->$orig( %info );
};
has is_empty => (
is => 'ro',
isa => 'Bool',
lazy => 1,
builder => '_build_is_empty',
);
sub _build_is_empty {
my ($self) = @_;
return !(defined $self->year || $self->month || $self->day);
}
has format => (
is => 'ro',
isa => 'Str',
lazy => 1,
builder => '_build_format',
);
sub _build_format {
my ($self) = @_;
return '' if $self->is_empty;
my ($year, $month, $day, $result) =
($self->year, $self->month, $self->day, '');
if (defined $year) {
$result .= (sprintf '%04d', $year);
} elsif ($month || $day) {
$result .= '????';
}
if ($month) {
$result .= '-' . (sprintf '%02d', $month);
} elsif ($day) {
$result .= '-??';
}
$result .= '-' . (sprintf '%02d', $day) if $day;
return $result;
}
=attribute defined_run
Return all parts of the date that are defined, returning at the first
undefined value.
=cut
has defined_run => (
isa => 'ArrayRef[Int]',
lazy => 1,
builder => '_build_defined_run',
traits => ['Array'],
handles => {defined_run => 'elements'},
);
sub _build_defined_run {
my $self = shift;
my @components = ($self->year, $self->month, $self->day);
return [take_while { defined } @components];
}
sub _cmp
{
my ($a, $b) = @_;
# Stuff without a year sorts first too
return 0 if (!defined($a->year) && !defined($b->year));
return 1 if ( defined($a->year) && !defined($b->year));
return -1 if (!defined($a->year) && defined($b->year));
# Date::Calc can't understand years <= 0, so we special case this sorting
if ($a->year <= 0 || $b->year <= 0) {
return
$a->year <=> $b->year ||
(($a->month // 1) <=> ($b->month // 1)) ||
(($a->day // 1) <=> ($b->day // 1));
}
# We have years for both dates, we can now assume real sorting
my @begin = ($a->year, $a->month || 1, $a->day || 1);
my @end = ($b->year, $b->month || 1, $b->day || 1);
# Sort invalid dates first. Should make it obvious something is broken :)
return 0 if (!Date::Calc::check_date(@begin) && !Date::Calc::check_date(@end));
return 1 if (!Date::Calc::check_date(@end));
return -1 if (!Date::Calc::check_date(@begin));
my ($days) = Date::Calc::Delta_Days(@begin, @end);
return $days > 0 ? -1
: $days < 0 ? 1
: 0;
}
sub new_from_row {
my ($class, $row, $prefix) = @_;
$prefix //= '';
my %info;
$info{year} = $row->{$prefix . 'year'} if defined $row->{$prefix . 'year'};
$info{month} = $row->{$prefix . 'month'} if defined $row->{$prefix . 'month'};
$info{day} = $row->{$prefix . 'day'} if defined $row->{$prefix . 'day'};
return $class->new(%info);
}
sub TO_JSON {
my ($self) = @_;
return {
year => $self->year,
month => $self->month,
day => $self->day,
};
}
__PACKAGE__->meta->make_immutable;
no Moose;
1;
=head1 COPYRIGHT
Copyright (C) 2009 Lukas Lalinsky
Copyright (C) 2012 MetaBrainz Foundation
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
=cut
|
{
"pile_set_name": "Github"
}
|
"""
========
numpydoc
========
Sphinx extension that handles docstrings in the Numpy standard format. [1]
It will:
- Convert Parameters etc. sections to field lists.
- Convert See Also section to a See also entry.
- Renumber references.
- Extract the signature from the docstring, if it can't be determined otherwise.
.. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard
"""
import os, re, pydoc
from docscrape_sphinx import get_doc_object, SphinxDocString
from sphinx.util.compat import Directive
import inspect
def mangle_docstrings(app, what, name, obj, options, lines,
reference_offset=[0]):
cfg = dict(use_plots=app.config.numpydoc_use_plots,
show_class_members=app.config.numpydoc_show_class_members)
if what == 'module':
# Strip top title
title_re = re.compile(ur'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*',
re.I|re.S)
lines[:] = title_re.sub(u'', u"\n".join(lines)).split(u"\n")
else:
doc = get_doc_object(obj, what, u"\n".join(lines), config=cfg)
lines[:] = unicode(doc).split(u"\n")
if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \
obj.__name__:
if hasattr(obj, '__module__'):
v = dict(full_name=u"%s.%s" % (obj.__module__, obj.__name__))
else:
v = dict(full_name=obj.__name__)
lines += [u'', u'.. htmlonly::', '']
lines += [u' %s' % x for x in
(app.config.numpydoc_edit_link % v).split("\n")]
# replace reference numbers so that there are no duplicates
references = []
for line in lines:
line = line.strip()
m = re.match(ur'^.. \[([a-z0-9_.-])\]', line, re.I)
if m:
references.append(m.group(1))
# start renaming from the longest string, to avoid overwriting parts
references.sort(key=lambda x: -len(x))
if references:
for i, line in enumerate(lines):
for r in references:
if re.match(ur'^\d+$', r):
new_r = u"R%d" % (reference_offset[0] + int(r))
else:
new_r = u"%s%d" % (r, reference_offset[0])
lines[i] = lines[i].replace(u'[%s]_' % r,
u'[%s]_' % new_r)
lines[i] = lines[i].replace(u'.. [%s]' % r,
u'.. [%s]' % new_r)
reference_offset[0] += len(references)
def mangle_signature(app, what, name, obj, options, sig, retann):
# Do not try to inspect classes that don't define `__init__`
if (inspect.isclass(obj) and
'initializes x; see ' in pydoc.getdoc(obj.__init__)):
return '', ''
if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return
if not hasattr(obj, '__doc__'): return
doc = SphinxDocString(pydoc.getdoc(obj))
if doc['Signature']:
sig = re.sub(u"^[^(]*", u"", doc['Signature'])
return sig, u''
def initialize(app):
try:
app.connect('autodoc-process-signature', mangle_signature)
except:
monkeypatch_sphinx_ext_autodoc()
def setup(app, get_doc_object_=get_doc_object):
global get_doc_object
get_doc_object = get_doc_object_
app.connect('autodoc-process-docstring', mangle_docstrings)
app.connect('builder-inited', initialize)
app.add_config_value('numpydoc_edit_link', None, False)
app.add_config_value('numpydoc_use_plots', None, False)
app.add_config_value('numpydoc_show_class_members', True, True)
# Extra mangling directives
name_type = {
'cfunction': 'function',
'cmember': 'attribute',
'cmacro': 'function',
'ctype': 'class',
'cvar': 'object',
'class': 'class',
'function': 'function',
'attribute': 'attribute',
'method': 'function',
'staticmethod': 'function',
'classmethod': 'function',
}
for name, objtype in name_type.items():
app.add_directive('np-' + name, wrap_mangling_directive(name, objtype))
#------------------------------------------------------------------------------
# Input-mangling directives
#------------------------------------------------------------------------------
from docutils.statemachine import ViewList
def get_directive(name):
from docutils.parsers.rst import directives
try:
return directives.directive(name, None, None)[0]
except AttributeError:
pass
try:
# docutils 0.4
return directives._directives[name]
except (AttributeError, KeyError):
raise RuntimeError("No directive named '%s' found" % name)
def wrap_mangling_directive(base_directive_name, objtype):
base_directive = get_directive(base_directive_name)
if inspect.isfunction(base_directive):
base_func = base_directive
class base_directive(Directive):
required_arguments = base_func.arguments[0]
optional_arguments = base_func.arguments[1]
final_argument_whitespace = base_func.arguments[2]
option_spec = base_func.options
has_content = base_func.content
def run(self):
return base_func(self.name, self.arguments, self.options,
self.content, self.lineno,
self.content_offset, self.block_text,
self.state, self.state_machine)
class directive(base_directive):
def run(self):
env = self.state.document.settings.env
name = None
if self.arguments:
m = re.match(r'^(.*\s+)?(.*?)(\(.*)?', self.arguments[0])
name = m.group(2).strip()
if not name:
name = self.arguments[0]
lines = list(self.content)
mangle_docstrings(env.app, objtype, name, None, None, lines)
self.content = ViewList(lines, self.content.parent)
return base_directive.run(self)
return directive
#------------------------------------------------------------------------------
# Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5)
#------------------------------------------------------------------------------
def monkeypatch_sphinx_ext_autodoc():
global _original_format_signature
import sphinx.ext.autodoc
if sphinx.ext.autodoc.format_signature is our_format_signature:
return
print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..."
_original_format_signature = sphinx.ext.autodoc.format_signature
sphinx.ext.autodoc.format_signature = our_format_signature
def our_format_signature(what, obj):
r = mangle_signature(None, what, None, obj, None, None, None)
if r is not None:
return r[0]
else:
return _original_format_signature(what, obj)
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2014/deployment" AppPlatformVersion="8.1">
<DefaultLanguage xmlns="" code="en-US"/>
<App xmlns="" ProductID="{28df003b-40c3-4550-8000-103ad513bc6d}" Title="NControlDemo.WP81" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="NControlDemo.WP81 author" Description="Sample description" SDOptOut ="false" BackUpOptOut ="false" Publisher="NControlDemo.WP81" PublisherID="{6695e85a-9432-4de0-a26c-e4bb92fffe01}">
<IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
<Capabilities>
<Capability Name="ID_CAP_NETWORKING"/>
<Capability Name="ID_CAP_MEDIALIB_AUDIO"/>
<Capability Name="ID_CAP_MEDIALIB_PLAYBACK"/>
<Capability Name="ID_CAP_SENSORS"/>
<Capability Name="ID_CAP_WEBBROWSERCOMPONENT"/>
</Capabilities>
<Tasks>
<DefaultTask Name ="_default" NavigationPage="MainPage.xaml" ActivationPolicy="Resume"/>
</Tasks>
<Tokens>
<PrimaryToken TokenID="NControlDemo.WP81Token" TaskName="_default">
<TemplateFlip>
<SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
<Count>0</Count>
<BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
<Title>NControlDemo.WP81</Title>
<BackContent></BackContent>
<BackBackgroundImageURI></BackBackgroundImageURI>
<BackTitle></BackTitle>
<DeviceLockImageURI></DeviceLockImageURI>
<HasLarge></HasLarge>
</TemplateFlip>
</PrimaryToken>
</Tokens>
<ScreenResolutions>
<ScreenResolution Name="ID_RESOLUTION_WVGA"/>
<ScreenResolution Name="ID_RESOLUTION_WXGA"/>
<ScreenResolution Name="ID_RESOLUTION_HD720P"/>
</ScreenResolutions>
</App>
</Deployment>
|
{
"pile_set_name": "Github"
}
|
// ***************************************************************************
// *
// * Copyright (C) 2005 International Business Machines
// * Corporation and others. All Rights Reserved.
// * Tool: com.ibm.icu.dev.tool.cldr.LDML2ICUConverter.java
// * Source File: ../../../../ICU4J/cldr/common/main/sid.xml
// *
// ***************************************************************************
/**
* ICU <specials> source: ./xml/main/sid.xml
*/
sid{
Countries{
BR{"Brazil"}
CN{"China"}
DE{"Germany"}
ET{"Itiyoophiya"}
FR{"France"}
GB{"United Kingdom"}
IN{"India"}
IT{"Italy"}
JP{"Japan"}
RU{"Russia"}
US{"United States"}
}
Currencies{
BRL{
"BRL",
"Brazilian Real",
}
CNY{
"CNY",
"Chinese Yuan Renminbi",
}
ETB{
"$",
"ETB",
}
EUR{
"€",
"Euro",
}
GBP{
"£",
"British Pound Sterling",
}
INR{
"=0#Rs.|1#Re.|1<Rs.",
"Indian Rupee",
}
JPY{
"¥",
"Japanese Yen",
}
RUB{
"RUB",
"Russian Ruble",
}
USD{
"US$",
"US Dollar",
}
}
ExemplarCharacters{"[a-z]"}
Languages{
ar{"Arabic"}
de{"German"}
en{"English"}
es{"Spanish"}
fr{"French"}
hi{"Hindi"}
it{"Italian"}
ja{"Japanese"}
pt{"Portuguese"}
ru{"Russian"}
sid{"Sidaamu Afo"}
zh{"Chinese"}
}
LocaleScript{
"Latn",
}
Scripts{
Latn{"Latin"}
}
Version{"1.19"}
calendar{
gregorian{
AmPmMarkers{
"soodo",
"hawwaro",
}
DateTimeElements:intvector{
7,
1,
}
DateTimePatterns{
"h:mm:ss a",
"h:mm:ss a",
"h:mm:ss a",
"h:mm a",
"EEEE, MMMM dd, yyyy",
"dd MMMM yyyy",
"dd-MMM-yyyy",
"dd/MM/yy",
"{1} {0}",
}
dayNames{
format{
abbreviated{
"Sam",
"San",
"Mak",
"Row",
"Ham",
"Arb",
"Qid",
}
wide{
"Sambata",
"Sanyo",
"Maakisanyo",
"Roowe",
"Hamuse",
"Arbe",
"Qidaame",
}
}
stand-alone{
narrow{
"S",
"S",
"M",
"R",
"H",
"A",
"Q",
}
}
}
eras{
abbreviated{
"YIA",
"YIG",
}
}
monthNames{
format{
abbreviated{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
}
wide{
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
}
}
stand-alone{
narrow{
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
}
}
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# Encoding file: iso8859-15, single-byte
S
003F 0 1
00
0000000100020003000400050006000700080009000A000B000C000D000E000F
0010001100120013001400150016001700180019001A001B001C001D001E001F
0020002100220023002400250026002700280029002A002B002C002D002E002F
0030003100320033003400350036003700380039003A003B003C003D003E003F
0040004100420043004400450046004700480049004A004B004C004D004E004F
0050005100520053005400550056005700580059005A005B005C005D005E005F
0060006100620063006400650066006700680069006A006B006C006D006E006F
0070007100720073007400750076007700780079007A007B007C007D007E007F
0080008100820083008400850086008700880089008A008B008C008D008E008F
0090009100920093009400950096009700980099009A009B009C009D009E009F
00A000A100A200A320AC00A5016000A7016100A900AA00AB00AC00AD00AE00AF
00B000B100B200B3017D00B500B600B7017E00B900BA00BB01520153017800BF
00C000C100C200C300C400C500C600C700C800C900CA00CB00CC00CD00CE00CF
00D000D100D200D300D400D500D600D700D800D900DA00DB00DC00DD00DE00DF
00E000E100E200E300E400E500E600E700E800E900EA00EB00EC00ED00EE00EF
00F000F100F200F300F400F500F600F700F800F900FA00FB00FC00FD00FE00FF
|
{
"pile_set_name": "Github"
}
|
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../../out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"projects/integration-pwa-material/src/**/*.d.ts"
]
}
|
{
"pile_set_name": "Github"
}
|
require './spec/cases/helper'
process_diff do
Parallel.each((0..10).to_a, :in_processes => 5) { |a| a*2 }
end
|
{
"pile_set_name": "Github"
}
|
/*
* JSON lexer
*
* Copyright IBM, Corp. 2009
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#include "qstring.h"
#include "qlist.h"
#include "qdict.h"
#include "qint.h"
#include "qemu-common.h"
#include "json-lexer.h"
/*
* \"([^\\\"]|(\\\"\\'\\\\\\/\\b\\f\\n\\r\\t\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]))*\"
* '([^\\']|(\\\"\\'\\\\\\/\\b\\f\\n\\r\\t\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]))*'
* 0|([1-9][0-9]*(.[0-9]+)?([eE]([-+])?[0-9]+))
* [{}\[\],:]
* [a-z]+
*
*/
enum json_lexer_state {
ERROR = 0,
IN_DQ_UCODE3,
IN_DQ_UCODE2,
IN_DQ_UCODE1,
IN_DQ_UCODE0,
IN_DQ_STRING_ESCAPE,
IN_DQ_STRING,
IN_SQ_UCODE3,
IN_SQ_UCODE2,
IN_SQ_UCODE1,
IN_SQ_UCODE0,
IN_SQ_STRING_ESCAPE,
IN_SQ_STRING,
IN_ZERO,
IN_DIGITS,
IN_DIGIT,
IN_EXP_E,
IN_MANTISSA,
IN_MANTISSA_DIGITS,
IN_NONZERO_NUMBER,
IN_NEG_NONZERO_NUMBER,
IN_KEYWORD,
IN_ESCAPE,
IN_ESCAPE_L,
IN_ESCAPE_LL,
IN_ESCAPE_I,
IN_ESCAPE_I6,
IN_ESCAPE_I64,
IN_WHITESPACE,
IN_START,
};
#define TERMINAL(state) [0 ... 0x7F] = (state)
/* Return whether TERMINAL is a terminal state and the transition to it
from OLD_STATE required lookahead. This happens whenever the table
below uses the TERMINAL macro. */
#define TERMINAL_NEEDED_LOOKAHEAD(old_state, terminal) \
(json_lexer[(old_state)][0] == (terminal))
static const uint8_t json_lexer[][256] = {
/* double quote string */
[IN_DQ_UCODE3] = {
['0' ... '9'] = IN_DQ_STRING,
['a' ... 'f'] = IN_DQ_STRING,
['A' ... 'F'] = IN_DQ_STRING,
},
[IN_DQ_UCODE2] = {
['0' ... '9'] = IN_DQ_UCODE3,
['a' ... 'f'] = IN_DQ_UCODE3,
['A' ... 'F'] = IN_DQ_UCODE3,
},
[IN_DQ_UCODE1] = {
['0' ... '9'] = IN_DQ_UCODE2,
['a' ... 'f'] = IN_DQ_UCODE2,
['A' ... 'F'] = IN_DQ_UCODE2,
},
[IN_DQ_UCODE0] = {
['0' ... '9'] = IN_DQ_UCODE1,
['a' ... 'f'] = IN_DQ_UCODE1,
['A' ... 'F'] = IN_DQ_UCODE1,
},
[IN_DQ_STRING_ESCAPE] = {
['b'] = IN_DQ_STRING,
['f'] = IN_DQ_STRING,
['n'] = IN_DQ_STRING,
['r'] = IN_DQ_STRING,
['t'] = IN_DQ_STRING,
['/'] = IN_DQ_STRING,
['\\'] = IN_DQ_STRING,
['\''] = IN_DQ_STRING,
['\"'] = IN_DQ_STRING,
['u'] = IN_DQ_UCODE0,
},
[IN_DQ_STRING] = {
[1 ... 0xFF] = IN_DQ_STRING,
['\\'] = IN_DQ_STRING_ESCAPE,
['"'] = JSON_STRING,
},
/* single quote string */
[IN_SQ_UCODE3] = {
['0' ... '9'] = IN_SQ_STRING,
['a' ... 'f'] = IN_SQ_STRING,
['A' ... 'F'] = IN_SQ_STRING,
},
[IN_SQ_UCODE2] = {
['0' ... '9'] = IN_SQ_UCODE3,
['a' ... 'f'] = IN_SQ_UCODE3,
['A' ... 'F'] = IN_SQ_UCODE3,
},
[IN_SQ_UCODE1] = {
['0' ... '9'] = IN_SQ_UCODE2,
['a' ... 'f'] = IN_SQ_UCODE2,
['A' ... 'F'] = IN_SQ_UCODE2,
},
[IN_SQ_UCODE0] = {
['0' ... '9'] = IN_SQ_UCODE1,
['a' ... 'f'] = IN_SQ_UCODE1,
['A' ... 'F'] = IN_SQ_UCODE1,
},
[IN_SQ_STRING_ESCAPE] = {
['b'] = IN_SQ_STRING,
['f'] = IN_SQ_STRING,
['n'] = IN_SQ_STRING,
['r'] = IN_SQ_STRING,
['t'] = IN_SQ_STRING,
['/'] = IN_DQ_STRING,
['\\'] = IN_DQ_STRING,
['\''] = IN_SQ_STRING,
['\"'] = IN_SQ_STRING,
['u'] = IN_SQ_UCODE0,
},
[IN_SQ_STRING] = {
[1 ... 0xFF] = IN_SQ_STRING,
['\\'] = IN_SQ_STRING_ESCAPE,
['\''] = JSON_STRING,
},
/* Zero */
[IN_ZERO] = {
TERMINAL(JSON_INTEGER),
['0' ... '9'] = ERROR,
['.'] = IN_MANTISSA,
},
/* Float */
[IN_DIGITS] = {
TERMINAL(JSON_FLOAT),
['0' ... '9'] = IN_DIGITS,
},
[IN_DIGIT] = {
['0' ... '9'] = IN_DIGITS,
},
[IN_EXP_E] = {
['-'] = IN_DIGIT,
['+'] = IN_DIGIT,
['0' ... '9'] = IN_DIGITS,
},
[IN_MANTISSA_DIGITS] = {
TERMINAL(JSON_FLOAT),
['0' ... '9'] = IN_MANTISSA_DIGITS,
['e'] = IN_EXP_E,
['E'] = IN_EXP_E,
},
[IN_MANTISSA] = {
['0' ... '9'] = IN_MANTISSA_DIGITS,
},
/* Number */
[IN_NONZERO_NUMBER] = {
TERMINAL(JSON_INTEGER),
['0' ... '9'] = IN_NONZERO_NUMBER,
['e'] = IN_EXP_E,
['E'] = IN_EXP_E,
['.'] = IN_MANTISSA,
},
[IN_NEG_NONZERO_NUMBER] = {
['0'] = IN_ZERO,
['1' ... '9'] = IN_NONZERO_NUMBER,
},
/* keywords */
[IN_KEYWORD] = {
TERMINAL(JSON_KEYWORD),
['a' ... 'z'] = IN_KEYWORD,
},
/* whitespace */
[IN_WHITESPACE] = {
TERMINAL(JSON_SKIP),
[' '] = IN_WHITESPACE,
['\t'] = IN_WHITESPACE,
['\r'] = IN_WHITESPACE,
['\n'] = IN_WHITESPACE,
},
/* escape */
[IN_ESCAPE_LL] = {
['d'] = JSON_ESCAPE,
},
[IN_ESCAPE_L] = {
['d'] = JSON_ESCAPE,
['l'] = IN_ESCAPE_LL,
},
[IN_ESCAPE_I64] = {
['d'] = JSON_ESCAPE,
},
[IN_ESCAPE_I6] = {
['4'] = IN_ESCAPE_I64,
},
[IN_ESCAPE_I] = {
['6'] = IN_ESCAPE_I6,
},
[IN_ESCAPE] = {
['d'] = JSON_ESCAPE,
['i'] = JSON_ESCAPE,
['p'] = JSON_ESCAPE,
['s'] = JSON_ESCAPE,
['f'] = JSON_ESCAPE,
['l'] = IN_ESCAPE_L,
['I'] = IN_ESCAPE_I,
},
/* top level rule */
[IN_START] = {
['"'] = IN_DQ_STRING,
['\''] = IN_SQ_STRING,
['0'] = IN_ZERO,
['1' ... '9'] = IN_NONZERO_NUMBER,
['-'] = IN_NEG_NONZERO_NUMBER,
['{'] = JSON_OPERATOR,
['}'] = JSON_OPERATOR,
['['] = JSON_OPERATOR,
[']'] = JSON_OPERATOR,
[','] = JSON_OPERATOR,
[':'] = JSON_OPERATOR,
['a' ... 'z'] = IN_KEYWORD,
['%'] = IN_ESCAPE,
[' '] = IN_WHITESPACE,
['\t'] = IN_WHITESPACE,
['\r'] = IN_WHITESPACE,
['\n'] = IN_WHITESPACE,
},
};
void json_lexer_init(JSONLexer *lexer, JSONLexerEmitter func)
{
lexer->emit = func;
lexer->state = IN_START;
lexer->token = qstring_new();
lexer->x = lexer->y = 0;
}
static int json_lexer_feed_char(JSONLexer *lexer, char ch)
{
int char_consumed, new_state;
lexer->x++;
if (ch == '\n') {
lexer->x = 0;
lexer->y++;
}
do {
new_state = json_lexer[lexer->state][(uint8_t)ch];
char_consumed = !TERMINAL_NEEDED_LOOKAHEAD(lexer->state, new_state);
if (char_consumed) {
qstring_append_chr(lexer->token, ch);
}
switch (new_state) {
case JSON_OPERATOR:
case JSON_ESCAPE:
case JSON_INTEGER:
case JSON_FLOAT:
case JSON_KEYWORD:
case JSON_STRING:
lexer->emit(lexer, lexer->token, new_state, lexer->x, lexer->y);
case JSON_SKIP:
QDECREF(lexer->token);
lexer->token = qstring_new();
new_state = IN_START;
break;
case ERROR:
return -EINVAL;
default:
break;
}
lexer->state = new_state;
} while (!char_consumed);
return 0;
}
int json_lexer_feed(JSONLexer *lexer, const char *buffer, size_t size)
{
size_t i;
for (i = 0; i < size; i++) {
int err;
err = json_lexer_feed_char(lexer, buffer[i]);
if (err < 0) {
return err;
}
}
return 0;
}
int json_lexer_flush(JSONLexer *lexer)
{
return lexer->state == IN_START ? 0 : json_lexer_feed_char(lexer, 0);
}
void json_lexer_destroy(JSONLexer *lexer)
{
QDECREF(lexer->token);
}
|
{
"pile_set_name": "Github"
}
|
/*
* Name: Config file functions
*
* Purpose: Read info from casrc ou create one if it doesnt exist
*
* Author: Pedro de Oliveira <falso@rdk.homeip.net>
*
* Copyright (c) 2004-2011 Pedro de Oliveira ( falso@rdk.homeip-net )
*
* This file is part of aMule.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef CAS_CONFIGFILE_H
#define CAS_CONFIGFILE_H
#define IMG_TEXTLINES 7
#define MAX_CONF_ARG_LEN 120
typedef struct {
char font[MAX_CONF_ARG_LEN+1];
char source[MAX_CONF_ARG_LEN+1];
char template[MAX_CONF_ARG_LEN+1];
int x[IMG_TEXTLINES];
int y[IMG_TEXTLINES];
int enabled[IMG_TEXTLINES];
float size;
int img_type; // 0 = PNG, else = JPG
} CONF;
int writeconfig(void);
int readconfig(CONF *config);
#endif
/* // File_checked_for_headers */
|
{
"pile_set_name": "Github"
}
|
[
{
"date": "2022-01-01 00:00:00",
"start": "2022-01-01T00:00:00.000Z",
"end": "2022-01-02T00:00:00.000Z",
"name": "New Year's Day",
"type": "public",
"rule": "01-01",
"_weekday": "Sat"
},
{
"date": "2022-01-03 00:00:00",
"start": "2022-01-03T00:00:00.000Z",
"end": "2022-01-04T00:00:00.000Z",
"name": "New Year's Day (substitute day)",
"type": "public",
"substitute": true,
"rule": "substitutes 01-01 if saturday then next monday",
"_weekday": "Mon"
},
{
"date": "2022-03-27 00:00:00",
"start": "2022-03-27T00:00:00.000Z",
"end": "2022-03-27T23:00:00.000Z",
"name": "Mother's Day",
"type": "observance",
"rule": "easter -21",
"_weekday": "Sun"
},
{
"date": "2022-04-15 00:00:00",
"start": "2022-04-14T23:00:00.000Z",
"end": "2022-04-15T23:00:00.000Z",
"name": "Good Friday",
"type": "public",
"rule": "easter -2",
"_weekday": "Fri"
},
{
"date": "2022-04-17 00:00:00",
"start": "2022-04-16T23:00:00.000Z",
"end": "2022-04-17T23:00:00.000Z",
"name": "Easter Sunday",
"type": "public",
"rule": "easter",
"_weekday": "Sun"
},
{
"date": "2022-04-18 00:00:00",
"start": "2022-04-17T23:00:00.000Z",
"end": "2022-04-18T23:00:00.000Z",
"name": "Easter Monday",
"type": "public",
"rule": "easter 1",
"_weekday": "Mon"
},
{
"date": "2022-05-02 00:00:00",
"start": "2022-05-01T23:00:00.000Z",
"end": "2022-05-02T23:00:00.000Z",
"name": "Early May bank holiday",
"type": "public",
"rule": "1st monday in May",
"_weekday": "Mon"
},
{
"date": "2022-05-30 00:00:00",
"start": "2022-05-29T23:00:00.000Z",
"end": "2022-05-30T23:00:00.000Z",
"name": "Spring bank holiday",
"type": "public",
"rule": "1st monday before 06-01",
"_weekday": "Mon"
},
{
"date": "2022-12-15 00:00:00",
"start": "2022-12-15T00:00:00.000Z",
"end": "2022-12-16T00:00:00.000Z",
"name": "Homecoming Day",
"type": "public",
"rule": "12-15",
"_weekday": "Thu"
},
{
"date": "2022-12-25 00:00:00",
"start": "2022-12-25T00:00:00.000Z",
"end": "2022-12-26T00:00:00.000Z",
"name": "Christmas Day",
"type": "public",
"rule": "12-25",
"_weekday": "Sun"
},
{
"date": "2022-12-26 00:00:00",
"start": "2022-12-26T00:00:00.000Z",
"end": "2022-12-27T00:00:00.000Z",
"name": "Boxing Day",
"type": "public",
"rule": "12-26",
"_weekday": "Mon"
},
{
"date": "2022-12-27 00:00:00",
"start": "2022-12-27T00:00:00.000Z",
"end": "2022-12-28T00:00:00.000Z",
"name": "Christmas Day (substitute day)",
"type": "public",
"substitute": true,
"rule": "substitutes 12-25 if sunday then next tuesday",
"_weekday": "Tue"
}
]
|
{
"pile_set_name": "Github"
}
|
page_title: Getting started with Docker Hub
page_description: Introductory guide to getting an account on Docker Hub
page_keywords: documentation, docs, the docker guide, docker guide, docker, docker platform, virtualization framework, docker.io, central service, services, how to, container, containers, automation, collaboration, collaborators, registry, repo, repository, technology, github webhooks, trusted builds
# Getting Started with Docker Hub
This section provides a quick introduction to the [Docker Hub](https://hub.docker.com),
including how to create an account.
The [Docker Hub](https://hub.docker.com) is a centralized resource for working with
Docker and its components. Docker Hub helps you collaborate with colleagues and get the
most out of Docker.To do this, it provides services such as:
* Docker image hosting.
* User authentication.
* Automated image builds and work-flow tools such as build triggers and web
hooks.
* Integration with GitHub and BitBucket.
In order to use Docker Hub, you will first need to register and create an account. Don't
worry, creating an account is simple and free.
## Creating a Docker Hub Account
There are two ways for you to register and create an account:
1. Via the web, or
2. Via the command line.
### Register via the web
Fill in the [sign-up form](https://hub.docker.com/account/signup/) by
choosing your user name and password and entering a valid email address. You can also
sign up for the Docker Weekly mailing list, which has lots of information about what's
going on in the world of Docker.

### Register via the command line
You can also create a Docker Hub account via the command line with the
`docker login` command.
$ sudo docker login
### Confirm your email
Once you've filled in the form, check your email for a welcome message asking for
confirmation so we can activate your account.
### Login
After you complete the confirmation process, you can login using the web console:

Or via the command line with the `docker login` command:
$ sudo docker login
Your Docker Hub account is now active and ready to use.
## Next steps
Next, let's start learning how to Dockerize applications with our "Hello world"
exercise.
Go to [Dockerizing Applications](/userguide/dockerizing).
|
{
"pile_set_name": "Github"
}
|
Property Type Read-only Value
CONFIG.CLK_INTF.FREQ_HZ string false 10000000
CONFIG.CcmImp string false Distributed_Memory
CONFIG.ClockEnable string false false
CONFIG.Component_Name string false ipcore_mult_20b_20b_40b
CONFIG.ConstValue string false 129
CONFIG.InternalUser string false 0
CONFIG.MultType string false Parallel_Multiplier
CONFIG.Multiplier_Construction string false Use_Mults
CONFIG.OptGoal string false Area
CONFIG.OutputWidthHigh string false 39
CONFIG.OutputWidthLow string false 0
CONFIG.PipeStages string false 0
CONFIG.PortAType string false Signed
CONFIG.PortAWidth string false 20
CONFIG.PortBType string false Signed
CONFIG.PortBWidth string false 20
CONFIG.RoundPoint string false 0
CONFIG.SclrCePriority string false SCLR_Overrides_CE
CONFIG.SyncClear string false false
CONFIG.UseRounding string false false
CONFIG.Use_Custom_Output_Width string false false
CONFIG.ZeroDetect string false false
IPDEF string true xilinx.com:ip:mult_gen:12.0
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.run.util;
import com.android.tools.deploy.proto.Deploy;
import com.android.tools.deployer.ClassRedefiner;
import com.android.tools.deployer.DeployerException;
import com.android.tools.deployer.JdiBasedClassRedefiner;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.engine.JavaExecutionStack;
import com.intellij.debugger.engine.SuspendContextImpl;
import com.intellij.debugger.engine.events.DebuggerCommandImpl;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.impl.DebuggerSession;
import com.intellij.debugger.impl.DebuggerTask;
import com.intellij.debugger.impl.MultiProcessCommand;
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.ui.breakpoints.BreakpointManager;
import com.intellij.debugger.ui.breakpoints.StackCapturingLineBreakpoint;
import com.intellij.execution.configurations.RemoteConnection;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.xdebugger.XDebugSession;
import com.sun.jdi.VirtualMachine;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.IntStream;
/**
* Helper class for the deploy task to deal with the interactions with the IntelliJ debugger.
*
* In particular, all the debugger interaction within IntelliJ happens in the main thread. This class takes care of queuing up debugger
* task in that thread.
*/
public class DebuggerRedefiner implements ClassRedefiner {
private final Project project;
// This is the port that the IntelliJ talks to (port opended by ddmlib).
private final int debuggerPort;
private RedefineClassSupportState supportState = null;
public DebuggerRedefiner(Project project, int debuggerPort) {
this.project = project;
this.debuggerPort = debuggerPort;
}
@Override
public RedefineClassSupportState canRedefineClass() throws DeployerException{
if (supportState != null) {
return supportState;
}
MultiProcessCommand commands = new MultiProcessCommand();
DebuggerSession debuggerSession = getDebuggerSession(project, debuggerPort);
if (debuggerSession == null) {
throw DeployerException.noDebuggerSession(debuggerPort);
}
final AtomicReference<RedefineClassSupportState> result = new AtomicReference<>();
DebuggerCommandImpl task = new DebuggerCommandImpl() {
@Override
protected void action() {
result.set(canRedefineClassInternal(debuggerSession));
}
};
commands.addCommand(debuggerSession.getProcess(), task);
commands.run();
task.waitFor();
supportState = result.get();
return supportState;
}
private RedefineClassSupportState canRedefineClassInternal(DebuggerSession debuggerSession) {
// We use the IntelliJ abstraction of the debugger here since it is available.
DebuggerManagerThreadImpl.assertIsManagerThread();
DebugProcessImpl debugProcess = debuggerSession.getProcess();
VirtualMachineProxyImpl virtualMachineProxy = debugProcess.getVirtualMachineProxy();
// Simple case, debugger has the capability to all is good.
if (virtualMachineProxy.canRedefineClasses()) {
return new RedefineClassSupportState(RedefineClassSupport.FULL, null);
}
Collection<ThreadReferenceProxyImpl> allThreads = virtualMachineProxy.allThreads();
// Prioritize on MAIN_THREAD_RUNNING since this is the safest option.
for (ThreadReferenceProxyImpl thread : allThreads) {
if (thread.name().equals("main")) {
if (!thread.isSuspended()) {
return new RedefineClassSupportState(RedefineClassSupport.MAIN_THREAD_RUNNING, "main");
}
}
}
// Just hope for a thread on a breakpoint after.
for (ThreadReferenceProxyImpl thread : allThreads) {
if (thread.isAtBreakpoint()) {
RedefineClassSupportState state = new RedefineClassSupportState(RedefineClassSupport.NEEDS_AGENT_SERVER, thread.name());
return state;
}
}
return new RedefineClassSupportState(RedefineClassSupport.NONE, null);
}
@Override
public Deploy.SwapResponse redefine(Deploy.SwapRequest request) throws DeployerException {
MultiProcessCommand commands = new MultiProcessCommand();
DebuggerSession debuggerSession = getDebuggerSession(project, debuggerPort);
if (debuggerSession == null) {
throw DeployerException.noDebuggerSession(debuggerPort);
}
// A bit of a hack. Exceptions posted to background tasks ends up on the log only. We are going to gather
// as much of these as possible and present it to the user.
final AtomicReference<DeployerException> exception = new AtomicReference<>();
DebuggerCommandImpl task = new DebuggerCommandImpl() {
@Override
protected void action() {
try {
redefine(project, debuggerSession, request);
}
catch (DeployerException e) {
exception.set(e);
}
}
@Override
protected void commandCancelled() {
debuggerSession.setModifiedClassesScanRequired(true);
}
};
commands.addCommand(debuggerSession.getProcess(), task);
commands.run();
task.waitFor();
if (exception.get() != null) {
throw exception.get();
}
return Deploy.SwapResponse.newBuilder().setStatus(Deploy.SwapResponse.Status.OK).build();
}
private void redefine(Project project, DebuggerSession session, Deploy.SwapRequest request) throws DeployerException {
try {
disableBreakPoints(project, session);
VirtualMachine vm = session.getProcess().getVirtualMachineProxy().getVirtualMachine();
new JdiBasedClassRedefiner(vm, canRedefineClass()).redefine(request);
} finally {
enableBreakPoints(project, session);
}
}
/**
* Give a project return the DebugggerSession object associated with it at the port should a debugger is connected there. Otherwise,
* return null.
*/
public static DebuggerSession getDebuggerSession(Project project, int port) {
Collection<DebuggerSession> debuggerSessions = DebuggerManagerEx.getInstanceEx(project).getSessions();
for (DebuggerSession debuggerSession : debuggerSessions) {
RemoteConnection s = debuggerSession.getProcess().getConnection();
String address = s.getAddress();
int projectDebuggerPort = Integer.parseInt(address);
if (port == projectDebuggerPort) {
return debuggerSession;
}
}
return null;
}
/**
* @return True true if there is at least one debugger attached to a given project.
*/
public static boolean hasDebuggersAttached(Project project) {
return !DebuggerManagerEx.getInstanceEx(project).getSessions().isEmpty();
}
private static void disableBreakPoints(Project project, DebuggerSession debuggerSession) {
DebuggerManagerThreadImpl.assertIsManagerThread();
DebugProcessImpl debugProcess = debuggerSession.getProcess();
BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager();
breakpointManager.disableBreakpoints(debugProcess);
StackCapturingLineBreakpoint.deleteAll(debugProcess);
VirtualMachineProxyImpl virtualMachineProxy = debugProcess.getVirtualMachineProxy();
if (Registry.is("debugger.resume.yourkit.threads")) {
virtualMachineProxy.allThreads().stream()
.filter(ThreadReferenceProxyImpl::isResumeOnHotSwap)
.filter(ThreadReferenceProxyImpl::isSuspended)
.forEach(t -> IntStream.range(0, t.getSuspendCount()).forEach(i -> t.resume()));
}
}
private static void enableBreakPoints(Project project, DebuggerSession debuggerSession) {
DebuggerManagerThreadImpl.assertIsManagerThread();
DebugProcessImpl debugProcess = debuggerSession.getProcess();
BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager();
debugProcess.onHotSwapFinished();
DebuggerContextImpl context = debuggerSession.getContextManager().getContext();
SuspendContextImpl suspendContext = context.getSuspendContext();
if (suspendContext != null) {
JavaExecutionStack stack = suspendContext.getActiveExecutionStack();
if (stack != null) {
stack.initTopFrame();
}
}
final Semaphore waitSemaphore = new Semaphore();
waitSemaphore.down();
//noinspection SSBasedInspection
ApplicationManager.getApplication().invokeLater(() -> {
try {
if (!project.isDisposed()) {
breakpointManager.reloadBreakpoints();
debugProcess.getRequestsManager().clearWarnings();
debuggerSession.refresh(false);
XDebugSession session = debuggerSession.getXDebugSession();
if (session != null) {
session.rebuildViews();
}
}
}
finally {
waitSemaphore.up();
}
});
waitSemaphore.waitFor();
if (!project.isDisposed()) {
breakpointManager.enableBreakpoints(debugProcess);
StackCapturingLineBreakpoint.createAll(debugProcess);
}
}
}
|
{
"pile_set_name": "Github"
}
|
//
// FLEXWebViewController.m
// Flipboard
//
// Created by Ryan Olson on 6/10/14.
// Copyright (c) 2014 Flipboard. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FLEXWebViewController : UIViewController
- (id)initWithURL:(NSURL *)url;
- (id)initWithText:(NSString *)text;
+ (BOOL)supportsPathExtension:(NSString *)extension;
@end
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<title>Uses of Interface jdk.nashorn.api.tree.InstanceOfTree (Java SE 12 & JDK 12 )</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils.min.js"></script>
<!--[if IE]>
<script type="text/javascript" src="../../../../../../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script>
<![endif]-->
<script type="text/javascript" src="../../../../../../jquery/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jquery-migrate-3.0.1.js"></script>
<script type="text/javascript" src="../../../../../../jquery/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface jdk.nashorn.api.tree.InstanceOfTree (Java SE 12 & JDK 12 )";
}
}
catch(err) {
}
//-->
var pathtoroot = "../../../../../../";
var useModuleDirectories = true;
loadScripts(document, 'script');</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<header role="banner">
<nav role="navigation">
<div class="fixedNav">
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a id="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../index.html">Overview</a></li>
<li><a href="../../../../../module-summary.html">Module</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 & JDK 12</strong> </div></div>
</div>
<div class="subNav">
<ul class="navListSearch">
<li><label for="search">SEARCH:</label>
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">
</li>
</ul>
</div>
<a id="skip.navbar.top">
<!-- -->
</a>
<!-- ========= END OF TOP NAVBAR ========= -->
</div>
<div class="navPadding"> </div>
<script type="text/javascript"><!--
$('.navPadding').css('padding-top', $('.fixedNav').css("height"));
//-->
</script>
</nav>
</header>
<main role="main">
<div class="header">
<h2 title="Uses of Interface jdk.nashorn.api.tree.InstanceOfTree" class="title">Uses of Interface<br>jdk.nashorn.api.tree.InstanceOfTree</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<div class="useSummary">
<table>
<caption><span>Packages that use <a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">InstanceOfTree</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<th class="colFirst" scope="row"><a href="#jdk.nashorn.api.tree">jdk.nashorn.api.tree</a></th>
<td class="colLast">
<div class="block">
Nashorn parser API provides interfaces to represent ECMAScript source code
as abstract syntax trees (AST) and Parser to parse ECMAScript source scripts.</div>
</td>
</tr>
</tbody>
</table>
</div>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList">
<section role="region"><a id="jdk.nashorn.api.tree">
<!-- -->
</a>
<h3>Uses of <a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">InstanceOfTree</a> in <a href="../package-summary.html">jdk.nashorn.api.tree</a></h3>
<div class="useSummary">
<table>
<caption><span>Methods in <a href="../package-summary.html">jdk.nashorn.api.tree</a> with parameters of type <a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">InstanceOfTree</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colSecond" scope="col">Method</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../TreeVisitor.html" title="type parameter in TreeVisitor">R</a></code></td>
<th class="colSecond" scope="row"><span class="typeNameLabel">TreeVisitor.</span><code><span class="memberNameLink"><a href="../TreeVisitor.html#visitInstanceOf(jdk.nashorn.api.tree.InstanceOfTree,P)">visitInstanceOf</a></span>​(<a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">InstanceOfTree</a> node,
<a href="../TreeVisitor.html" title="type parameter in TreeVisitor">P</a> p)</code></th>
<td class="colLast">
<div class="block"><span class="deprecatedLabel">Deprecated, for removal: This API element is subject to removal in a future version.</span></div>
<div class="block">Visit 'instanceof' expression tree.</div>
</td>
</tr>
</tbody>
</table>
</div>
</section>
</li>
</ul>
</li>
</ul>
</div>
</main>
<footer role="contentinfo">
<nav role="navigation">
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a id="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a id="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../index.html">Overview</a></li>
<li><a href="../../../../../module-summary.html">Module</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../InstanceOfTree.html" title="interface in jdk.nashorn.api.tree">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><div style="margin-top: 14px;"><strong>Java SE 12 & JDK 12</strong> </div></div>
</div>
<a id="skip.navbar.bottom">
<!-- -->
</a>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</nav>
<p class="legalCopy"><small><a href="https://bugreport.java.com/bugreport/">Report a bug or suggest an enhancement</a><br> For further API reference and developer documentation see the <a href="https://docs.oracle.com/pls/topic/lookup?ctx=javase12.0.2&id=homepage" target="_blank">Java SE Documentation</a>, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.<br> <a href="../../../../../../../legal/copyright.html">Copyright</a> © 1993, 2019, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.<br>All rights reserved. Use is subject to <a href="https://www.oracle.com/technetwork/java/javase/terms/license/java12.0.2speclicense.html">license terms</a> and the <a href="https://www.oracle.com/technetwork/java/redist-137594.html">documentation redistribution policy</a>. <!-- Version 12.0.2+10 --></small></p>
</footer>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
gocc -a example.bnf
|
{
"pile_set_name": "Github"
}
|
/*
* zzllrr Mather
* Copyright by zzllrr since 2013. All rights reserved.
* zzllrr@gmail
* Released under MIT License
*/
/*
Integer 整数:字符串
+-×^封闭
÷ 数组[商,余数]
^
Decimal 有理小数:数组[整数字符串, 10的幂次, 循环节长度]
+-×÷ 封闭
^ 根数:数组
Frac (有理)分数:数组[分子,分母]
+-×÷ 封闭
^ 根数:数组
Root (有理元素)根数 (有理数的有理数幂次):
本质是二维数组:[(-1)^的有理幂次(默认0),有理系数(默认1),底数(正分数,默认1),分数幂次(正分数,默认1)]
本身是有理数,或 无理代数数
×÷^(有理幂(分母奇数)) 封闭
负数的^(有理幂(分母偶数)) 复数
+- 代数数
^(无理幂) 超越数
Num 上述任意数:
*/
var Integer={/*整数 (本质是字符串)
不直接支持 x,10的幂 这种写法(此时建议用Decimal.build.I)
*/
build:{//直接构造典型数列中的整数
Mersenne:function(p,Mp){/*返回梅森数 参数p是素数 Mp指定返回双重梅森数:2^(2^p-1)-1
*/
},
Prime:function(){//典型素数
},
},
is:{//布尔逻辑
b2:{//二元关系
"=":function(a,b){
return +(''+a==''+b)
},
"≠":function(a,b){
return +(''+a!=''+b)
},
">":function(a,b){
var A=''+a,B=''+b,n=A.length,m=B.length, aisNeg=A[0]=='-', bisNeg=B[0]=='-';
if(A==B || aisNeg && !bisNeg || aisNeg && bisNeg && n>m || !aisNeg && !bisNeg && m>n){
return 0
}
if(!aisNeg && bisNeg || aisNeg && bisNeg && m>n || !aisNeg && !bisNeg && n>m){
return 1
}
for(var i=0;i<n;i++){
if(A[i]!=B[i]){
return aisNeg ^ (A[i]>B[i]) //异或
}
}
},
"≥":function(a,b){
return +(''+a==''+b || Integer.is.b2['>'](a,b))
},
"<":function(a,b){
return Integer.is.b2['>'](b,a)
},
"≤":function(a,b){
return Integer.is.b2['≥'](b,a)
},
"|":function(a,b){/* a整除b
位数相差不多时,可以用试除法,求余数
否则尽量利用a的倍数的性质(充要条件)来判断
454646545 78798
*/
var A=''+a,B=''+b,Al=A.length,Bl=B.length;
if(B=='0' || A=='1' || A=='-1' || A==B){return 1}
if(A=='0' || Integer.is.b2['<'](B,A)){return 0}
if(A=='10'){return +(B.substr(-1)=='0')}//末位是0
//console.log(A,B);
if(/^10+$/.test(A)){return +/^0+$/.test(B.substr(1-A.length))}//末尾是连续的0
if(A=='2'){return 1-(+B.substr(-1) % 2)}//末位是偶数
if(A=='5'){return +/[05]/.test(B.substr(-1))}//末位是0或5
if(A=='3' || A=='9'){return Bl==1?(A=='3'?/[369]/.test(B):/[9]/.test(B)):Integer.is.b2['|'](A,Integer.oprs('+',B.split('')))}//各位和是倍数 A=An*9...9+An-1*9...9+...A2*9 + (An+An-1+...+A1)
if(A=='4' || A=='25'){return +B.substr(-2) % +A?0:1}//末两位数是倍数
if(A=='8' || A=='125'){return +B.substr(-3) % +A?0:1}//末三位数是倍数
if(A=='6'){return Integer.is.b2['|'](2,B) && Integer.is.b2['|'](3,B)}//
if(Bl<10){return +B%(+A)?0:1}//被除数较小时,直接用JS取余数判断整除
/*
方法1:奇数位(从左向右数)之和减去偶数位之和是倍数 A=An*9...9 + An-2*9...9 + + ... +_A4A3_*99 +(An + An-2 + ... + A2) - ( An-1 + An-3 + ... + A1 )
*/
if(/^10*1$/.test(A)){//
var A0=A.replace(/1/g,'').length;
return Integer.is.b2['|'](A, Integer.oprs('-',[B.substr(0,Bl-A0),B.substr(-A0)]))
}
if(/^1{2,}$/.test(A) || /^3{2,}$/.test(A) || /^9{2,}$/.test(A) ){//重位数
return Integer.is.b2['|'](A, Integer.oprs('+',ZLR(0,Integer.oprs('/',[Bl,Al])[1])+B).split(new RegExp('\\d{'+Al+'}','g')))
}
},
},
b1:{//一元关系
'0':function(n){//
return +(n[0]=='0')
},
'+':function(n){//是正数
return +(n[0]!='0' && n[0]!='-')
},
'-':function(n){//是负数
return +(n[0]=='-')
},
'2n+1':function(n){//是奇数
return +/[^02468]$/.test(n)
},
'2n':function(n){//是偶数
return +/[02468]$/.test(n)
},
'prime':function(n){/*
方法1:检验√n以内的所有质数,是否整除n
*/
}
}
},
fromStr:function(s){
if(/^-?\d+$/.test(s)){
return ''+s
}
return undefined
},
toStr:function(n,typ){//转成文本
/*
typ数字类型
整数 (默认)
. 小数
, 每3位数字一个逗号分隔符
%‰‱ 百(千万)分数
/ 分数
一 中文小写
一元 中文货币小写
壹圆 中文货币大写
10 科学计数法
1000 工程计数法
*/
return typ?Decimal.toStr([n,0], typ):n+'';
},
opr1:function(op,n,p){//一元运算 p是参数
var a=''+n,l=a.length,aisNeg=a[0]=='-';
if(op=='-' || op=='+'){/* 相反数 绝对值
*/
return aisNeg?a.substr(1):(op=='+'?'':'-')+a
}
if(op=='进制'){/* 10进制转p进制
返回数组,而不是字符串,是为了表示高进制(10个数字+26个字母,此时不够用)
JS 最多支持32进制, 另外 JS中2的幂,Math.pow(2,54) 再高次幂就失真了
*/
var b=''+p,A=[];
while(Integer.is.b2['≥'](a,b)){
var B=Integer.oprs('/',[a,b]);//得到余数
////console.log(a,b,A,B);
A.unshift(B[1]);
a=B[0]
}
A.unshift(a);
if(aisNeg){A.unshift('-')}
return A
}
if(op=='因式分解'){// 【只考虑正数】
}
if(op=='*0~9'){//一次性获得a的0~9倍,得到数组 【只考虑自然数】
if(a=='0'){
return copyA('0',10)//ZLR(0,10).split('')
}
if(/^10*$/.test(a)){
return [0].concat(zlrA2(seqsA('1~9'),ZLR(0,l-1)))
}
return ['0'].concat(Arrf(function(t){return Integer.oprs('+',[t,a])},['0'].concat(Array(8)),'cp1'))
}
if(op=='^2'){//求平方 【只考虑自然数】
/*平方尾数
1 1 1 1 1
2 4 6 6 6
3 9 1 1 1
4 6 6 6 6
5 5 5 5 5
6 6 6 6 6
7 9 1 1 1
8 4 6 6 6
9 1 1 1 1
3个吸引子
2,8 4 6 6 6 偶数最终到6
3,7 9 1 1 1 奇数(5除外)最终到1
5 5 5 5 奇数5最终到5
a^(2^m) m>=2时,尾数只能是0,1,5,6
立方尾数
1 1 1
2 8 2
3 7 3
4 4 4
5 5 5
6 6 6
7 3 7
8 2 8
9 9 9
1 ... 1
2 8 2 8 ...
3 7 3 7 ...
4 ... 4
5 ... 5
6 ... 6
9 ... 9
4方尾数(参见平方尾数)
奇数(5除外)最终到1
奇数5最终到5
偶数最终到6
5方尾数
到自身
6方尾数(同平方尾数)
1 1 1
2 4 6
3 9 1
4 6 6
5 5 5
6 6 6
7 9 1
8 4 6
9 1 1
7方尾数(同立方尾数)
*/
if(a=='0' || a=='1'){return a}
if(/^10*1$/.test(a)){//(10^t+1)^2=10^2t+2*10^t+1
return a.replace(/1$/,a.replace('1','2'))
}
if(/^9+$/.test(a)){//(10^t-1)^2=10^2t-2*10^t+1
return a.replace(/9$/,8+ZLR(0,l-1)+1)
}
if(/^10*2$/.test(a)){//(10^t+2)^2=10^2t+2*2*10^t+4
return a.replace(/2$/,a.replace('1',4).replace(2,4))
}
if(/^9+8$/.test(a)){//(10^t-2)^2=10^2t-2*2*10^t+4
return a.replace(/9$/,6+ZLR(0,l-1)+4)
}
if(/^10*3$/.test(a)){//(10^t+3)^2=10^2t+2*3*10^t+9
return a.replace(/3$/,a.replace('1',6).replace(3,9))
}
if(/^9+7$/.test(a)){//(10^t-3)^2=10^2t-2*3*10^t+9 继续推广有难度,因为二项式展开,最后一项已经不是个位数了。
return a.replace(/9$/,4+ZLR(0,l-1)+9)
}
return Integer.oprs('*',[a,a]);
}
if(op=='^3'){/*求立方 【只考虑自然数】
立方尾数
1 1 1
2 8 2
3 7 3
4 4 4
5 5 5
6 6 6
7 3 7
8 2 8
9 9 9
1 ... 1
2 8 2 8 ...
3 7 3 7 ...
4 ... 4
5 ... 5
6 ... 6
9 ... 9
*/
if(a=='0' || a=='1'){return a}
return Integer.oprs('*',[Integer.opr1('^2',a),a]);
}
if(op=='^1/2'){/*求开平方(向下取整)
*/
if(a=='0' || a=='1'){return a}
//(10^t+[123])^2=10^2t+2[123]*10^t+[123]^2
if(a=='121' || /^1(0*)2\1[1]$/.test(a)){
return a.replace(/2.+$/,'1')
}
if(a=='141' || /^1(0*)4\1[4]$/.test(a)){
return a.replace(/4.+$/,'2')
}
if(a=='161' || /^1(0*)6\1[9]$/.test(a)){
return a.replace(/6.+$/,'3')
}
//(10^t-[123])^2=10^2t-2[123]*10^t+[123]^2
if(/^9*80*1$/.test(a) && a.indexOf('8')==l/2-1){
return ZLR(9,l/2)
}
if(/^9*60*4$/.test(a) && a.indexOf('6')==l/2-1){
return ZLR(9,l/2-1)+'8'
}
if(/^9*40*9$/.test(a) && a.indexOf('4')==l/2-1){
return ZLR(9,l/2-1)+'7'
}
/*
a=b*10^2t
√a = √b *10^t
21334345323534534 ≈ 前15位 * 10^(l-15)
a=a1* 10^(l-15) + a2*10^(l-30) + a3*10^(l-45)
每15位一截,利用不等式,进行求近似值:
|√a-√b| = √(a+b-2√ab) <√(a+b) < √(a+b+2√ab) = √a+√b
*/
return Integer.oprs('*',[a,a]);
}
if(op=='数根'){/*求数根 digital root 反复求各位数之和,迭代到结果为个位数为止时的数 【只考虑自然数】
参数p,返回数组[最终结果,中间结果数组]
*/
var A=['',[]];
while(l>1){
a=Integer.oprs('+',a.split(''));
l=a.length;
if(p){//计算过程
A[1].push(a);
//console.log(A[1])
}
}
if(p){
A[0]=a;
//console.log(A);
return A
}else{
return a
}
}
},
oprs:function(op,arr,p){//多元运算 p是参数
//op 可以是单个运算符,也可以是同级运算符数组
var aA=arr.join().split(','),al=aA.length, aA0=aA[0],aA1=aA[1];
if(al<2){
return aA0
}
var aisNeg=aA0[0]=='-', bisNeg=aA1[0]=='-', islastNeg=aA[al-1][0]=='-', negCnt=aA.filter(function(t){return t[0]=='-'}).length;
if(isArr(op)){//op是数组时,依次执行(这里不考虑正负数先抵消的优化,Mfn中才考虑)
var x=aA0;
for(var i=1;i<al;i++){
x=Integer.oprs(op[i-1],[x,aA[i]])
}
return x
}
if(op=='+'){//加法
if(al>2){/* 暂不实现算法:参数p是策略:按顺序(默认),'加减分离', '',
而是死算
*/
return Integer.oprs('+',[Integer.oprs('+',aA.slice(0,al-1)),aA[al-1]])
}
if(aA0=='0'){
return aA1
}
if(aA1=='0'){
return aA0
}
if(aisNeg && bisNeg){
return '-'+Integer.oprs('+',[aA0.substr(1),aA1.substr(1)])
}else if(aisNeg ^ bisNeg){
return Integer.oprs('-',[aA[+aisNeg],aA[+bisNeg].substr(1)])
}
//下面算法仅支持两个正数相加
if(BigInt){
return BigInt(aA0)+BigInt(aA1)+''
}
var agb=Integer.is.b2['>'](aA0,aA1),a=agb?aA0:aA1,b=agb?aA1:aA0,al=a.length,bl=b.length,A=a.split('');
////console.log(a+' + '+b+' = ?');
for(var i=0;i<bl;i++){
var bi=+b[bl-i-1],ai=al-i-1;
if(bi){
var si=bi+(+A[ai]);
// //console.log('si='+si);
if(si>9){
A[ai]=(''+si).substr(-1);
if(i==bl-1){
if(ai<1){
// //console.log('已经到达b的第1位,且a也达到第1位 '+a+' + '+b+' = ' +(''+si)[0]+A.join(''));
return (''+si)[0]+A.join('')
}
return Integer.oprs('+',[A.slice(0,ai).join(''),(''+si)[0]])+A.slice(ai).join('')
// return Integer.oprs('+',[A.slice(0,ai).join(''),(''+si).substr(0,(''+si).length-1)])+A.slice(ai).join('')
}else{
var ai1=+A[ai-1]+(+(''+si)[0]);
// //console.log('前一位' + A[ai-1]+ ' + '+(''+si)[0] + ' == '+ai1);
if(ai1>9){
////console.log('ai1 = '+ai1+' 替换前2位,A[ai-2]为'+(+A[ai-2]+(+(''+ai1)[0])));
return Integer.oprs('+',[A.slice(0,ai).join(''),(''+si)[0],b.substr(0,bl-i-1)])+A.slice(ai).join('')
}else{
A[ai-1]=ai1;
}
}
}else{
////console.log('si<9 直接替换A[ai] '+ A[ai]+' -> '+si);
A[ai]=si;
}
}
}
// //console.log(a+' + '+b+' = ' +A.join(''));
return A.join('')
}
if(op=='-'){//减法 暂不考虑al>2
if(BigInt){
return BigInt(aA0)-BigInt(aA1)+''
}
if(aA0==aA1){return '0'}
var agb=Integer.is.b2['>'](aA0,aA1);
if(!aisNeg && bisNeg){return Integer.oprs('+',[aA0,aA1.substr(1)])} //+ -
if(!aisNeg && !bisNeg && !agb){return '-'+Integer.oprs('-',[aA1,aA0])} //+ < +
if(aisNeg && !bisNeg){return '-'+Integer.oprs('+',[aA0.substr(1),aA1])} //- +
if(aisNeg && bisNeg && !agb){return '-'+Integer.oprs('-',[aA0.substr(1),aA1.substr(1)])} //- < -
if(aisNeg && bisNeg && agb){return Integer.oprs('-',[aA1.substr(1),aA0.substr(1)])} //- > -
var a=aA0,b=aA1,al=a.length,bl=b.length,A=a.split('');
for(var i=0;i<bl;i++){
var bi=+b[bl-i-1];
////console.log(bi);
if(bi){
var si=+A[al-i-1]-bi;
////console.log(bi,si);
if(si<0){
// //console.log(si);
si+=10;
A[al-i-1]=si;
////console.log(si);
////console.log(A.slice(al-i-1).join(''));
if(i==bl-1){
return Integer.oprs('-',[A.slice(0,al-i-1).join(''),'1']).replace(/^0+/,'')+A.slice(al-i-1).join('')
}else{
return Integer.oprs('-',[A.slice(0,al-i-1).join(''),Integer.oprs('+',[b.slice(0,bl-i-1),'1'])]).replace(/^0+/,'')+A.slice(al-i-1).join('')
}
}else{
A[al-i-1]=si;
}
}
}
// //console.log('- ',A);
return A.join('').replace(/^0+/,'')
}
if(op=='*1'){//仅计算乘数b是个位数的情况,仅限2元运算 【只考虑非负数a】
if(BigInt){
return BigInt(aA0)*BigInt(aA1)+''
}
var b=+aA[1];
if(!b){
return '0'
}
var n=aA0.length,A=aA0.split(''),B=new Array(n);
for(var i=0;i<n;i++){
var ai=+A[n-i-1];
////console.log('A='+A);
var si=b*ai;
if(B[n-i-1]){
si+=B[n-i-1];
}
if(si>9){
if(i==n-1){
////console.log(A);
return si+A.slice(1).join('')
}else{
////console.log(si,A);
A[n-i-1]=(''+si).substr(-1);
////console.log('A ='+A);
B[n-i-2]=+(''+si)[0];
////console.log(B[n-i-2]);
////console.log(' A='+A);
}
}else{
A[n-i-1]=si;
}
}
return A.join('')
}
if(op=='*'){//乘法
if(aA.indexOf('0')>-1){return '0'}
if(al>2){
return Integer.oprs('*',[Integer.oprs('*',aA.slice(0,al-1)),aA[al-1]]) //左结合
//return Integer.oprs('*',[aA0,Integer.oprs('*',aA.slice(1))]) //右结合
}
if(BigInt){
if(/[a-z]/.test(aA0)||/[a-z]/.test(aA1)){
return aA0+''+aA1
}
return BigInt(aA0)*BigInt(aA1)+''
}
if(aisNeg || bisNeg){return (aisNeg && bisNeg?'':'-')+Integer.oprs('*',[aisNeg?aA0.substr(1):aA0, bisNeg?aA1.substr(1):aA1])}
var n0=aA0.length,n1=aA1.length,m0=aA0.match(/[^0]/g).length,m1=aA1.match(/[^0]/g).length,
a=m0>m1?aA0:aA1,b=m0>m1?aA1:aA0,an=a.length,bn=b.length,A=[],B=Integer.opr1('*0~9',a);
for(var i=0;i<bn;i++){
var bi=+b[bn-i-1];
if(bi){
A.push(B[bi]+ZLR(0,i));//计算被乘数与单个数字的乘积,并补充末0
//A.unshift(Integer.oprs('*1',[a,bi+''])+ZLR(0,i))
}
}
return Integer.oprs('+',A)
}
if(op=='/'){/*返回数组[商,余数],仅限2元运算
带余除法 a= b p + r
a=(-b)(-p) + r
-a= b (-p) + (-r)
-a=(-b) p + (-r)
与JS中运算符%规则一致
*/
var a=aA0,b=aA1;
if(b=='1' || b=='0'){return [a,'0']} //除数为0时,认为是1
if(a==b){return ['1','0']}
if(negCnt){
// //console.log(a,b,aisNeg?a.substr(1):a, bisNeg?b.substr(1):b);
var A=Integer.oprs('/',[aisNeg?a.substr(1):a, bisNeg?b.substr(1):b]);
return [(negCnt>1 || a[0]=='0'?'':'-')+a[0],(!aisNeg && bisNeg?'':'-')+a[1]]
}
if(Integer.is.b2['<'](a,b)){return ['0',a]}
if(BigInt){
return [BigInt(aA0)/BigInt(aA1)+'',BigInt(aA0) % BigInt(aA1)+'']
}
var n0=a.length,n1=b.length,q='',a0=a.substr(0,n1),bI=[];
/*
方法1【累减法】:被除数减去除数(减法若干次,次数是商),直至余数小于除数
方法2【试商法】:被除数减去除数的倍数(0~9倍),得到商的各位数字(各位最多做乘法9次+1次减法,迭代次数是商的位数)和最终余数
*/
for(var i=1;i<10;i++){
bI.push(Integer.oprs('*1',[b,i]));
}
for(var i=n1;i<n0+1;i++){
////console.log(i,n0+1);//Integer.oprs('/',['1232402135','10334302'])
if(Integer.is.b2['>'](b,a0)){
if(q){q+='0'}
}else{
var a0n=a0.length;
for(var j=9;j>0;j--){
var bj=bI[j-1];
// //console.log('j='+j+', bj='+bj);
if(bj==a0){
q+=j;
a0='';
// //console.log('bj==a0, q='+q+', a0='+a0);
break;
}
if(Integer.is.b2['<'](bj,a0)){
q+=j;
// //console.log(a0,bj);
a0=Integer.oprs('-',[a0,bj]);
// //console.log('bj<a0 q='+q+', a0='+a0);
break;
}
}
}
// //console.log(i,a[i-1],n0);
if(i==n0){
return [q,a0||'0']
}
if(a0=='0'){
a0=a[i]
}else{
a0+=a[i];
}
// //console.log(i,'a0='+a0);
}
}
if(op=='^p'){/* a^p = a^b 素数p次幂(p>2)
p=q+1 ,对q进行因式分解求幂
p=s1^k1 * s2^k2 * s3^k3 + t1^j1
算法:对于p=2,直接算平方
对于其他素数p,用a的p-1次幂,乘以a
*/
if(BigInt){
return BigInt(aA0) ** BigInt(aA1)+''
}
var b=aA1;
if(b=='2'){
//return Integer.oprs('2^',[aA0,aA1])
return Integer.oprs('*',[aA0,aA0])
}
return Integer.oprs('*',[Integer.oprs('^',[aA0,Integer.oprs('-',[b,1])]),aA0])
}
if(op=='^'){/*幂 【仅考虑幂是自然数的情况】
从a,a^2开始,迭代求幂
迭代函数:
f(x)=x*x
f(x)=x*a
f(x)=x*a^2
f(x)=x*a^i(i是已计算出的幂)
b是2的n次幂时,a^b=a^(2^n)=(...((a^2)^2)^2...)^2 至少做n次乘法(平方)
b是2^n+1时,至少做n+1次乘法
b是2^n+2时,至少做n+1次乘法
b是2^n+2+1时,至少做n+2次乘法(a^3未知时),做n+1次乘法(a^3已知时)
b是2^n+2^2时,至少做n+1次乘法
b是2^n+2^2+1时,至少做n+2次乘法
b是2^n+2^2+2时,至少做n+2次乘法
b是2^n+2^2+2+1时,至少做n+3次乘法
b是2^n+2^3时,至少做n+1次乘法
b是2^n+2^3+1时,至少做n+2次乘法
b转成2进制,至少做(取第1位1对应的2的幂次k + 其余1的个数,介于k~2k之间)次乘法,
但这种乘法次数不一定是最少的,事实上,可以对b做因式分解,15=3*5 2+3(因式分解方法)<6(二进制方法) 15二进制2^3+2^2+2+1
b因式分解:f1f2...fk (((b)^f1)^f2)^f3... 共需乘法f1+f2+f3+..+fk - k次
由于xy-1 > x-1 + y-1 (因为(x-1)(y-1)>0) 因此因式分解越细越好
*/
var a=aA0,b=aA1;
if(a=='0'){return '0'}//这里不考虑0的0次幂
if(a=='1'){return '1'}
if(b=='0'){return '1'}
if(b=='1'){return a}
if(aA.indexOf('0')>-1){return Integer.oprs('^',aA.slice(0,aA.indexOf('0')-1))}
if(aA.indexOf('1')>-1){return Integer.oprs('^',aA.slice(0,aA.indexOf('1')))}
// if(al==1){return aA0} 可省略
if(al>2){
return Integer.oprs('^',aA.slice(0,al-2).concat(Integer.oprs('^',aA.slice(al-2))))
}
if(a[0]=='-'){
var evenb=/[02468]$/.test(b);
return (evenb?'':'-')+Integer.oprs('^',[a.substr(1),b])
}
/*
if(/^10+$/.test(a)){//10的b次幂 下面用+b,默认为幂次不会很高,否则结果太大,计算不了
return '1'+ZLR(0,(+b)*(a.length-1));
}
*/
if(/0+$/.test(a)){//末尾含0的b次幂
return Integer.oprs('^',[a.replace(/0+$/,''),b])+ZLR(0,(+b)*(a.length-a.replace(/0+$/,'').length));
}
// //console.log(b);
if(b=='2'){
return Integer.oprs('*',[a,a]);
}
if(BigInt){
return BigInt(aA0) ** BigInt(aA1)+''
}
var f=(''+factor(b)).split('×'),fl=f.length,x=a;
//console.log('aA = ',aA);
//console.log(f, b, factor(b));
for(var i=0;i<fl;i++){
x=Integer.oprs('^p',[x,f[i]])
}
return x
}
if(op=='2^'){/* a^(2^b) 反复求平方 (迭代平方b次)
当a=2时,结果是费马数-1
目前已知最大的梅森素数M49 = 2^74207281-1 约等于2^(2^26.14505741099363)-1 位数有22,338,618
计算极限: Integer.oprs('2^',[2,13]).length 2467 部分电脑上b是13即不可算出结果,出现 Uncaught RangeError: Maximum call stack size exceeded(…)
[3,13] .length 3909
[4~14,11].length -28681-
[248,10].length
Integer.oprs('2^',[179,5]).length ----74 Integer.oprs('2^',[181,5]).length 83 也异常
*/
var a=aA0,b=aA1;
if(a=='0' || a=='1' || b=='0'){return a}
if(/^10+$/.test(a)){
return '1'+ZLR(0,Integer.oprs('*',[Integer.oprs('^',[2,b]),a.length-1]));
}
while(b!='0'){
//a=Integer.opr1('^2',a);
a=Integer.oprs('*',[a,a]);
////console.log(b+ ' !!! '+a);
b=Integer.oprs('-',[b,1]);
}
return a
//return Arrf(function(t){return Integer.opr1('^2',t)},new Array(b),'cp1') //返回每一次求平方的结果 数组
}
if(op=='%'){/* a%b 求余数
算法:
比较长度:a小,则返回a
用数论方法判断是否a/b 整除及余数
*/
if(BigInt){
return BigInt(aA0) % BigInt(aA1)+''
}
return (+aA0) % (+aA1)+''
}
if(op=='^%'){/* a^b mod p 求幂余数 仅限2元运算
p是素数情况下,
a^p≡a (mod p)
a^(p-1)≡1 (mod p) 费马小定理
a^b≡a^(k(p-1)+t)≡a^(1+t) (mod p)
*/
var a=aA0,b=aA1;
if(a=='0' || a=='1'){return a}
if( b=='0'){return '1'}
if(isPrime(p)){
if(b==p){
return Integer.oprs('%',[a,p])
}
if(b==Integer.oprs('-',[p,1])){
return '1'
}
//if(Integer.is.b2['>'](b,p-1)){
b=Integer.oprs('%',[b,Integer.oprs('-',[p,1])]);
return Integer.oprs('^%',[a,Integer.oprs('+',[b,1])],p)
}else{
Integer.oprs('%',[Integer.oprs('^',[a,b]),p]);
}
}
if(op=='^/'){/*返回幂余数组 [幂次k, 系数c] a=cb^k [k,c] 仅限(正整数)2元运算
a<b 或者 a中不含因子b(不能被b整除) a=ab^0 返回[0,a]
a=b a=1b^1 返回[1,1]
a=b^k a=1b^k 返回[k,1]
ln a = ln c + k ln b 类似于除法
*/
var a=aA0,b=aA1,r=1,k=0;
while(r){
var qr=Integer.oprs('/',[a,b]);
if(qr[1]=='0'){
a=qr[0];
k=Integer.oprs('+',[k,1]);
}else{
break
}
}
return [k,a]
}
}
}, Decimal={/*小数(有理数,分数) 本质是数组:[整数(不含尾0), 尾0数(负数), 循环节长度]
有限小数(化成最简分数时,分母没有2、5之外的因数) 除法不封闭
无限小数(无限循环小数化成最简分数时,分母有2、5之外的因数,无限不循环是无理数)
*/
build:{
I:function(t,b){//长整数(本质是数组)t是数字串, b是进制(默认为空,是10)
var s=''+((b||10) == 10?t:parseInt(t,b));
s=s.replace(/^-0$/,0);
var i=''+(s.replace(/0+$/,'')||0), A=[i,i=='0'?0:s.replace(/.*[^0]/,'').length,0];
A.type='Decimal';A.toStr=function(p){return Decimal.toStr(this,p)};
return A
},
D:function(t,m,len){//小数(本质是数组)t是数字串(可以含小数点,或者百分号等后缀), m是后缀10的幂次 %(-2)‰(-3)‱(-4) len是循环节长度
//t中可以含2个小数点(此时是无限循环小数的写法,例如:0.13.3),其中第2个小数点后数字表示循环节
var s=(''+t).replace(/[%‰‱]$/,''),d=+m||0;
if(s.split('.').length>2){//含2个小数点
return Decimal.build.D(s.replace(/\.\d+$/,''),0,s.split('.')[2].length)
}
if(/\./.test(s)){
s=s.replace(/0+$/,'');
d+=-s.split('.')[1].length;
s=s.replace('.','').replace(/^([-]?)0+/,'$1');
}
//console.log(s,d);
if(/[%‰‱]$/.test(t)){
d-='01%‰‱'.indexOf((''+t).substr(-1));
}
var i=''+(s.replace(/0+$/,'')||0), A=[i,i=='0'?0:d+(s.match(/0+$/)||[''])[0].length,len||0];
A.type='Decimal';A.toStr=function(p){return Decimal.toStr(this,p)};
return A
},
'10':function(t){//t是科学计数法字符串 Decimal.build['10']('-2.8×10^(-3)')
return Decimal.build.D(t.replace(/×10\^.+/,''), /×10\^/.test(t)?wrapTrim(t.replace(/.+×10\^/,'')):0)
},
F:function(t){//t是分数字符串a/b或数组 化成小数对象
var s=''+t;
if(/[\/,]/.test(s)){
return Frac.opr1('.',s.split(/[\/,]/))
}else{
return Decimal.build.I(s)
}
},
JS:function(t){//JS表达式,得到有限小数(精度不可控!)
return Decimal.build.D(eval(t))
}
},
is:{//布尔逻辑
b2:{//二元关系
"=":function(A,B){
return +(A.join()==B.join())
},
"≠":function(A,B){
return +(A.join()!=B.join())
},
">":function(A,B){
return Frac.is.b2['>'](Frac.build.D(A),Frac.build.D(B))
},
"≥":function(A,B){
return Frac.is.b2['≥'](Frac.build.D(A),Frac.build.D(B))
},
"<":function(A,B){
return Frac.is.b2['<'](Frac.build.D(A),Frac.build.D(B))
},
"≤":function(A,B){
return Frac.is.b2['≤'](Frac.build.D(A),Frac.build.D(B))
},
},
b1:{//一元关系
"1":function(A){return +(+A[0]==1 && A[1]==0 && A[2]==0)},
"0":function(A){return +(+A[0]==0)},
"+":function(A){return +(+A[0]!=0 && (A[0]+'')[0]!='-')},
"-":function(A){return +((A[0]+'')[0]=='-')},
".":function(A){return +(A[1]<0)},
"Z":function(A){return +(A[1]>=0)},//整数
"N":function(A){return +((A[0]+'')[0]!='-' && A[1]>=0 )},//自然数
"+Z":function(A){return +(+A[0]!=0 && (A[0]+'')[0]!='-' && A[1]>=0)},//正整数
"-Z":function(A){return +((A[0]+'')[0]=='-' && A[1]>=0 )},//负整数
}
},
fromStr:function(s){
if(/^-?\d+$/.test(s)){
return Decimal.build.I(s)
}
if(/^-?[\d\.]+[%‰‱]?$/.test(s)){//含百分号、无限循环小数、有限小数等情况
return Decimal.build.D(s)
}
if(/^-?[\d\.]+×10\^.+$/.test(s)){
return Decimal.build['10'](s)
}
if(/^-?\d+[/]\d+$/.test(s)){
return Decimal.build.F(s)
}
return undefined
},
toStr:function(A,typ){//转成文本
/* typ数字类型
. 小数 (默认)
, 每3位数字一个逗号分隔符
%‰‱ 百(千万)分数
/ 分数
一 中文小写
一元 中文货币小写
壹圆 中文货币大写
10 科学计数法
1000 工程计数法
*/
var type=typ||'.',str=A[0]+'',d=A[1],I=str.replace(/^-/,'').length,isNeg=str[0]=='-';
if(type=='/'){
str=Frac.toStr(Frac.build.D(A))
}else if(type=='10'){
str=(I>1?str.replace(/\d/,'$&.'):str)+(str.substr(-1)=='1' && d==1?'0':(I==1 && d || I>1?'×10'+(d+I-1?'^'+(d+I-1):'').replace(/\^1$/,''):''))
}else if(type=='1000'){
if(I<4 && d%3==0){
str+=d?'×10^'+(d):''
}else{
str=str.replace(new RegExp('\\d{'+(I-(I+d)%3+(I+d<0?-3:0))+'}$'),'.$&')+'×10^'+(I+d-(I+d)%3+(I+d<0?-3:0))
}
str=str.replace(/^-\./,'-0.').replace(/^\./,'0.');
}else{
if(/[%‰‱]/.test(type)){
d+='%‰‱'.indexOf(type)+2;
}
if(d){
if(d>0){
str+=ZLR(0,d)
}else if(I>-d){
str=str.replace(new RegExp('\\d{'+(-d)+'}$'),'.$&')
}else{
str=(isNeg?'-':'')+'0.'+ZLR(0,-d-I)+(isNeg?str.substr(1):str)
}
}
if(type==','){
str=str.replace(/^[^\.]+/,function(t){return t.split('').reverse().join('').replace(/\d{3}/g,'$&,').split('').reverse().join('').replace(/^,/,'').replace(/-,/,'-')})
.replace(/\..+/,function(t){return t.replace(/\d{3}/g,'$&,').replace(/,$/,'')})
}
if(/[%‰‱]/.test(type)){
str+=type
}
if(type=='一'){
str=n2Zh(str)
}
if(type=='一元'){
str=n2Zh(str,0,1)
}
if(type=='壹圆'){
str=n2Zh(str,1,1)
}
if(A[2]){//循环节长度
//console.log(str,A[2]);
str=str.replace(new RegExp('(\\d\\.?){'+A[2]+'}$'),function(x){return x.replace(/\d/,'\\dot$&').replace(/(\d.*)(\d)$/,'$1\\dot$2')})
}
}
return str
},
opr1:function(op,arr,p){//一元运算 p是参数
var A=[].concat(arr),str=A[0],d=A[1],I=str.replace(/^-/,'').length,isNeg=str[0]=='-';
A.type='Decimal';
if(op=='-'){//相反数
if(A[0][0]!='0'){
A[0]=A[0][0]=='-'?A[0].substr(1):'-'+A[0];
}
return A
}
if(op=='/'){//小数化既约分数(数组)
return Frac.build.D(A)
}
if(op=='I'){//取整 参数p:u(p)向上 d(own)向下 t(runc)截取 r(ound)四舍五入
if(d<0){
if(I<=-d){
if(p=='u'){A=[''+(+!isNeg),0,0]}
if(p=='d'){A=[(isNeg?'-':'')+(+isNeg),0,0]}
if(p=='t'){A=['0',0,0]}
if(p=='r'){A=[(isNeg?'-':'')+(+(+str[+isNeg]>4)),0,0]}
A.type='Decimal';
}else{
if(p=='u'){A=Decimal.oprs('+',[Decimal.build.D(str.substr(0,I+d)),[''+(+!isNeg),0]])}
if(p=='d'){A=Decimal.oprs('-',[Decimal.build.D(str.substr(0,I+d)),[''+(+isNeg),0]])}
if(p=='t'){A=Decimal.build.D(str.substr(0,I+d+(+isNeg)))}
if(p=='r'){A=Decimal.oprs('+',Decimal.build.D(str.substr(0,I+d+(+isNeg))),[(+(+str.substr(d+1)>4))*(isNeg?-1:1),0])}
}
}
return A
}
if(op=='d'){//取小数
if(d<0){
if(I>-d){
A[0]=Decimal.build.D(str.substr(d),d)
}
}else{
A=['0',0,0];
A.type='Decimal';
}
return A
}
if(op=='r_0'){//四舍五入(不强制保留小数中尾0) 得到数组, 参数 p是小数位数(负数表示取整百整千...)
//console.log('小数位数 p=',p,' 原来小数点d在',d,'p+d+1= ',p+d+1);
if(p+d+1<=0){//-p>=d+1
var I0=str.replace(/^-/,'').substr(0,I+p+d+1);
if(I0.length<p+1){
I0='0'.repeat(p+1-I0.length)+I0;
}
//console.log('I0 = ',I0,'-p= ',-p)
if(/[5-9]$/.test(I0)){
I0=Integer.oprs('+',[I0.substr(0,I0.length-1),1]);
if(I0.length<p+1){
I0='0'.repeat(p+1-I0.length)+I0;
}
}else{
I0=I0.substr(0,I0.length-1)
}
A=Decimal.build.D((isNeg?'-':'')+I0, -p)
}else{//-p<d+1 p+d+1>0
}
return A
}
if(op=='r'){//四舍五入(强制保留小数中尾0) 返回字符串 参数 p是小数位数(负数表示取整百整千...)
A=Decimal.toStr(Decimal.opr1('r_0',A,p));
if(/\./.test(A) && p>A.split('.')[1].length){
A+='0'.repeat(p-A.split('.')[1].length)
}
return A
}
},
oprs:function(op,arrA,p){//多元运算 p是参数
var aA=[].concat(arrA),al=aA.length, t;
if(!(aA[0] instanceof Array)){
aA=Arrf(Decimal.build.D,aA);
}
if(op=='竖式+-'){//参数p:+或-,支持二元以上同一种运算(但不支持+-混合)
//console.log(aA.join(brn),al);
aA.push(Decimal.oprs(p,aA));
aA=Arrf(Decimal.toStr,aA);
//console.log(aA.join(brn),al);
t=aA.slice(0,al).join(p)+'='+aA[al];
Arrf(function(x,i){aA[i]=(''+x).split('.')},aA);
//console.log(aA.join(';'),max(Arri(aA,0)),max(Arri(aA,1)));
var nl=(''+max(Arri(aA,0))).length,nr=(''+max(Arri(aA,1))).length;
//console.log(aA.join(brn), nl, nr);
Arrf(function(x,i){
x[0]=hp().repeat(Math.abs(nl-(''+x[0]).length))+x[0];
if(!x[1]){
x[1]=x[0]+hp('.'+'0'.repeat(nr))
x[0]='';
}else{
x[1]+=nr-(''+x[1]).length?hp('0'.repeat(nr-(''+x[1]).length)):'';
x[1]=x.join('.');
x[0]='';
}
},aA);
aA[al-1][0]=p;
//console.log(aA.join(brn),al);
return [mtrx(aA,'.','.','','I'+al),t,''].join(kbr+'\\widetilde{'+'~'.repeat(27)+'}'+kbr);
}
if(op=='竖式*'){//二元
/* 测试用例:
$Decimal.oprs('竖式*',[1.234,20.15])$
$Decimal.oprs('竖式*',[0.002,20.15])$
$Decimal.oprs('竖式*',[0.002,0.01])$
$Decimal.oprs('竖式*',[0.002,300])$
*/
//console.log(aA.join('; '));
var a=aA[0][0],b=aA[1][0], bl=b.length, nr0=max([aA[0][1], aA[1][1], aA[0][1]+aA[1][1], 0]);
//console.log(a,b,bl,nr0);
t=Decimal.toStr(aA[0])+'×'+Decimal.toStr(aA[1])+'='+Decimal.toStr(Decimal.oprs('*',aA));
var tA=[];
for(var i=bl-1;i>-1;i--){
if(b[i]!='0'){
tA.push([Integer.oprs('*1',[a,b[i]]), bl-i-1]);
}
}
var tAl=tA.length;
if(bl>1){
//tA.push(Decimal.oprs('+',tA));
var x=Decimal.oprs('+',tA);
tA.push([x[0],x[1]]);
// console.log(tA[tAl][0], tA[tAl][1]);
tA[tAl][0]=tA[tAl][0]+'0'.repeat(tA[tAl][1]);
tA[tAl][1]=0;
// console.log(tA.join(' ; '));
}else{
tAl--;
tA[tAl][0]=tA[tAl][0]+'0'.repeat(tA[tAl][1]);
tA[tAl][1]=0;
// console.log(tA.join(' ; '));
}
var nl=max([tA.slice(-1)[0][0].length, -aA[0][0].length-aA[0][1]+1, -aA[1][0].length-aA[1][1]+1]),
d=Integer.oprs('+',[aA[0][1], aA[1][1]]), dA=[];
//console.log(nl,d,'tA=',tA.join(' ; '));
if(aA[0][1]<0){
aA[0][0]=Decimal.toStr(aA[0]);
dA.push(aA[0][1]);
}
if(aA[1][1]<0){
aA[1][0]=Decimal.toStr(aA[1]);
if(dA.indexOf(aA[1][1])<0){
dA.push(aA[1][1]);
}
}
if(+d<0 && bl>=1){
var t0=tA[tAl][0];
//console.log('t0= ',t0,'tA[tAl][0]=',tA[tAl][0]);
tA[tAl][0]=t0.replace(new RegExp('(\\d{'+(-d)+'})$'),'.$1');
t0=tA[tAl][0];
//console.log('t0= ',t0,'tA[tAl][0]=',tA[tAl][0]);
if(t0[0]=='.'){
tA[tAl][0]=0+t0;
nl++;
}else if(!/\./.test(t0)){
tA[tAl][0]='0.'+'0'.repeat(-d-t0.length)+t0.replace(/0+$/,function(t){return '∅'.repeat(t.length)});
//console.log(tA[tAl]);
nl=-d+1;
}
if(dA.indexOf(+d)<0){
dA.push(+d);
}
}
//console.log(nl,tA.join('; '));
Arrf(function(x){
//console.log('x=',x,' nl= ',nl,nr0,(''+x[0]).replace(/[\.①]/g,'').length,nl-(''+x[0]).replace(/[\.①]/g,'').length-x[1]);
x[1]='⓪'.repeat(Math.max(nl-(''+x[0]).replace(/[\.①]/g,'').length-x[1],0)) //透明0
+x[0]
+'⓪'.repeat(x[1]+nr0); //透明0
//console.log('x[1]= ',x[1]);
if(/\./.test(x[1])){
x[1]=x[1].replace(/0+$/,function(t){return '∅'.repeat(t.length)})
}
x[0]='';
},tA);
//console.log(aA.join(' aA= '));
aA[0]=['','⓪'.repeat(Math.max(nl-(''+aA[0][0]).replace(/[\.①]/g,'').length,0))
+aA[0][0]
+'0'.repeat(aA[0][1]>0?aA[0][1]:0)
+'⓪'.repeat(nr0-Math.max(aA[0][1],0))];
aA[1]=['×','⓪'.repeat(Math.max(nl-(''+aA[1][0]).replace(/[\.①]/g,'').length,0))
+aA[1][0]
+'0'.repeat(aA[1][1]>0?aA[1][1]:0)
+'⓪'.repeat(nr0-Math.max(aA[1][1],0))];
//console.log('dA ',dA, 'nl ',nl);
var dotf=function(x){
if(x[1].split('.').length-1<dA.length){
for(var i=dA.length-1;i>=0;i--){
var y=x[1].replace(/①/g,'.').replace(/⓪/g,'0'), yl=y.length;
//console.log('y ',y,'nl-dA['+i+']= ',nl+dA[i]);
if(!(new RegExp('^([^\\.]\\.*){'+(nl+dA[i])+'}\\.')).test(y)){
x[1]=x[1].replace(new RegExp('^(([⓪\\d][①|\\.]*){'+(nl+dA[i])+'})'),'$1①');
if(x[1].split(/[\.①]/).length-1==dA.length){
break;
}
}
}
}
x[1]=x[1].replace(/∅/g,kancel(0)).replace(/①/g,hp('.')).replace(/⓪/g,hp());
};
dotf(aA[0]);
dotf(aA[1]);
for(var i=tA.length-1;i>=0;i--){
dotf(tA[i]);
}
//console.log(tA[tAl][1], d);
if(+d>0){
//console.log(tA[tAl][1], d);
tA[tAl][1]=tA[tAl][1].replace(new RegExp('(\\\\hphantom\\{0\\}){'+nr0+'}$'), '0'.repeat(d)+kancel(0).repeat(Math.max(nr0-d,0)));
//console.log(tA[tAl][1]);
}else{
//console.log(tA[tAl][1], d);
tA[tAl][1]=tA[tAl][1].replace(new RegExp('\\.0+(\\\\hphantom\\{0\\})*$'), function(x){return Arrf(kancel,x.split('\\')[0].split('')).join('')+'\\'+x.split('\\')[1]});
}
var h0=/^\\hphantom\{\.\}/.test(aA[0][1]), h1=/^\\hphantom\{\.\}/.test(aA[1][1]);
if(h0||h1){
var dots=h0 && /^\d+\./.test(aA[1][1])?aA[1][1].split('.')[0].length:(h1 && /^\d+\./.test(aA[0][1])?aA[0][1].split('.')[0].length:0), s=hp(0).repeat(dots);
for(var i=aA.length-1;i>=0;i--){
if(/^\\hphantom\{\.\}/.test(aA[i][1])){
aA[i][1]=s+aA[i][1];
}
}
for(var i=tA.length-1;i>=0;i--){
if(/^\\hphantom\{\.\}/.test(tA[i][1])){
tA[i][1]=s+tA[i][1];
}
}
}
//console.log(aA,tA);
return [mtrx(aA.concat(tA),'.','.','','I2'+(bl>=2?'_'+(tA.length+1):'')),t,''].join(kbr+'\\widetilde{'+'~'.repeat(27)+'}'+kbr);
}
if(op=='竖式/'){//二元 p需计算到的小数位
/* 测试用例:
$Decimal.oprs('竖式/',[1.43,0.13])$\\
$Decimal.oprs('竖式/',[1.234,20.15],5)$\\
$Decimal.oprs('竖式/',[1.234,20.15])$\\
$Decimal.oprs('竖式/',[1.3,0.78],1)$\\
$Decimal.oprs('竖式/',[0.002,20.15])$\\
$Decimal.oprs('竖式/',[0.002,0.01])$\\
$Decimal.oprs('竖式/',[0.002,300])$\\
$Decimal.oprs('竖式/',[0.02,0.01])$\\
*/
//console.log(aA.join('; '));
var a=aA[0][0],b=aA[1][0],
al=a.length, bl=b.length,
atens=aA[0][1], btens=aA[1][1],
c='', d=aA[0][1]-aA[1][1],q='',
Da=Decimal.toStr(aA[0]), Db=Decimal.toStr(aA[1]),
sa=Da, sb=/\./.test(Db)?Db.replace('.','③'):Db.replace(/0+$/,function(x){return x.replace(/0/g,'②')}),
rep01=function(x){return x.replace(/[\d②]/g,'⓪').replace(/[\.③]/g,'①')},//.replace(/[\.③⑤]/g,'①')},
rep4=function(x){return x.replace(/[⓪①②③⑤]/g,'')},
repI=function(x){return x.replace(/[①③⑤\.]/g,'').replace(/[⓪②]/g,'0').replace(/^0+/,'')},
repopa=function(x){return x.replace(/[①③⑤]/g,'.').replace(/[⓪②]/g,'0')};
//把b化成整数(a相应扩大或缩小倍数) 透明0:⓪ 透明. :① kancel(0): ② kancel('.'):③ hp(kancel('.')):⑤
if(btens){
sa=sa.replace('.','③');
}
if(btens>0){//sa小数点向左偏移
if(/0$/.test(sa)){//atens>0
var r0=sa.replace(/.*[^0]/,'').length;
if(r0>=btens){
sa=sa.substr(0,sa.length-btens)+'②'.repeat(btens)
}else{
sa=sa.substr(0,sa.length-btens)+'.'+sa.substr(sa.length-btens,sa.length-r0)+'②'.repeat(r0)
}
}else{//atens<=0
var n=atens<0?sa.split('③')[0].length:al;
if(n>btens){
sa=sa.substr(0,n-btens)+'.'+sa.substr(n-btens,sa.length)
}else{
sa='0.'+'0'.repeat(btens-n)+sa
}
}
}
if(btens<0){//sa小数点向右偏移
if(atens>=0){//atens>0
sa+='0'.repeat(-btens);
}else{// if(/\./.test(sa)){//atens<0
var dotr=sa.split('③')[1].length;
if(dotr>-btens){
sa=sa.substr(0,sa.length-(dotr+btens))+'.'+sa.substr(sa.length-(dotr+btens),sa.length)
}else if(dotr==-btens){
sa+='①';
}else{
//sa='0.'+'0'.repeat(-btens-dotr)+sa
sa=(/^0③/.test(sa)?sa.replace(/0③0*/,function(x){return x.replace(/0/g,'②')}):sa)+'0'.repeat(-btens-dotr)+'①'
}
}
}
// 以下待续
var sl=sa.length, nop=p==undefined, fx=nop?8:p, fxi=0,r='',A='',IA='', tA=[sa];
//console.log('sa= ',sa, '小数精度位数 fx = ',fx);
for(var i=0;i<sl+fx+2;i++){
//console.log('i= ',i, 'c= ',c,'r= ',r,'A= ',A,'IA =',IA);
if(/^0+$/.test(rep4(r))){//余数为0
break;
}
if(fxi>=fx+1){
//console.log('小数精度达标',fxi,' >= ',fx,'+1');
break;
}
var dos=0;
do{
//console.log('do循环开始:i= ',i,'c= ',c);
var si=i<sl?sa[i]:(/[\.①③]/.test(sa) || i>sl?'0':'①');//'⓪':'①'
A+=si;
IA=repI(A);
//console.log('小循环开始:i= ',i,'si= ',si, 'sa = ',sa, 'sl = ',sl);
//console.log('si = ',si,'sa= ',sa,'c= ',c,'A= ',A,'IA= ',IA,'fxi= ', fxi,'fx+1= ',fx+1,'(b,IA) = ',b,IA);
if(/[\.①]/.test(si)){
//console.log('si = ',si,'fx = ',fx,'c = ',c,'fxi = ',fxi);
if(!fx && si=='①'){
c=c.replace(/⓪$/,'0');
fxi=1;
A=A.replace(/①$/,'')
break
}
c=c.replace(/⓪$/,'0')+'.'
}else if(/③/.test(si)){
c+='⑤';
}else if(Integer.is.b2['>'](b,IA)){
if(/\d/.test(c)){
c+=0;
}else{
c+='⓪';
}
}
//console.log('小循环尾声 i= ',i,'c= ',c);
fxi=(rep4(c).split('.')[1]||'').length;
i++;
dos=1;
//console.log('商 c= ',c,' 小数位数 fxi= ',fxi,'此时i= ',i);
}while(Integer.is.b2['>'](b,IA) && fxi<fx+1)
//console.log('i= ',i,'qr之前,c= ',c);
var qr=Integer.oprs('/',[IA,b]);
//console.log(IA,'/',b,' = qr= ',qr);
//console.log('i= ',i,'tA= ',tA,'A= ',A,'fxi= ',fxi,' fx+1 = ',fx, '+1');
if(tA.length>1){
tA[tA.length-1]=A;
}
if(qr[0]=='0' && fxi>=fx+1){
//console.log('精度足够,退出循环');
r=A;
break
}
if(!/\d/.test(c) && qr[0]=='0'){
c+='⓪'
}else{
c+=qr[0]
}
fxi=(rep4(c).split('.')[1]||'').length;
//console.log('qr之后,c= ',c,'此时商的小数位数 fxi = ',fxi);
var pd=Integer.oprs('-',[IA,qr[1]]);
//console.log('pd= ',pd);
var pdi=rep01(c).split('');
//console.log('pdi= ',pdi.join(''),'c= ',c,'c.length',c.length);
for(var j=c.length-1;j>-1;j--){
//console.log('c[',j,'] = ',c[j], /[\.①③⑤]/.test(c[j]));
if(!/[\.①③⑤]/.test(c[j])){
pdi[j]=pd.slice(-1);
pd=pd.substr(0,pd.length-1);
//console.log('j= ',j,' pdi= ',pdi.join(''),' pd =', pd);
if(!pd){
break
}
}
}
tA.push(pdi.join(''));
//console.log('后来 pdi= ',pdi.join(''));
var ri=rep01(c).split(''), qr1=qr[1];
//console.log('ri= ',ri.join(''));
for(var j=c.length-1;j>-1;j--){
if(!/[\.①③⑤]/.test(c[j])){
ri[j]=qr1.slice(-1);
qr1=qr1.substr(0,qr1.length-1);
if(!qr1){
break
}
}
}
A=ri.join('');
IA=repI(A);
//console.log('余数 A= ',A,'IA = ',IA);
r=A;
if(i<sl){
//console.log('局部余数= ',r,'A = ',A);
r+=sa.substr(i);
//console.log('整体余数= ',r);
}
//console.log('大循环尾声 i= ',i,'c= ',c,'r= ',r, 'sa= ',sa, 'fxi= ',fxi, 'fx+1=',fx,'+1',' dos= ',dos);
//这里需要更新A, IA, C
tA.push(r);
if(dos){
i--;
}
}
if(c.length<sl){
//console.log('此时 c=',c );
//console.log('sa= ',sa );
//c+=rep01(sa.substr(c.length))
c+=rep01(sa.substr(c.length));
//console.log('然后 c=',c );
if(/⓪+$/.test(c)){
c=c.replace(/⓪+$/,function(x){return '0'.repeat(x.length)})
}
}
var cl=c.length;
Arrf(function(x,i){
if(x.length<cl){
tA[i]+=rep01(c.substr(x.length))
}
//console.log(tA[i]);
if(i%2){//需加下划线的行
if(/^\D*0.*\d/.test(tA[i+1])){
var l0=tA[i+1].match(/^\D*0[0\D]*/g)[0].length+1-tA[i].replace(/\d.+/,'').length;
tA[i]=tA[i].replace(/(\d.*)*\d.*/,function(x){return x.length>l0?kxu(x.substr(0,l0))+x.substr(l0):kxu(x)})
}else{
tA[i]=tA[i].replace(/(\d.*)*\d/,function(x){return kxu(x)})
}
}else{
//console.log(tA[i]);
if(/^\D*0.*\d/.test(tA[i])){
var l0=tA[i].replace(/[^0].*/,'').length;
//tA[i]=tA[i].replace(/^\D*0[0\D]*/, function(x){return x.replace(/0/g,'⓪')});
// tA[i]=tA[i].replace(/^\D*00+/, function(x){var x0=x.split('0')[0]+0;return x0+x.substr(x0.length).replace(/0/g,'⓪')});
tA[i]=tA[i].replace(/00+$/, function(x){return x.replace(/0/g,'⓪').replace(/⓪$/,'0')});
tA[i]=tA[i].replace(/^\D*0+[1-9]/, function(x){return x.replace(/0/g,'⓪')});
//console.log(tA[i]);
}
}
tA[i]=(i?hp(sb+')'):sb+')')+tA[i]
},tA);
tA.unshift(hp(sb)+kxu(hp(')')+c));
c=rep4(c);
//console.log('尾声r = ',r);
if(r.length<sl){
r+=sa.substr(r.length);
//console.log('实际上 r = ',r);
}
r=/[1-9]/.test(r)?repopa(/⑤/.test(r)?r.replace('⑤','.').replace('①',''):r.replace('①','.')):'0';//r=/[1-9]/.test(r)?rep4(r.replace(/⓪/g,'0').replace(/①/g,'.')).replace(/^0+/,''):'0';
r=r.replace(/^0+/,'');
if(r[0]=='.'){
r=0+r
}
//console.log('最终r = ',r);
t=Da+'÷'+Db+'='+c+
(r?'\\cdots '+r+(fx?'\\\\ '+Da+'÷'+Db+'≈'+Decimal.opr1('r',Decimal.build.D(c),fx)+'(保留'+fx+'位小数)':''):'');
/*
js精度bug
(0.000099255).toFixed(8)
*/
return [mtrx(tA,'.','.','').replace(/⓪/g,hp()).replace(/①/g,hp('.')).replace(/②/g,kancel(0)).replace(/③/g,kancel('.')).replace(/⑤/g,hp(kancel('.'))),t,''].join(kbr+'\\widetilde{'+'~'.repeat(27)+'}'+kbr);
}
if(op=='+'){
for(var i=0;i<al;i++){
if(aA[i][0]=='0'){
aA.splice(i,1);
al--;
i--;
}
}
if(al<2){return aA[0]}
var sA=[];
for(var i=0;i<al;i++){
sA.push(aA[i].join())
}
for(var i=0;i<al;i++){
for(var j=i+1;j<al;j++){
if(sA[i]=='-'+sA[j] || sA[j]=='-'+sA[i]){
sA.splice(i,1);
sA.splice(j-1,1);
aA.splice(i,1);
aA.splice(j-1,1);
al-=2;
i--;
break;
}
}
}
if(al==0){var A=['0',0,0];A.type='Decimal';return A}
if(al<2){return aA[0]}
if(al>2){
return Decimal.oprs('+',[Decimal.oprs('+',aA.slice(0,al-1)),aA[al-1]])
}else{
var a0=''+aA[0][0],a1=aA[0][1],b0=''+aA[1][0],b1=aA[1][1],isNega=a0[0]=='-',isNegb=b0[0]=='-',isNegSame=isNega==isNegb,
Ia=a0.replace(/^-/,'').length,Ib=b0.replace(/^-/,'').length,Na=a0.replace(/-/,''),Nb=b0.replace(/-/,'');
//console.log(Na,Nb,isNegSame,isNega,isNegb);
if(isNegSame){
if(a1>=Ib+b1){
return [a0+ZLR(0,a1-Ib-b1)+b0.substr(+isNegb),b1]
}
if(b1>=Ia+a1){
return [b0+ZLR(0,b1-Ia-a1)+a0.substr(+isNega),a1]
}
if(a1==b1){
return Decimal.build.D((isNega?'-':'')+Integer.oprs('+',[Na,Nb]),a1)
}
if(a1>b1){
return Decimal.build.D((isNega?'-':'')+Integer.oprs('+',[Na+ZLR(0,a1-b1),Nb]),b1)
}
if(a1<b1){
return Decimal.build.D((isNega?'-':'')+Integer.oprs('+',[Nb+ZLR(0,b1-a1),Na]),a1)
}
}else{
////console.log(isNegb?[aA[0],[Nb,b1]]:[aA[1],[Na,a1]]);
return Decimal.oprs('-',isNegb?[aA[0],[Nb,b1]]:[aA[1],[Na,a1]])
}
}
}
if(op=='-'){
for(var i=1;i<al;i++){
if(aA[i][0]=='0'){
aA.splice(i,1);
al--;
i--;
}
}
if(al<2){return aA[0]}
//console.log(aA.join(brn), al);
if(aA[0][0]=='0'){
if(al==2){
return Decimal.opr1('-',aA[0])
}else{
return Decimal.opr1('-',Decimal.oprs('+',aA.slice(1)))
}
}
if(al>2){
return Decimal.oprs('-',[aA[0],Decimal.oprs('+',aA.slice(1))])
}else{
//console.log(aA.join(brn), al);
var a0=aA[0][0],a1=aA[0][1],b0=aA[1][0],b1=aA[1][1],isNega=a0[0]=='-',isNegb=b0[0]=='-',isNegSame=isNega==isNegb,
Ia=a0.replace(/^-/,'').length,Ib=b0.replace(/^-/,'').length,Na=a0.replace(/-/,''),Nb=b0.replace(/-/,'');
//console.log(isNegSame,isNega,isNegb,aA[0],aA[1]);
if(isNegSame){
var agb=Decimal.is.b2['≥'](aA[0],aA[1]);
if(a1==b1){
return Decimal.build.D((agb?'':'-')+Integer.oprs('-',[Na,Nb]).replace(/-/,''),a1)
}
//console.log(a1,b1,agb);
if(a1>b1){
////console.log(Na+ZLR(0,a1-b1),Nb);
return Decimal.build.D((agb?'':'-')+Integer.oprs('-',[Na+ZLR(0,a1-b1),Nb]).replace(/-/,''),b1)
}
if(a1<b1){
return Decimal.build.D((agb?'':'-')+Integer.oprs('-',[Na,Nb+ZLR(0,b1-a1)]).replace(/-/,''),a1)
}
}else{
return isNegb?Decimal.oprs('+',[aA[0],[b0.substr(1),b1]]):Decimal.opr1('-',Decimal.oprs('+',[[a0.substr(1),a1],aA[1]]))
}
}
}
if(op=='*'){
if(al<2){return aA[0]}
for(var i=0;i<al;i++){
if(aA[i][0]=='0'){
var A=['0',0,0];A.type='Decimal';
return A
}
}
var tens=0,isneg=0,nA=[];
for(var i=0;i<al;i++){
var ai=aA[i];
if(ai[0]=='-'){
isneg=!isneg;
if(ai[0]!='-1'){
nA.push(ai[0].substr(1));
}
}else{
if(ai[0]!='1'){
nA.push(ai[0]);
}
}
if(ai[1]){
tens+=ai[1];
}
}
al=nA.length;
if(al<2){var A=[nA[0],tens];A.type='Decimal';return A}
if(al>2){
return Decimal.oprs('*',[Decimal.build.D(Integer.oprs('*',nA.slice(0,al-1))),[nA[al-1],tens]])
}else{
var A=[Integer.oprs('*',nA),tens,0];
A.type='Decimal';
if(/0+$/.test(A[0])){
A[1]+=A[0].replace(/^.*[^0]/,'').length;
A[0]=A[0].replace(/0+$/,'');
}
return A
}
}
if(op=='/'){
return Frac.opr1('.',Frac.oprs('/',Arrf(Frac.build.D,aA)))
}
if(op=='^'){//有理小数幂运算不封闭,可能得到根号形式的无理数
return Frac.oprs('^',Arrf(Frac.build.D,aA))
}
}
/*函数依赖关系:
Decimal.build.F 依赖于 Frac.opr1('.',A)
Decimal.toStr(,'/') 依赖于 Frac.toStr(Frac.build.D(A))
Decimal.opr1('/') 依赖于 Frac.build.D(A)
*/
}, Frac={/*分数(分子,分母) 本质是数组:[分子,分母]
*/
build:{
A:function(a){//分子,分母数组
var A=[].concat(a);
A.type='Frac';A.toStr=function(p){return Frac.toStr(this,p)};
return A
},
I:function(t){//整数数字串
var A=[t+'','1'];
A.type='Frac';A.toStr=function(p){return Frac.toStr(this,p)};
return A
},
D:function(a){//有理小数Decimal对象 或有限小数字符串
var A=isArr(a)?[].concat(a):[a,0,0];
if(A.length==1){
A.push(0,0)
}
if(A.length==1){
A.push(0)
}
A[0]=Decimal.toStr(Decimal.build.D(A[0],A[1]));
return Frac.build.F(n2frac(A[0],A[2]))
},
F:function(t){//t是分数字符串a/b 或整数字符串
var s=wrapTrim(''+t), A=s.split('/');
A.type='Frac';A.toStr=function(p){return Frac.toStr(this,p)};
if(!/\//.test(s)){
A.push('1');
}
return A
}
},
is:{//布尔逻辑
b2:{//二元关系
"=":function(A,B){
return +(FracReduct(A)==FracReduct(B))
},
"≠":function(A,B){
return +(FracReduct(A)!=FracReduct(B))
},
">":function(A,B){
return +/-/.test(fracOpr('-',B,A))
},
"≥":function(A,B){
return +!/-/.test(fracOpr('-',A,B))
},
"<":function(A,B){
return +/-/.test(fracOpr('-',A,B))
},
"≤":function(A,B){
return +!/-/.test(fracOpr('-',B,A))
},
},
b1:{//一元关系
"1":function(A){return +(A[0]+''==A[1]+'' && A[0]+''!='0')},
"0":function(A){return +(A[0]+''=='0')},
"+":function(A){return +(A[0]+''!='0' && (A[0]+'')[0]!='-')},
"-":function(A){return +((A[0]+'')[0]=='-')},
}
},
fromStr:function(s){
if(/^-?\d+$/.test(s)){
return Frac.build.I(s)
}
if(/^-?[\d\.]+[%‰‱]?$/.test(s)){
return Frac.build.D(s)
}
if(/^-?[\d\.]+×10\^.+$/.test(s)){
return Frac.build.D(Decimal.build['10'](s))
}
if(/^-?\d+[/]\d+$/.test(s)){
return Frac.build.F(s)
}
return undefined
},
toStr:function(A,latex){//转成文本
/*
分数文本
参数latex 指定输出latex形式
*/
var t=A.join('/').replace(/\/1$/,'');
return latex && A[1]!='1'?kfrac(t):t
},
opr1:function(op,arr,p){//一元运算 p是参数 运算结果仍是有理数,则返回分数数组,否则返回表达式字符串!
var A=FracReduct(arr).split('/'),a=A[0],b=A[1]||'1',isNeg=a[0]=='-', aa=isNeg?a.substr(1):a;
if(!A[1]){
A[1]='1'
}
A.type='Frac';A.toStr=function(p){return Frac.toStr(this,p)};
if(op=='-'){//相反数
if(a!='0'){
A[0]=isNeg?aa:'-'+a;
}
}
if(op=='||'){//绝对值
if(isNeg){
A[0]=aa;
}
}
if(op=='1/'){//倒数
if(a!='0'){
A[0]=isNeg?'-'+b:b;
A[1]=aa;
}
}
if(op=='^2'){//平方
if(a!='0'){
A[0]=Integer.opr1('^2',aa);
A[1]=Integer.opr1('^2',b);
}
}
if(op=='^3'){//立方
if(a!='0'){
A[0]=Integer.opr1('^3',aa);
A[1]=Integer.opr1('^3',b);
}
}
if(op=='√'){//开方
return Frac.oprs('^',[A,[1,2]])
}
if(op=='∛'){//开立方
return Frac.oprs('^',[A,[1,3]])
}
if(op=='∜'){//开四次方
return Frac.oprs('^',[A,[1,4]])
}
if(op=='.'){//分数化小数对象 a=qb+r
if(a=='0'){
return Decimal.build.I(0)
}
a=a.replace('-','');
//console.log(a,b,'化小数对象');
var al=a.length,q='',r='',qr=[],len=0;
while(!len || r!='0'){
var x=Integer.oprs('/',[a,b]),X=x.join();
//console.log(a,'/',b,' = ',x);
r=x[1];
if(r=='0'){//除尽
q+=x[0];
return Decimal.build.D(nTrim(q.replace(/^0+([1-9])/,'$1').replace(/^0+\./,'0.')),0,0)
}
if(qr.indexOf(X)>-1){//发现循环节
if(qr.indexOf(X)>-1){
len=qr.length-qr.indexOf(X);
}
return Decimal.build.D(nTrim(q.replace(/^0+([1-9])/,'$1').replace(/^0+\./,'0.')),0,len)
}
qr.push(X);
q+=x[0];
if(q.length==al && r!='0'){
q+='.'
}
a=r+'0';
}
}
if(op=='='){/*约分化简 分子、分母都是整数
*/
var t=gcd(A);
if(a=='0'){A[0]='0';return A}
var s=isNeg ^ b[0]=='-'?'-':'';
a=Integer.oprs('/',[a.replace('-',''),t])[0];
b=Integer.oprs('/',[b.replace('-',''),t])[0];
A[0]=s+a;
A[1]=b;
}
return A
},
oprs:function(op,arr,p){//多元运算 p是参数
var A=[].concat(arr),l=A.length;
A.type='Frac';A.toStr=function(p){return Frac.toStr(this,p)};
if(/^[\+\-\*\/×÷]$/.test(op)){
return Frac.build.F(Arrf(function(x,y){return fracOpr(op,x,y)},A,'cp2'))
}
if(op=='^'){
var t=fracOpr(op,A[0],A[1]);
if(t.indexOf('(-1)^')>-1){//负数开偶次方,得到复数
return t
}else if(t.indexOf('^')>-1){//开方 根数
return t
}else{
if(l>2){
A.shift();
A[0]=Frac.build.F(t);
return Frac.oprs('^',A)
}else{
return Frac.build.F(t)
}
}
}
}
}, Root={/*根数 本质是二维数组:[(-1)^的有理幂次(默认0),有理系数(默认1),底数(正分数,默认1),分数幂次(正分数,默认1)]
*/
build:{
I:function(t){//整数字符串
var A=[Frac.build.I('0'),Frac.build.I(t),Frac.build.I('1'),Frac.build.I('1')];
A.type='Root';A.toStr=function(p){return Root.toStr(this,p)};
return A
},
D:function(a){//小数对象
var A=[Frac.build.I('0'),Frac.build.D(a),Frac.build.I('1'),Frac.build.I('1')];
A.type='Root';A.toStr=function(p){return Root.toStr(this,p)};
return A
},
F:function(t){//t是分数字符串a/b 或数组
var A=[Frac.build.I('0'),isArr(t)?t:Frac.build.F(t),Frac.build.I('1'),Frac.build.I('1')];
A.type='Root';A.toStr=function(p){return Root.toStr(this,p)};
return A
},
FP:function(t){/* t是分数幂字符串(-1)^(奇数/偶数)×(e/f)×(a/b)^(c/d) 或分数数组[[a0,a1],[b0,b1]]
(-1)^(1/2) [1,2], [1,1], [1,1], [1,1]
(-1)^(1/2)×(e/f)×(a/b)^(c/d) [1,2], [e,f], [a,b], [c,d]
(-1)^(1/2)×(-1)×(a/b)^(c/d) [1,2], [-1,1], [a,b], [c,d]
(-1)^(1/2)×(e/f) [1,2], [e,f], [1,1], [1,1]
(-1)^(1/2)×(a/b)^(c/d) [1,2], [1,1], [a,b], [c,d]
(e/f)×(a/b)^(c/d) [0,1], [e,f], [a,b], [c,d]
-(a/b)^(c/d) [0,1], [-1,1], [a,b], [c,d]
e/f [0,1], [e,f], [1,1], [1,1]
(a/b)^(c/d) [0,1], [1,1], [a,b], [c,d]
*/
var A=isArr(t)?[Frac.build.I('0'),Frac.build.I('1')].concat(t):(t.indexOf('(-1)^')>-1?[
Frac.build.F(t.split('×')[0].split('^')[1]),
Frac.build.F((t.split('×')[1]||'1^').indexOf('^')>0?'1':t.split('×')[1]),
Frac.build.F(t.split('^').length>2?t.split('^')[1].replace(/.+×/,''):'1'),
Frac.build.F(t.split('^').length>2?t.split('^')[2]:'1'),
]:[
Frac.build.F('0'),
Frac.build.F(t.split('×')[0].indexOf('^')>0?(t.split('×')[0][0]=='-'?'-1':'1'):t.split('×')[0]),
Frac.build.F(t.split('^').length>1?t.split('^')[0].replace(/^(-|.+×)/g,''):'1'),
Frac.build.F(t.split('^').length>1?t.split('^')[1]:'1'),
]);
A.type='Root';A.toStr=function(p){return Root.toStr(this,p)};
return A
},
},
is:{//布尔逻辑
b2:{//二元关系
"=":function(A,B){
return +(A.join()==B.join())
},
"≠":function(A,B){
return +(A.join()!=B.join())
},
">":function(A,B){
},
"≥":function(A,B){
},
"<":function(A,B){
},
"≤":function(A,B){
},
},
b1:{//一元关系
"1":function(A){return +(A.join(';')==[[0,1],[1,1],[1,1],[1,1]].join(';'))},
"0":function(A){return +(A[1][0]=='0')},
"+":function(A){return +(A[1][0]!='0' && A[1][0]!='-')},//忽略虚数系数
"-":function(A){return +(A[1][0]=='-')},//忽略虚数系数
}
},
fromStr:function(s){
if(/^-?\d+$/.test(s)){
return Root.build.I(s)
}
if(/^-?[\d\.]+[%‰‱]?$/.test(s)){
return Root.build.F(Frac.build.D(s))
}
if(/^-?[\d\.]+×10\^.+$/.test(s)){
return Root.build.D(Decimal.build['10'](s))
}
if(/^-?\d+[/]\d+$/.test(s)){
return Root.build.F(s)
}
if(/^(\(-1\)\^[\d/\(\)]+|-)?(×?[\d/\(\)]+)?(×?[\d/\(\)]+\^[\d/\(\)]+)?$/.test(s)){
return Root.build.FP(s)
}
return undefined
},
toStr:function(A,latex){//转成文本
/*
根数文本
参数latex 指定输出latex形式
*/
var a=[],b,haspow=A[2].join()!='1,1';
if(A[1][0]=='0'){
return '0'
}
if(A[0][0]!='0'){//-1的幂次
b=Frac.toStr(A[0]);
a.push('(-1)^'+pp((b.indexOf('/')>0 && latex?kfrac(b,'',1):b),latex?'{}':'()'))
}
if(A[1].join()!='1,1'){//有理系数
b=Frac.toStr(A[1]);
if(b=='-1'){
if(haspow){
if(a.length<1){
a.push('-')
}
}else{// (-1)^ ×(-1) 变成 (-1)^
if(a.length<1){
return '-1'
}
b=Frac.toStr(Frac.oprs('+',[A[0],['1','0']]));
return '(-1)^'+pp((b.indexOf('/')>0 && latex?kfrac(b,'',1):b),latex?'{}':'()')
}
}else{
if((b.indexOf('/')>0 || b[0]=='-') && (a.length || haspow)){
a.push(latex?zp(b.indexOf('/')>0?kfrac(b):b):pp(b,'()'))
}else{
a.push(b)
}
}
}
if(haspow){//有理底数
b=Frac.toStr(A[2]);
var c=b.indexOf('/')>0?(latex?zp(kfrac(b)):pp(b,'()')):b;
c+='^';
b=Frac.toStr(A[3]);
if(latex){
c+=pp(b.indexOf('/')>0?kfrac(b,'',1):b,'{}')
}else{
c+=b.indexOf('/')>0?pp(b,'()'):b;
}
a.push(c)
}
////console.log(a,b,c);
b=a.join('×').replace('-×','-')
return b
},
opr1:function(op,arr,p){//一元运算 p是参数
var A=Arrfc([Frac.build.F,FracReduct],arr),isNeg=A[1][0][0]=='-';
A.toStr=function(p){return Root.toStr(this,p)};
if(op=='-'){//相反数
if(A[1][0]!='0'){
A[1][0]=isNeg?A[1][0].substr(1):'-'+A[1][0];
}
return A
}
if(op=='='){//化简
if(A[1][0]=='0' || A[2][0]=='0'){//系数或底数为0
A[0][0]='0';
A[0][1]='1';
A[1][0]='0';
A[1][1]='1';
A[2][0]='1';
A[2][1]='1';
A[3][0]='1';
A[3][1]='1';
return A
}
if(A[2][0][0]=='-' && /[02468]$/.test(A[3][0])){// 负底数的偶次幂
A[2][0]=A[2][0].substr(1);
}
if(A[2][0][0]=='-' && /[13579]$/.test(A[3][0]) && /[13579]$/.test(A[3][1])){// 负底数的奇次幂
A[1][0]=A[1][0][0]=='-'?A[1][0].substr(1):'-'+A[1][0];
A[2][0]='1';
A[2][1]='1';
A[3][0]='1';
A[3][1]='1';
}
if(A[2][0][0]=='-' && /[13579]$/.test(A[3][0]) && /[02468]$/.test(A[3][1])){// 负底数的奇次幂,然后开偶次方
var f=Frac.oprs('+',[A[0],A[3]]);
A[0][0]=f[0];
A[0][1]=f[1];
A[2][0]==A[2][0].substr(1);
}
if(A[3][0]=='0' || A[2].join()=='1,1'){// 幂次为0,或底数为1
A[2][0]='1';
A[2][1]='1';
A[3][0]='1';
A[3][1]='1';
}
if(A[3][0][0]=='-'){// 负幂,底数变成倒数
var f=Frac.opr1('1/',A[2]);
A[2][0]=f[0];
A[2][1]=f[1];
A[3][0]=A[3][0].substr(1);
}
if(A[3][0]!='1' && A[3][1]=='1'){// 底数的整数幂,化成,纯底数
var f=Frac.oprs('*',[A[1],Frac.oprs('^',[A[2],A[3]])]);
A[1][0]=f[0];
A[1][1]=f[1];
A[2][0]='1';
A[2][1]='1';
A[3][0]='1';
A[3][1]='1';
}
if(A[3][0]!='1' || A[3][1]!='1'){// 底数的分数幂
var f=Frac.oprs('^',[A[2],A[3]]);
if(isStr(f)){//
}else{
f=Frac.oprs('*',[A[1],f]);
A[1][0]=f[0];
A[1][1]=f[1];
A[2][0]='1';
A[2][1]='1';
A[3][0]='1';
A[3][1]='1';
}
}
return A
}
},
oprs:function(op,arr,p){//多元运算 p是参数
var aA=[].concat(arr),al=aA.length, t;
if(op=='+'){
}
if(op=='-'){
}
if(op=='*'){
return A
}
if(op=='/'){
return A
}
if(op=='^'){//第2个元素,只能是有理数,不能是根数(否则变成超越数)
return A
}
}
}, Num={//上述基本(有理元素)数学对象的统一全体(不含变量) 运算结果,可能得到上述之外的数学表达式对象(Mfn)
build:function(a){
return isStr(a)?a:[].concat(a)
},
fromStr:function(s){//根据表达式自动识别数字类型,返回基本(有理元素)数学对象Integer Decimal Frac Root
var x=Frac.fromStr(s);
if(x==undefined){
x=Root.fromStr(s);
}
return x
},
toStr:function(a,p){
if(isStr(a)){
return a
}
//console.log(a);
var x=a.type;
if(x){
//return eval(x).toStr(a,p)
return a.toStr(p);
}
return undefined
},
is:{//布尔逻辑
b2:{//二元关系
"=":function(a,b){
return +(''+a==''+b)
},
"≠":function(a,b){
return +(''+a!=''+b)
},
},
b1:{//一元关系
'0':function(n){//
return +(n[0]=='0')
},
'+':function(n){//是正数
return +(n[0]!='0' && n[0]!='-')
},
'-':function(n){//是负数
return +(n[0]=='-')
},
}
},
opr1:function(op,n,latex){//一元运算 latex指定不计算,得到形式字符串(LaTeX格式)
if(op=='-'){//相反数
}
if(op=='1/'){//倒数
}
},
oprs:function(op,A,latex){//多元运算 latex指定不计算,得到形式字符串(LaTeX格式)
if(ZLR('+ - * / × ÷').indexOf(op)>-1){
}
if(op=='^'){
}
}
//下列涉及数字转换
},percnt2n=function(n){//百分数转小数
var p=''+n,A=p.replace(/[%‰‱]/,'').split('.'),pcnt='%‰‱'.indexOf(p.substr(-1))+2;
if(pcnt>1){
if(A.length<2){
A.push('');
}
A[0]=A[0].replace(/(\d)/,'0'.repeat(pcnt)+'$1');
A[1]=A[0].substr(-pcnt)+A[1];
A[0]=A[0].substr(0,A[0].length-pcnt).replace(/^-?0+(.)/,'$1');
}
return A.join('.')
},n2percnt=function(n,dgts,force){/*小数化百分比 [小数, 小数位数, 强制保留]
参数force 强制保留几位小数(尾0不丢弃)
*/
var d=dgts||0,p=percnt2n(n),ds=0;
if(/\./.test(p)){
ds=p.split('.')[1].length
}
p=(+p*100).toFixed(d||ds);
if(!force){
p=nTrim(p)
}
return p+'%'
},n2frac=function(n,len){/*小数转成分数
假分数improper
带分数vulgar 暂不支持
真分数
参数 len 指定循环节长度(n最末尾的m个数字作为循环节)
*/
var p=percnt2n(n),A=p.split('.');
if(/^-/.test(p)){
return '-'+n2frac(p.substr(1),len)
}
if(/\//.test(p)){
if(A.length<2){
return p
}else{
A=p.split('/');
return n2frac(A[0])
}
}
if(A.length>1){
if(len){//循环小数
var m=+len;
if(A[0]=='0' && A[1].length==m){//纯循环小数
/*
0.a...b a...b a...b ...
q*a...b*(1-q^n)/(1-q) 其中q=10^(-m)
n→+∞,取极限,得到q*a...b/(1-q) = a...b/9...9
*/
A[0]=ZLR('9',m);
return fracReduct(A[1],A[0])
}else{//混循环
var B=[A.join('').substr(0,p.length-1-m),A.join('').substr(-m)];
/*
c...d . a...b a...b a...b ...
c...d+q*a...b*(1-q^n)/(1-q) 其中q=10^(-m)
n→+∞,取极限,得到c...d+q*a...b/(1-q) = c...d + a...b/9...9
= [c...d*(10^m-1) + a...b]/9...9 = [c...d*10^m + a...b - c...d]/9...9
*/
var A0l=A[0].length,A1l=A[1].length, B0l=B[0].length;
return fracOpr('+',A0l==B0l?B[0]:(A0l<B0l?B[0].substr(0,A0l)+'.'+B[0].substr(A0l-B0l):B[0]+ZLR('0',A0l-B0l)),
fracOpr('/',B[1]+ZLR('0',Math.max(m-A1l,0)),ZLR('9',m)+ZLR('0',Math.max(A1l-m,0))))
}
}else{
A[0]=+A[0].replace(/^-/,'');
A[1]=A[1].replace(/0+$/,'');
A[1]=[+A[1],A[1].length,A[1].length];
while(!(A[1][0]%2) && A[1][1]){
A[1][0]/=2;
A[1][1]--;
}
while(!(A[1][0]%5) && A[1][2]){
A[1][0]/=5;
A[1][2]--;
}
A[1][1]=Math.pow(2,A[1][1])*Math.pow(5,A[1][2]);
A[0]=(/^-/.test(p)?'-':'')+(A[0]*A[1][1]+A[1][0])+'/'+A[1][1]
}
}
return A[0]
},n2ArabBig=function(n){//数字转大号阿拉伯数字
var SN='0123456789';
return (''+n).replace(/\d/g,function(s){return SN[s]});
},n2Roman=function(m,c){/*I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)
参数c 指定小写
I II III IV V VI VII VIII IX X XI XII XIII XIV XV
每3位一个组合,加几个横线,表示乘以1000的几次幂
1,2,3 以几个1表示
4,9,以5,10前放个1表示
6,7,8, 11,12,13以5,10后放几个1表示
*/
var n=+m,t=''+m,tl=t.length, ks=Math.ceil(tl/3),r='',caps=+c||0,f1=function(x,c){//个位数
var u=('0'+x).substr(-1),v=+u,c=+c||0;
return v<4?ZLR('Ii'[c],v):(v==9||v==4?'Ii'[c]+'VvXx'[+(v==9)*2+c]:'Vv'[c]+ZLR('Ii'[c],v-5))
},f2=function(x,c){//两位数
var u=('00'+x).substr(-2),u0=u[0],u1=u[1],v0=+u0,v1=+u1,c=+c||0;
return (v0<4?ZLR('Xx'[c],v0):(v0==9||v0==4?'Xx'[c]+'LlCc'[+(v0==9)*2+c]:'Ll'[c]+ZLR('Xx'[c],v0-5)))+f1(v1,c)
},f3=function(x,c){//三位数
var u=('000'+x).substr(-3),u0=u[0],u1=u.substr(1),v0=+u0,v1=+u1,c=+c||0;
return (v0<4?ZLR('Cc'[c],v0):(v0==9||v0==4?'Cc'[c]+'DdMm'[+(v0==9)*2+c]:'Dd'[c]+ZLR('Cc'[c],v0-5)))+f2(v1,c)
},f4=function(x,c){//四位数
var u=('0000'+x).substr(-4),u0=u[0],u1=u.substr(1),v0=+u0,v1=+u1,c=+c||0;
return (v0<4?ZLR('Mm'[c],v0):kxo(f1(v0,c)))+f3(v1,c)
};
if(tl<5){
return [f1,f2,f3,f4][tl-1](n,caps)
}
r=f3(t.substr(-3),caps);
tl=ks*3;
t=('00'+t).substr(-tl);
////console.log(t);
for(var i=2;i<ks+1;i++){
////console.log(t.substr(tl-i*3,3));
r=Arrfc(copyA(kxo,i-1),f3(t.substr(tl-i*3,3),caps))+r;
}
return r
},Roman2n=function(s){//罗马数字(如有横线,字母后加逗号)转成普通数字
var fi=function(t){//判断单个罗马字母表示几位数
return t==''?0:(/IV/i.test(t)?1:(/XL/i.test(t)?2:(/CD/i.test(t)?3:4)))
},k2n=function(t){/*将千以内罗马字母转成数字
*/
var tl=t.length,r;
if(tl){
// //console.log(t);
var t0=t[0].toUpperCase(),t1=(t[1]||'').toUpperCase(),ti0=fi(t0),ti1=fi(t1),is5=/[VLD]/.test(t0),ten=Math.pow(10,(is5?'VLD':'IXCM').indexOf(t0));
if(is5){
r=ten*5;
if(/[XCM]/.test(t1) && ti0==ti1){
t1=t.replace(new RegExp('^.'+t1+'+','i'),'');
r+=ten*(tl-t1.length-1)+k2n(t1);
}else{
r+=k2n(t.substr(1));
}
}else if(ti1==ti0+1){//^10 100
// //console.log('^10 100');
r=ten*9+k2n(t.substr(2))
}else if(ti1==ti0 && /[VLD]/.test(t1)){//^10 50
// //console.log('^10 50');
r=ten*4+k2n(t.substr(2))
}else if(t1==t0){//^10+
// //console.log('^10+');
t1=t.replace(new RegExp('^'+t0+'+','i'),'');
r=ten*(tl-t1.length)+k2n(t1);
}else{
// //console.log('^10 1 10*');
r=ten+k2n(t.substr(1));
}
return r
}
return 0
};
return s.replace(/\D+,/g, function(t){return ('00'+k2n(t.replace(',',''))).substr(-3)}).replace(/\D+/g, function(t){return ('00'+k2n(t)).substr(-3)}).replace(/^0+/,'')
//下列涉及数字正则
},nRegofab=function(s){/*1a2a3b 含字母数字串,转为正则
1aaa -> 1(.)\1{2}
1a2 -> 1(.)[2]
*/
var t=s;
if(/a/.test(s)){
for(var i=0;i<26;i++){
var c=String.fromCharCode(97+i);
if(t.indexOf(c)>-1){
t=t.replace(new RegExp(c+'+[^'+c+']?','gi'), function(x){
var l=x.length;
if(/\d/.test(x[l-1])){
return copyA('\\'+(i+1),l-1).join('')+'['+x[l-1]+']'
}else{
return x.replace(new RegExp(c,'gi'),'\\'+(i+1))
}
}).replace('\\'+(i+1),'(.)');
}else{
return t
}
}
}
return t
},nReg2dot=function(r){//数字正则转换成点号表达式。为简化,正则做限制:不允许使用*,只允许[] () . \数字1~9 {数字}
var s=r.replace(/\[[^\]]+\]/g,'.').replace(/(\\\d|[\.\d])\{\d+\}/g,
function(t){return ZLR(t.replace(/\{.+/,''),+t.replace(/.+\{|\}/g,''))}).replace(/(\(\.+\))\{\d+\}/g,
function(t){return t.replace(/\{.+/,'')+ZLR(t.replace(/\).+|\(/g,''),+t.replace(/.+\{|\}/g,'')-1)});
for(var i=1;i<10;i++){
if(/\(/.test(s)){
var p=s.match(/\([^\)]+\)/g)[0].replace(/\(|\)/g,'');
s=s.replace(new RegExp('\\\\'+i,'g'),p).replace(/\([^\)]+\)/,p);
}else{
break
}
}
return s
},nReg2digits=function(r){//正则转换成满足正则条件(但(\d+).+\1这种无法精确满足)的数字串(含[])。为简化,正则做限制:不允许使用*,只允许[] () . \数字1~9 {数字}
var s=r.replace(/(\\\d|[\.\d])\{\d+\}/g,function(t){return ZLR(t.replace(/\{.+/,''),+t.replace(/.+\{|\}/g,''))})
.replace(/\./g,'[0123456789]').replace(/\d-\d/g,function(t){return seqsA(t.replace('-','~')).join('')})
.replace(/\^\d+/g,function(t){return '0123456789'.replace(new RegExp('['+t.substr(1)+']','g'),'')})
.replace(/\[\d+\]\{\d+\}/g,
function(t){return ZLR(t.replace(/\]\{.+/,'')+']',+t.replace(/.+\{|\}/g,''))})
.replace(/(\(\.+\))\{\d+\}/g,
function(t){return t.replace(/\{.+/,'')+ZLR(t.replace(/\).+|\(/g,''),+t.replace(/.+\{|\}/g,'')-1)});
for(var i=1;i<10;i++){
if(/\(/.test(s)){
var p=s.match(/\([^\)]+\)/g)[0].replace(/\(|\)/g,'');
s=s.replace(new RegExp('\\\\'+i,'g'),p).replace(/\([^\)]+\)/,p);
}else{
break
}
}
return s
},nReg2A=function(r){//正则转换成满足正则条件(但(\d+).+\1这种无法精确满足)的笛卡尔数组。为简化,正则做限制:不允许使用*,只允许[] () . \数字1~9 {数字}
var s=nReg2digits(r);
return Arrf(function(t){return t.join('')}, cartestian(eval(('['+s+']').replace(/[\d\]](?!\]|$)/g,'$&,')))).filter(function(t){return t[0]!='0'})
//下列涉及数字识别
},is0=function(t){return +/^0$/.test(t)
},nis=function(a,pos,negA,pos1,neg1){/*判断正整数a是否满足表达式:整数,2n,2n+1,3n,3n-1,p素数,c合数
pos 必须都满足的表达式组
negA 必须都不满足的表达式组
pos1 表达式组中至少有1个被满足
neg1 表达式组中至少有1个不被满足
*/
var n=+a,pA=(pos||'').split(','),nA=(negA||'').split(','),p1A=(pos1||'').split(','),n1A=(neg1||'').split(',');
var f=function(k,e){//判断满足表达式
if(/[pc]/.test(e)){
return e=='p' ^ !isPrime(k) //异或
}
if(/n/.test(e)){//算术表达式
var b=+(e.split('n')[0])||1, r=+e.split('n')[1]||0;
if(r<0){r+=b}
return +((+k)%b==r)
}
return +(''+k==e) //常数
};
for(var i=0,l=pA.length;i<l;i++){
var e=pA[i];
if(e && !f(n,e)){
return 0
}
}
for(var i=0,l=nA.length;i<l;i++){
var e=nA[i];
if(e && f(n,e)){
return 0
}
}
if(pos1){
var r=0;
for(var i=0,l=p1A.length;i<l;i++){
var e=p1A[i];
if(e && f(n,e)){
r=1;
break;
}
}
if(!r){
return 0
}
}
if(neg1){
var r=0;
for(var i=0,l=n1A.length;i<l;i++){
var e=n1A[i];
if(e && !f(n,e)){
r=1;
break;
}
}
if(!r){
return 0
}
}
return 1
},nAis=function(A,pos,negA, pos1,neg1, pos1All,neg1All, posA1,negA1){/*判断数组A中正整数a是否满足表达式
pos 必须都满足的表达式组
negA 必须都不满足的表达式组
pos1 表达式组中每个表达式至少有A中1个元素满足 满射
neg1 表达式组中每个表达式至少有A中1个元素不满足 满射
pos1All 至少有A中1个元素满足表达式组中所有表达式
neg1All 至少有A中1个元素不满足表达式组中所有表达式
posA1 A中元素都满足表达式组中至少1个表达式 单射
negA1 A中元素都不满足表达式组中至少1个表达式 单射
*/
var n=A.length,p1A=(pos||'').split(','),nA=(negA||'').split(',');
if(pos || negA){
for(var i=0;i<n;i++){
if(pos && !nis(A[i],pos) || negA && !nis(A[i],'',negA)){
return 0
}
}
}
if(posA1 || negA1){
for(var i=0;i<n;i++){
if(posA1 && !nis(A[i],'','',posA1) || negA1 && !nis(A[i],'','','',posA1)){
return 0
}
}
}
if(pos1All){
var r=0;
for(var i=0;i<n;i++){
if(nis(A[i],pos1All)){
r=1;
break;
}
}
if(!r){//A中没有元素全满足
return 0
}
}
if(neg1All){
var r=0;
for(var i=0;i<n;i++){
if(nis(A[i],'',neg1All)){
r=1;
break;
}
}
if(!r){//A中没有元素全不满足
return 0
}
}
if(pos1){
for(var i=0,l=p1A.length;i<l;i++){
var r=0;
for(var j=0;j<n;j++){
var a=A[j];
if(nis(a,p1A[i])){//只要有1个元素a满足
r=1;
break;
}
}
if(!r){//A中没有元素满足
return 0
}
}
}
if(neg1){
for(var i=0,l=n1A.length;i<l;i++){
var r=0;
for(var j=0;j<n;j++){
var a=A[j];
if(nis(a,'',n1A[i])){//只要有1个元素a不满足
r=1;
break;
}
}
if(!r){//A中没有元素满足
return 0
}
}
}
return 1
},nisd=function(n,notNeg){//判断表达式是数字(仅整数、小数) 参数notNeg 指定是否非负
return /^-?\d+\.?\d*$/.test(n) && (notNeg?!/-/.test(n):1)
},nisVd=function(n,notNeg){//判断表达式是单字母或数字
return isVar(n)||nisd(n,notNeg)
},nisVid=function(n,notNeg){//判断表达式是单字母(可含下标格式:A_i A_12 A_{1i} A_(1i) A_(10,23) A_(i,j) A_{i,j} A_{i_1} A_{i_{1k}} A_{i_1,j_2} A_{i_{1m},j_{2n}} )或数字
if(nisVd(n,notNeg)){
return true
}
if(notNeg && /^-\d+/.test(n) || !notNeg && /^[^a-z]/i.test(n)){
return false
}
if(/_/.test(n) && isVar(n.split('_')[0])){
var n1=n.split('_')[1];
if(nisVd(n1)){return true}
if(/^\(.+\)$/.test(n1) || /^\{.+\}$/.test(n1)){
n1=n1.replace(/^.|.$/g,'');
if(/^[\da-z]+[,\da-z]*$/i.test(n1) || nisVid(n1)){return true}
if(/,/.test(n1)){
return Arrf(nisVid,n1.split(',')).indexOf(false)<0
}
}
}
return false
},nisSupSuffix=function(n){//判断表达式是上标后缀
return /^[\*TH†]$/.test(n)
},nisfrac=function(n,notNeg){//判断表达式是有理数 参数notNeg 指定是否非负
return /^-?\d+[/]?\d*$/.test(n) && (notNeg?!/-/.test(n):1)
},nisn=function(n0,sign,qType,fracType){/*判断表达式是数字(整数、分数、有理数) 不考虑小数、百(千、万)分数等情况
参数
sign 符号为(-1负数,0,1正数) 默认值:null任意
qType 有理数类型(-1小数,0整数,1分数) 默认值:null任意
fracType 分数类型
-2假分数(分子>=分母)
-1非既约分数(可约分)
0(化简后是整数)的假分数
1最简分数(既约分数,不含整数)
2真分数(分子<分母))
默认值:null任意
非null, 则认为qType=1
*/
var n=nTrim(n0),l=arguments.length;
if(!/^-?\d+([\/\.]\d+)?$/.test(n)){
return 0
}
if(l==1){
return 1
}
if(sign===1 && (/^-/.test(n) || n=='0') || sign===-1 && !/^-/.test(n) || sign===0 && n!='0'){
return 0
}
if(qType===-1 && !/^-?\d+\.\d+$/.test(n) || qType===0 && !/^-?\d+$/.test(n) || (qType===1||l>3) && !/^-?\d+\/\d+$/.test(n)){
return 0
}
if(l>3){
var A=n.replace(/-/,'').split('/');
if(fracType===0 && A[0]!=A[1] || fracType===2 && !Integer.is.b2['<'](A[0],A[1]) || fracType===-2 && Integer.is.b2['<'](A[0],A[1])){
return 0
}
var F=FracReduct(n);
if(fracType===-1 && F==n|| fracType===1 && F!=n){
return 0
}
}
return 1
//下列涉及数字精度计算
},digi=function(n,k){//精确到小数位,然后去除小数尾0
return +(n.toFixed(k||2).replace(/\.0+$/,'').replace(/(\.\d)0/,'$1'));
},Nsqrt=function(n){/*大整数取平方根(向下取整) n是BigInt类型
Math.sqrt(Number(444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444n))
2.1081851067789195e+55
a² < x² < b²
(a+b)^2=a^2+2ab+b^2
2ab+b^2=(ab+b^2/2)^2
目前最好的算法,是卡马克算法(优点:无除法,循环迭代少,精度高;缺点:依赖一个Magic Number神奇初始值,需要理解数字存储机制,难理解)
其它算法:二分法(慢),牛顿法
https://blog.csdn.net/yutianzuijin/article/details/78839981
2345436565565465464576859231434
2
*/
if(BigInt){
var r=Math.trunc(Math.sqrt(Number(n))), m=BigInt(0);
if(/e/.test(r)){
r=BigInt((''+r).replace(/\.|e.+/g,'')+'0'.repeat(+(''+r).split('+')[1]-(''+r).replace(/.\.|e.+/g,'').length))
}else{
r=BigInt(r)
}
while(m<n){
r++;
m=r*r;
}
return r
}else{
return Math.trunc(Math.sqrt(Number(n)))
}
//下列涉及分数化简计算
},fracReduct=function(m,n){/*约分 分子、分母都是整数
返回字符串:a/b 或者整数a
*/
var a=nTrim(m),b=nTrim(n),t=gcd([a,b]);
if(a=='0'){return 0}
var s=a[0]=='-' ^ b[0]=='-'?'-':'';
a=Integer.oprs('/',[a.replace('-',''),t])[0];
b=Integer.oprs('/',[b.replace('-',''),t])[0];
return s+a+(b=='1'?'':'/'+b)
},FracReduct=function(f,vulgar){/*化成既约分数 返回字符串
参数f 可以是字符串,或数组[分子,分母]
参数 vulgar 指定返回带分数数组['k','a/b']
*/
if(isArr(f)){
var v=fracReduct(f[0],f[1]);
}else{
var m=nTrim(f), md=/[\.%‰‱]/.test(m),mf=/\//.test(m),v=''+m;
if(md){
v=n2frac(m)
}else if(mf){
v=m.split('/');
v=fracReduct(v[0],v[1]);
}else{//是整数
v=v.replace(/^0+/,'')||'0'
}
}
if(vulgar){
v=v.split('/');
if(v.length==2){
var v0=+v[0].replace(/-/,''),v1=+v[1];
return [v[0][0].replace(/[^-]/,'')+Math.floor(v0/v1),(v0%v1)+'/'+v1] //这里需要用Integer.oprs('/',[v0,v1]) 进行改造,以支持大数
}else{
return ['0',v.join('/')]
}
}
return v
},fracOpr=function(o,x,y){/*分数二元运算
分数运算 返回 字符串
+ - * / 封闭
^ 整数幂 封闭
分数幂 得到开根号的无理数 (a/b)^(c/d)
含根号数乘除有理数
关系运算 返回 逻辑0,1
*/
//console.log(o,x,y);
var A=(''+FracReduct(x)).split('/'),B=(''+FracReduct(y)).split('/'),l=A.length+B.length,s,op=opreplace0(o,1),m=A.join('/'),n=B.join('/');
if(/[\|∤]/.test(op)){
if(+m==0||l>2){return 0}
return +(op=='|' && !((+n)%(+m))||op=='∤' && (+n)%(+m))
}
if(/[≤=≥<>]=?/.test(op)){
var r=fracOpr('-',m,n);
if(/^0$/.test(r)){
return +/[≤=≥]/.test(op)
}if(/^-/.test(r)){
return +/[≤<]/.test(op)
}else{
return +/[≥>]/.test(op)
}
}
//console.log(op,m,n);
var Ahasi=/i/.test(m),Bhasi=/i/.test(n);
if(Ahasi || Bhasi){
//var mon=(m[0]=='-' && op!='^'?'-'+pp(m.substr(1)):pp(m))+op+pp(n); //mathjs bug math.simplify(math.parse('(-1/24)*(4i-8)')).toString()
var mon=pp(m)+op+pp(n);
console.log(mon);
if(/√/.test(mon)){
mon=mon.replace(/√(\d+)/g,'^(1/$1)');
}
var r=Mfn.fromStr(math.simplify(math.parse(mon)).toString()).toStr();
console.log('r=',r);
return r
}
if(l==2){//整数运算
if(op=='/'){
return fracReduct(m,n)
}else if(op=='^'){
return Integer.oprs(op,[m,n]) //Math.pow(m,n)
}else if(op=='#'){//商,忽略余数 相当于JS中的 (m-m%n)/n 以及 Math.floor(m/n)
return Integer.oprs('/',[m,n])[0]
}else if(op=='%'){//余数 相当于JS中的 m%n
return Integer.oprs('/',[m,n])[1]
}else if(/^[\+\-\*\/]$/.test(op)){//
return Integer.oprs(op,[m,n])
}else{
//console.log(m,op,n);
return eval(m+op+pp(n)) //加括号,防止n是负数时报错
}
}
if(l==3){
if(A.length==1){
A[1]=1
}else{
B[1]=1
}
}
A[0]=+A[0];A[1]=+A[1];//m的分子,分母
B[0]=+B[0];B[1]=+B[1];//n的分子,分母
if(/[\+\-]/.test(op)){
// //console.log(A,B);
s=lcm([A[1],B[1]]);
A[0]=s/A[1]*A[0];
B[0]=s/B[1]*B[0];
// //console.log(A,B);
return fracReduct(A[0]+B[0]*(op=='+'?1:-1),s)
}else if(/[\*\/]/.test(op)){
return fracReduct(A[0]*B[op=='*'?0:1],A[1]*B[op=='*'?1:0])
}else if(/[\^]/.test(op)){
if(l==3 && A[1]!=1){ //分数的整数幂
if(!B[0]){
return 1
}
s=Math.abs(B[0]);
if(s!=1){
A[0]=Math.pow(A[0],s);
A[1]=Math.pow(A[1],s);
}
if(B[0]<0){
s=A[0];
A[0]=A[1];
A[1]=Math.abs(s);
if(s<0){
A[0]=-A[0];
}
}
return A[0]+(A[1]==1?'':'/'+A[1])
}
if(B[0]<0){ //负幂
B[0]=-B[0];
s=A[0];
A[0]=A[1];
A[1]=Math.abs(s);
if(s<0 && B[0]%2){
A[0]=-A[0]
}
}
//var isneg=A[0]<0?(B[1]%2 && B[0]%2?'-':(B[0]%2?'(-1)^('+B[0]+'/'+B[1]+')×':'')):'';
var isneg=A[0]<0?(B[1]%2 && B[0]%2?'-':(B[0]%2?(B.join('/')=='1/2'?'i':'(-1)^('+B[0]+'/'+B[1]+')×'):'')):'';
if(A[0]<0){
A[0]=-A[0]
}
//console.log('有理数幂',A.join('/'),B.join('/'),A,B);
//下面对A分子,分母分别进行因式分解,因子公重数(>1),如果与B分母,可以约分,则化简
if(A[1]!=1){//分数的分数幂
var a=factorA(A[0]),ga=+gcd(a[1]);
var b=factorA(A[1]),gb=+gcd(b[1]);
//console.log('A: ','a=',a.join(' ;; '),'b=',b.join(' ;; '),'ga = ',ga,'gb = ',gb)
if(gb>1){
var gab=A[0]==1?gb:+gcd([ga,gb]);
//var gab=+gcd([ga,gb]);
if(gab>1){
//console.log('gab= ',gab)
var gabc=+gcd([gab,B[1]]);
if(gabc>1){
//console.log(A,B,'gabc = ',gabc);
//console.log('a = ',a.join(' ; '),'b = ',b.join(' ; '));
a[1]=Arrf(function(x){return x=='1'?x:Integer.oprs('/',[x,gabc])[0]},a[1]);
//console.log('a = ',a[0],' ;;; ',a[1]);
a=factorA2n(a);
//console.log('a = ',a);
b[1]=Arrf(function(x){return x=='1'?x:Integer.oprs('/',[x,gabc])[0]},b[1]);
b=factorA2n(b);
//console.log('b = ',b);
A=[a,b];
//console.log('A = ',A);
B[1]/=gabc;
if(B[1]==1){//整数幂
if(B[0]==1){
return isneg?isneg+(isneg=='-'?A.join('/'):pp(A.join('/'))):A.join('/')
}else{//2^10 3^6 4^5 5^4 (6~10)^3 (11~32)^2
//console.log(A,B);
var m=max(A);
if(m<=32 && B[0]<=10 && Math.pow(m,B[0])<=1024){
Arrf(function(t){return Math.pow(t,B[0])},A);
return isneg+Arrf(function(t){return Math.pow(t,B[0])},A).join('/')
}else{
return isneg+pp(A.join('/'))+'^'+B[0];
}
}
}
}
}
}
}else{//整数的分数幂
if(A[0]=='1'){
return isneg||'1'
}
var a=factorA(A[0]);
//遍历质因数,重数是分数幂的分母的倍数,则约分;或者重数比分数幂的分母大时,减去最大的倍数,约分后,移到根号外
var IA=[[],[]];
// console.log(a.join(' & '),B[1]);
a[1]=Arrf(function(x,i){
if(x!='1' && Integer.is.b2['≤'](B[1],x)){ //Integer.is.b2['|'](B[1],x)
var y=Integer.oprs('/',[x,B[1]]);
IA[0].push(a[0][i]);
IA[1].push(y[0]);
return y[1]
}
return x
},a[1]);
if(IA[0].length){
a=factorA2n(a);
var k=isneg+factorA2n(IA);
if(a=='1'){
return k
}
if(a=='-1'){
if(B.join('/')=='1/2'){
return k+'i'
}
console.log(-1,B.join('/'));
return k+pp(a)+'^('+B.join('/')+')'
}
//A=[a,1];
return k+'⋅'+a+'^('+B.join('/')+')'
}
return isneg+A[0]+'^('+B.join('/')+')';
}
//console.log('最终 ',isneg+pp(A.join('/'))+'^('+B.join('/')+')');
return isneg+pp(A.join('/'))+'^('+B.join('/')+')';
}
};
|
{
"pile_set_name": "Github"
}
|
# This is an auto generated Dockerfile for ros:perception
# generated from docker_images/create_ros_image.Dockerfile.em
FROM ros:kinetic-ros-base-xenial
# label ros packages
LABEL sha256.ros-kinetic-perception=7c8a2df83dbaf9bce97adcaa8ad1bf91781c27e5938417e47bf404411aca36f5
# install ros packages
RUN apt-get update && apt-get install -y --no-install-recommends \
ros-kinetic-perception=1.3.2-0* \
&& rm -rf /var/lib/apt/lists/*
|
{
"pile_set_name": "Github"
}
|
Notice 0: Reading LEF file: bus1.lef
Notice 0: Created 1 library cells
Notice 0: Finished LEF file: bus1.lef
Instance bus1
Cell: bus4
Library: bus1
Path cells: bus4
Input pins:
in[0] input in[0]
in[2] input in[2]
clk input clk
in[3] input in[3]
in[1] input in[1]
Output pins:
out[2] output out[2]
out[0] output out[0]
out[3] output out[3]
out[1] output out[1]
|
{
"pile_set_name": "Github"
}
|
#include "JSONDataParser.h"
DRAGONBONES_NAMESPACE_BEGIN
void JSONDataParser::_getCurvePoint(
float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4,
float t,
Point& result
)
{
const auto l_t = 1.0f - t;
const auto powA = l_t * l_t;
const auto powB = t * t;
const auto kA = l_t * powA;
const auto kB = 3.0f * t * powA;
const auto kC = 3.0f * l_t * powB;
const auto kD = t * powB;
result.x = kA * x1 + kB * x2 + kC * x3 + kD * x4;
result.y = kA * y1 + kB * y2 + kC * y3 + kD * y4;
}
void JSONDataParser::_samplingEasingCurve(const rapidjson::Value& curve, std::vector<float>& samples)
{
int curveCount = curve.Size();
int stepIndex = -2;
for (std::size_t i = 0, l = samples.size(); i < l; ++i)
{
float t = (float)(i + 1) / (l + 1); // float
while ((stepIndex + 6 < curveCount ? curve[stepIndex + 6].GetDouble() : 1) < t) // stepIndex + 3 * 2
{
stepIndex += 6;
}
const auto isInCurve = stepIndex >= 0 && stepIndex + 6 < curveCount;
const auto x1 = isInCurve ? curve[stepIndex].GetDouble() : 0.0f;
const auto y1 = isInCurve ? curve[stepIndex + 1].GetDouble() : 0.0f;
const auto x2 = curve[stepIndex + 2].GetDouble();
const auto y2 = curve[stepIndex + 3].GetDouble();
const auto x3 = curve[stepIndex + 4].GetDouble();
const auto y3 = curve[stepIndex + 5].GetDouble();
const auto x4 = isInCurve ? curve[stepIndex + 6].GetDouble() : 1.0f;
const auto y4 = isInCurve ? curve[stepIndex + 7].GetDouble() : 1.0f;
float lower = 0.0f;
float higher = 1.0f;
while (higher - lower > 0.0001f)
{
const auto percentage = (higher + lower) * 0.5f;
_getCurvePoint(x1, y1, x2, y2, x3, y3, x4, y4, percentage, _helpPoint);
if (t - _helpPoint.x > 0.0f)
{
lower = percentage;
}
else {
higher = percentage;
}
}
samples[i] = _helpPoint.y;
}
}
void JSONDataParser::_parseActionDataInFrame(const rapidjson::Value& rawData, unsigned frameStart, BoneData* bone, SlotData* slot)
{
if (rawData.HasMember(EVENT))
{
_mergeActionFrame(rawData[EVENT], frameStart, ActionType::Frame, bone, slot);
}
if (rawData.HasMember(SOUND))
{
_mergeActionFrame(rawData[SOUND], frameStart, ActionType::Sound, bone, slot);
}
if (rawData.HasMember(ACTION))
{
_mergeActionFrame(rawData[ACTION], frameStart, ActionType::Play, bone, slot);
}
if (rawData.HasMember(EVENTS))
{
_mergeActionFrame(rawData[EVENTS], frameStart, ActionType::Frame, bone, slot);
}
if (rawData.HasMember(ACTIONS))
{
_mergeActionFrame(rawData[ACTIONS], frameStart, ActionType::Play, bone, slot);
}
}
void JSONDataParser::_mergeActionFrame(const rapidjson::Value& rawData, unsigned frameStart, ActionType type, BoneData* bone, SlotData* slot)
{
const auto actionOffset = _armature->actions.size();
const auto& actions = _parseActionData(rawData, type, bone, slot);
ActionFrame* frame = nullptr;
for (const auto action : actions)
{
_armature->addAction(action, false);
}
if (_actionFrames.empty()) // First frame.
{
_actionFrames.resize(1);
_actionFrames[0].frameStart = 0;
}
for (auto& eachFrame : _actionFrames) // Get same frame.
{
if (eachFrame.frameStart == frameStart)
{
frame = &eachFrame;
break;
}
}
if (frame == nullptr) // Create and cache frame.
{
const auto frameCount = _actionFrames.size();
_actionFrames.resize(frameCount + 1);
frame = &_actionFrames[frameCount];
frame->frameStart = frameStart;
}
for (std::size_t i = 0; i < actions.size(); ++i) // Cache action offsets.
{
frame->actions.push_back(actionOffset + i);
}
}
unsigned JSONDataParser::_parseCacheActionFrame(ActionFrame& frame)
{
const auto frameOffset = _frameArray.size();
const auto actionCount = frame.actions.size();
_frameArray.resize(_frameArray.size() + 1 + 1 + actionCount);
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frame.frameStart;
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count.
for (std::size_t i = 0; i < actionCount; ++i) // Action offsets.
{
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 2 + i] = frame.actions[i];
}
return frameOffset;
}
ArmatureData* JSONDataParser::_parseArmature(const rapidjson::Value& rawData, float scale)
{
const auto armature = BaseObject::borrowObject<ArmatureData>();
armature->name = _getString(rawData, NAME, "");
armature->frameRate = _getNumber(rawData, FRAME_RATE, _data->frameRate);
armature->scale = scale;
if (rawData.HasMember(TYPE) && rawData[TYPE].IsString())
{
armature->type = _getArmatureType(rawData[TYPE].GetString());
}
else
{
armature->type = (ArmatureType)_getNumber(rawData, TYPE, (int)ArmatureType::Armature);
}
if (armature->frameRate == 0) // Data error.
{
armature->frameRate = 24;
}
_armature = armature;
if (rawData.HasMember(CANVAS))
{
const auto& rawCanvas = rawData[CANVAS];
const auto canvas = BaseObject::borrowObject<CanvasData>();
canvas->hasBackground = rawCanvas.HasMember(COLOR);
canvas->color = _getNumber(rawCanvas, COLOR, 0);
canvas->aabb.x = _getNumber(rawCanvas, X, 0.0f) * armature->scale;
canvas->aabb.y = _getNumber(rawCanvas, Y, 0.0f) * armature->scale;
canvas->aabb.width = _getNumber(rawCanvas, WIDTH, 0.0f) * armature->scale;
canvas->aabb.height = _getNumber(rawCanvas, HEIGHT, 0.0f) * armature->scale;
//
armature->canvas = canvas;
}
if (rawData.HasMember(AABB))
{
const auto& rawAABB = rawData[AABB];
armature->aabb.x = _getNumber(rawAABB, X, 0.0f) * armature->scale;
armature->aabb.y = _getNumber(rawAABB, Y, 0.0f) * armature->scale;
armature->aabb.width = _getNumber(rawAABB, WIDTH, 0.0f) * armature->scale;
armature->aabb.height = _getNumber(rawAABB, HEIGHT, 0.0f) * armature->scale;
}
if (rawData.HasMember(BONE))
{
const auto& rawBones = rawData[BONE];
for (std::size_t i = 0, l = rawBones.Size(); i < l; ++i)
{
const auto& rawBone = rawBones[i];
const auto& parentName = _getString(rawBone, PARENT, "");
const auto bone = _parseBone(rawBone);
if (!parentName.empty()) // Get bone parent.
{
const auto parent = armature->getBone(parentName);
if (parent != nullptr)
{
bone->parent = parent;
}
else // Cache.
{
auto& cacheBones = _cacheBones[parentName];
cacheBones.push_back(bone);
}
}
auto iterator = _cacheBones.find(bone->name);
if (iterator != _cacheBones.end())
{
for (const auto child : _cacheBones[bone->name])
{
child->parent = bone;
}
_cacheBones.erase(iterator);
}
armature->addBone(bone);
_rawBones.push_back(bone); // Cache raw bones sort.
}
}
if (rawData.HasMember(IK))
{
const auto& rawIKS = rawData[IK];
for (std::size_t i = 0, l = rawIKS.Size(); i < l; ++i)
{
const auto constraint = _parseIKConstraint(rawIKS[i]);
if (constraint)
{
armature->addConstraint(constraint);
}
}
}
armature->sortBones();
if (rawData.HasMember(SLOT))
{
int zOrder = 0;
const auto& rawSlots = rawData[SLOT];
for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i)
{
armature->addSlot(_parseSlot(rawSlots[i], zOrder++));
}
}
if (rawData.HasMember(SKIN))
{
const auto& rawSkins = rawData[SKIN];
for (std::size_t i = 0, l = rawSkins.Size(); i < l; ++i)
{
armature->addSkin(_parseSkin(rawSkins[i]));
}
}
for (std::size_t i = 0, l = _cacheRawMeshes.size(); i < l; ++i) // Link mesh.
{
const auto rawMeshData = _cacheRawMeshes[i];
const auto& shareName = _getString(*rawMeshData, SHARE, "");
if (shareName.empty()) {
continue;
}
auto skinName = _getString(*rawMeshData, SKIN, DEFAULT_NAME);
if (skinName.empty()) //
{
skinName = DEFAULT_NAME;
}
const auto shareMesh = armature->getMesh(skinName, "", shareName); // TODO slot;
if (shareMesh == nullptr) {
continue; // Error.
}
const auto mesh = _cacheMeshes[i];
mesh->vertices.shareFrom(shareMesh->vertices);
}
if (rawData.HasMember(ANIMATION))
{
const auto& rawAnimations = rawData[ANIMATION];
for (std::size_t i = 0, l = rawAnimations.Size(); i < l; ++i)
{
armature->addAnimation(_parseAnimation(rawAnimations[i]));
}
}
if (rawData.HasMember(DEFAULT_ACTIONS))
{
const auto& actions = _parseActionData(rawData[DEFAULT_ACTIONS], ActionType::Play, nullptr, nullptr);
for (const auto action : actions)
{
armature->addAction(action, true);
if (action->type == ActionType::Play) // Set default animation from default action.
{
const auto animation = armature->getAnimation(action->name);
if (animation != nullptr)
{
armature->defaultAnimation = animation;
}
}
}
}
if (rawData.HasMember(ACTIONS))
{
const auto& actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr);
for (const auto action : actions)
{
armature->addAction(action, false);
}
}
// Clear helper.
_rawBones.clear();
_cacheRawMeshes.clear();
_cacheMeshes.clear();
_armature = nullptr;
_weightSlotPose.clear();
_weightBonePoses.clear();
_cacheBones.clear();
_slotChildActions.clear();
return armature;
}
BoneData* JSONDataParser::_parseBone(const rapidjson::Value& rawData)
{
const auto bone = BaseObject::borrowObject<BoneData>();
bone->inheritTranslation = _getBoolean(rawData, INHERIT_TRANSLATION, true);
bone->inheritRotation = _getBoolean(rawData, INHERIT_ROTATION, true);
bone->inheritScale = _getBoolean(rawData, INHERIT_SCALE, true);
bone->inheritReflection = _getBoolean(rawData, INHERIT_REFLECTION, true);
bone->length = _getNumber(rawData, LENGTH, 0.0f) * _armature->scale;
bone->name = _getString(rawData, NAME, "");
if (rawData.HasMember(TRANSFORM))
{
_parseTransform(rawData[TRANSFORM], bone->transform, _armature->scale);
}
return bone;
}
ConstraintData* JSONDataParser::_parseIKConstraint(const rapidjson::Value& rawData)
{
const auto bone = _armature->getBone(_getString(rawData, BONE, ""));
if (bone == nullptr)
{
return nullptr;
}
const auto target = _armature->getBone(_getString(rawData, TARGET, ""));
if (target == nullptr)
{
return nullptr;
}
const auto constraint = BaseObject::borrowObject<IKConstraintData>();
constraint->scaleEnabled = _getBoolean(rawData, SCALE, false);
constraint->bendPositive = _getBoolean(rawData, BEND_POSITIVE, true);
constraint->weight = _getNumber(rawData, WEIGHT, 1.0f);
constraint->name = _getString(rawData, NAME, "");
constraint->bone = bone;
constraint->target = target;
const auto chain = _getNumber(rawData, CHAIN, (unsigned)0);
if (chain > 0 && bone->parent != nullptr)
{
constraint->root = bone->parent;
constraint->bone = bone;
}
else
{
constraint->root = bone;
constraint->bone = nullptr;
}
return constraint;
}
SlotData* JSONDataParser::_parseSlot(const rapidjson::Value& rawData, int zOrder)
{
const auto slot = BaseObject::borrowObject<SlotData>();
slot->displayIndex = _getNumber(rawData, DISPLAY_INDEX, (int)0);
slot->zOrder = zOrder;
slot->name = _getString(rawData, NAME, "");
slot->parent = _armature->getBone(_getString(rawData, PARENT, ""));
if (rawData.HasMember(BLEND_MODE) && rawData[BLEND_MODE].IsString())
{
slot->blendMode = _getBlendMode(rawData[BLEND_MODE].GetString());
}
else
{
slot->blendMode = (BlendMode)_getNumber(rawData, BLEND_MODE, (int)BlendMode::Normal);
}
if (rawData.HasMember(COLOR))
{
slot->color = SlotData::createColor();
_parseColorTransform(rawData[COLOR], *slot->color);
}
else
{
slot->color = &SlotData::DEFAULT_COLOR;
}
if (rawData.HasMember(ACTIONS))
{
_slotChildActions[slot->name] = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr);
}
return slot;
}
SkinData * JSONDataParser::_parseSkin(const rapidjson::Value& rawData)
{
const auto skin = BaseObject::borrowObject<SkinData>();
skin->name = _getString(rawData, NAME, DEFAULT_NAME);
if (skin->name.empty())
{
skin->name = DEFAULT_NAME;
}
if (rawData.HasMember(SLOT))
{
const auto& rawSlots = rawData[SLOT];
_skin = skin;
for (std::size_t i = 0, l = rawSlots.Size(); i < l; ++i)
{
const auto& rawSlot = rawSlots[i];
const auto& slotName = _getString(rawSlot, NAME, "");
const auto slot = _armature->getSlot(slotName);
if (slot != nullptr)
{
_slot = slot;
if (rawSlot.HasMember(DISPLAY))
{
const auto& rawDisplays = rawSlot[DISPLAY];
for (std::size_t j = 0, lJ = rawDisplays.Size(); j < lJ; ++j)
{
const auto& rawDisplay = rawDisplays[j];
if (!rawDisplay.IsNull())
{
skin->addDisplay(slotName, _parseDisplay(rawDisplay));
}
else
{
skin->addDisplay(slotName, nullptr);
}
}
}
_slot = nullptr;
}
}
_skin = nullptr;
}
return skin;
}
DisplayData* JSONDataParser::_parseDisplay(const rapidjson::Value& rawData)
{
const auto& name = _getString(rawData, NAME, "");
const auto& path = _getString(rawData, PATH, "");
auto type = DisplayType::Image;
DisplayData* display = nullptr;
if (rawData.HasMember(TYPE) && rawData[TYPE].IsString())
{
type = _getDisplayType(rawData[TYPE].GetString());
}
else
{
type = (DisplayType)_getNumber(rawData, TYPE, (int)DisplayType::Image);
}
switch (type)
{
case dragonBones::DisplayType::Image:
{
const auto imageDisplay = BaseObject::borrowObject<ImageDisplayData>();
imageDisplay->name = name;
imageDisplay->path = !path.empty() ? path : name;
_parsePivot(rawData, *imageDisplay);
display = imageDisplay;
break;
}
case dragonBones::DisplayType::Armature:
{
const auto armatureDisplay = BaseObject::borrowObject<ArmatureDisplayData>();
armatureDisplay->name = name;
armatureDisplay->path = !path.empty() ? path : name;
armatureDisplay->inheritAnimation = true;
if (rawData.HasMember(ACTIONS))
{
const auto& actions = _parseActionData(rawData[ACTIONS], ActionType::Play, nullptr, nullptr);
for (const auto action : actions)
{
armatureDisplay->addAction(action);
}
}
else if (_slotChildActions.find(_slot->name) != _slotChildActions.cend())
{
const auto displays = _skin->getDisplays(_slot->name);
if (displays == nullptr ? _slot->displayIndex == 0 : (std::size_t)_slot->displayIndex == displays->size())
{
for (const auto action : _slotChildActions[_slot->name])
{
armatureDisplay->addAction(action);
}
_slotChildActions.erase(_slotChildActions.find(_slot->name));
}
}
display = armatureDisplay;
break;
}
case dragonBones::DisplayType::Mesh:
{
const auto meshDisplay = BaseObject::borrowObject<MeshDisplayData>();
meshDisplay->vertices.inheritDeform = _getBoolean(rawData, INHERIT_DEFORM, true);
meshDisplay->name = name;
meshDisplay->path = !path.empty() ? path : name;
meshDisplay->vertices.data = _data;
if (rawData.HasMember(SHARE))
{
_cacheRawMeshes.push_back(&rawData);
_cacheMeshes.push_back(meshDisplay);
}
else
{
_parseMesh(rawData, *meshDisplay);
}
display = meshDisplay;
break;
}
case dragonBones::DisplayType::BoundingBox:
{
const auto boundingBox = _parseBoundingBox(rawData);
if (boundingBox != nullptr)
{
const auto boundingBoxDisplay = BaseObject::borrowObject<BoundingBoxDisplayData>();
boundingBoxDisplay->name = name;
boundingBoxDisplay->path = !path.empty() ? path : name;
boundingBoxDisplay->boundingBox = boundingBox;
display = boundingBoxDisplay;
}
break;
}
}
if (display != nullptr && rawData.HasMember(TRANSFORM))
{
_parseTransform(rawData[TRANSFORM], display->transform, _armature->scale);
}
return display;
}
void JSONDataParser::_parsePivot(const rapidjson::Value& rawData, ImageDisplayData& display)
{
if (rawData.HasMember(PIVOT))
{
const auto& rawPivot = rawData[PIVOT];
display.pivot.x = _getNumber(rawPivot, X, 0.0f);
display.pivot.y = _getNumber(rawPivot, Y, 0.0f);
}
else
{
display.pivot.x = 0.5f;
display.pivot.y = 0.5f;
}
}
void JSONDataParser::_parseMesh(const rapidjson::Value& rawData, MeshDisplayData& mesh)
{
const auto& rawVertices = rawData[VERTICES];
const auto& rawUVs = rawData[UVS];
const auto& rawTriangles = rawData[TRIANGLES];
const auto vertexCount = rawVertices.Size() / 2;
const auto triangleCount = rawTriangles.Size() / 3;
const auto vertexOffset = _floatArray.size();
const auto uvOffset = vertexOffset + vertexCount * 2;
const auto meshOffset = _intArray.size();
const auto meshName = _skin->name + "_" + _slot->name + "_" + mesh.name; // Cache pose data.
mesh.vertices.offset = meshOffset;
_intArray.resize(_intArray.size() + 1 + 1 + 1 + 1 + triangleCount * 3);
_intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexCount] = vertexCount;
_intArray[meshOffset + (unsigned)BinaryOffset::MeshTriangleCount] = triangleCount;
_intArray[meshOffset + (unsigned)BinaryOffset::MeshFloatOffset] = vertexOffset;
for (std::size_t i = 0, l = triangleCount * 3; i < l; ++i)
{
_intArray[meshOffset + (unsigned)BinaryOffset::MeshVertexIndices + i] = rawTriangles[i].GetUint();
}
_floatArray.resize(_floatArray.size() + vertexCount * 2 + vertexCount * 2);
for (std::size_t i = 0, l = vertexCount * 2; i < l; ++i)
{
_floatArray[vertexOffset + i] = rawVertices[i].GetDouble();
_floatArray[uvOffset + i] = rawUVs[i].GetDouble();
}
if (rawData.HasMember(WEIGHTS))
{
const auto& rawWeights = rawData[WEIGHTS];
const auto& rawSlotPose = rawData[SLOT_POSE];
const auto& rawBonePoses = rawData[BONE_POSE];
const auto& sortedBones = _armature->sortedBones;
std::vector<unsigned> weightBoneIndices;
const unsigned weightBoneCount = rawBonePoses.Size() / 7;
const auto floatOffset = _floatArray.size();
const auto weightCount = (rawWeights.Size() - vertexCount) / 2; // uint
const auto weightOffset = _intArray.size();
const auto weight = BaseObject::borrowObject<WeightData>();
weight->count = weightCount;
weight->offset = weightOffset;
weightBoneIndices.resize(weightBoneCount);
_intArray.resize(_intArray.size() + 1 + 1 + weightBoneCount + vertexCount + weightCount);
_intArray[weightOffset + (unsigned)BinaryOffset::WeigthFloatOffset] = floatOffset;
for (std::size_t i = 0; i < weightBoneCount; ++i)
{
const auto rawBoneIndex = rawBonePoses[i * 7].GetUint();
const auto bone = _rawBones[rawBoneIndex];
weight->addBone(bone);
weightBoneIndices[i] = rawBoneIndex;
_intArray[weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + i] = indexOf(sortedBones, bone);
}
_floatArray.resize(_floatArray.size() + weightCount * 3);
_helpMatrixA.a = rawSlotPose[0].GetDouble();
_helpMatrixA.b = rawSlotPose[1].GetDouble();
_helpMatrixA.c = rawSlotPose[2].GetDouble();
_helpMatrixA.d = rawSlotPose[3].GetDouble();
_helpMatrixA.tx = rawSlotPose[4].GetDouble();
_helpMatrixA.ty = rawSlotPose[5].GetDouble();
for (
std::size_t i = 0, iW = 0, iB = weightOffset + (unsigned)BinaryOffset::WeigthBoneIndices + weightBoneCount, iV = floatOffset;
i < vertexCount;
++i
)
{
const auto iD = i * 2;
const auto vertexBoneCount = rawWeights[iW++].GetUint();
_intArray[iB++] = vertexBoneCount;
auto x = _floatArray[vertexOffset + iD];
auto y = _floatArray[vertexOffset + iD + 1];
_helpMatrixA.transformPoint(x, y, _helpPoint);
x = _helpPoint.x;
y = _helpPoint.y;
for (std::size_t j = 0; j < vertexBoneCount; ++j)
{
const auto rawBoneIndex = rawWeights[iW++].GetUint();
const auto boneIndex = indexOf(weightBoneIndices, rawBoneIndex);
const auto matrixOffset = boneIndex * 7 + 1;
_helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble();
_helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble();
_helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble();
_helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble();
_helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble();
_helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble();
_helpMatrixB.invert();
_helpMatrixB.transformPoint(x, y, _helpPoint);
_intArray[iB++] = boneIndex;
_floatArray[iV++] = rawWeights[iW++].GetDouble();
_floatArray[iV++] = _helpPoint.x;
_floatArray[iV++] = _helpPoint.y;
}
}
mesh.vertices.weight = weight;
_weightSlotPose[meshName] = &rawSlotPose;
_weightBonePoses[meshName] = &rawBonePoses;
}
}
BoundingBoxData* JSONDataParser::_parseBoundingBox(const rapidjson::Value& rawData)
{
BoundingBoxData* boundingBox = nullptr;
BoundingBoxType type = BoundingBoxType::Rectangle;
if (rawData.HasMember(SUB_TYPE) && rawData[SUB_TYPE].IsString())
{
type = _getBoundingBoxType(rawData[SUB_TYPE].GetString());
}
else
{
type = (BoundingBoxType)_getNumber(rawData, SUB_TYPE, (int)type);
}
switch (type)
{
case BoundingBoxType::Rectangle:
boundingBox = BaseObject::borrowObject<RectangleBoundingBoxData>();
break;
case BoundingBoxType::Ellipse:
boundingBox = BaseObject::borrowObject<EllipseBoundingBoxData>();
break;
case BoundingBoxType::Polygon:
boundingBox = _parsePolygonBoundingBox(rawData);
break;
}
if (boundingBox != nullptr)
{
boundingBox->color = _getNumber(rawData, COLOR, 0x000000);
if (boundingBox->type == BoundingBoxType::Rectangle || boundingBox->type == BoundingBoxType::Ellipse)
{
boundingBox->width = _getNumber(rawData, WIDTH, 0.0f);
boundingBox->height = _getNumber(rawData, HEIGHT, 0.0f);
}
}
return boundingBox;
}
PolygonBoundingBoxData* JSONDataParser::_parsePolygonBoundingBox(const rapidjson::Value& rawData)
{
const auto polygonBoundingBox = BaseObject::borrowObject<PolygonBoundingBoxData>();
if (rawData.HasMember(VERTICES))
{
const auto& rawVertices = rawData[VERTICES];
auto& vertices = polygonBoundingBox->vertices;
polygonBoundingBox->vertices.resize(rawVertices.Size());
for (std::size_t i = 0, l = rawVertices.Size(); i < l; i += 2)
{
const auto x = rawVertices[i].GetDouble();
const auto y = rawVertices[i + 1].GetDouble();
vertices[i] = x;
vertices[i + 1] = y;
// AABB.
if (i == 0)
{
polygonBoundingBox->x = x;
polygonBoundingBox->y = y;
polygonBoundingBox->width = x;
polygonBoundingBox->height = y;
}
else
{
if (x < polygonBoundingBox->x)
{
polygonBoundingBox->x = x;
}
else if (x > polygonBoundingBox->width)
{
polygonBoundingBox->width = x;
}
if (y < polygonBoundingBox->y)
{
polygonBoundingBox->y = y;
}
else if (y > polygonBoundingBox->height)
{
polygonBoundingBox->height = y;
}
}
}
polygonBoundingBox->width -= polygonBoundingBox->x;
polygonBoundingBox->height -= polygonBoundingBox->y;
}
else
{
DRAGONBONES_ASSERT(false, "Data error.\n Please reexport DragonBones Data to fixed the bug.");
}
return polygonBoundingBox;
}
AnimationData* JSONDataParser::_parseAnimation(const rapidjson::Value& rawData)
{
const auto animation = BaseObject::borrowObject<AnimationData>();
animation->frameCount = std::max(_getNumber(rawData, DURATION, (unsigned)1), (unsigned)1);
animation->playTimes = _getNumber(rawData, PLAY_TIMES, (unsigned)1);
animation->duration = (float)animation->frameCount / _armature->frameRate; // float
animation->fadeInTime = _getNumber(rawData, FADE_IN_TIME, 0.0f);
animation->scale = _getNumber(rawData, SCALE, 1.0f);
animation->name = _getString(rawData, NAME, DEFAULT_NAME);
if (animation->name.empty())
{
animation->name = DEFAULT_NAME;
}
animation->frameIntOffset = _frameIntArray.size();
animation->frameFloatOffset = _frameFloatArray.size();
animation->frameOffset = _frameArray.size();
_animation = animation;
if (rawData.HasMember(FRAME))
{
const auto& rawFrames = rawData[FRAME];
const auto keyFrameCount = rawFrames.Size();
if (keyFrameCount > 0)
{
for (std::size_t i = 0, frameStart = 0; i < keyFrameCount; ++i)
{
const auto& rawFrame = rawFrames[i];
_parseActionDataInFrame(rawFrame, frameStart, nullptr, nullptr);
frameStart += _getNumber(rawFrame, DURATION, (unsigned)1);
}
}
}
if (rawData.HasMember(Z_ORDER))
{
_animation->zOrderTimeline = _parseTimeline(
rawData[Z_ORDER], FRAME, TimelineType::ZOrder,
false, false, 0,
std::bind(&JSONDataParser::_parseZOrderFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
}
if (rawData.HasMember(BONE))
{
const auto& rawTimelines = rawData[BONE];
for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i)
{
_parseBoneTimeline(rawTimelines[i]);
}
}
if (rawData.HasMember(SLOT))
{
const auto& rawTimelines = rawData[SLOT];
for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i)
{
_parseSlotTimeline(rawTimelines[i]);
}
}
if (rawData.HasMember(FFD))
{
const auto& rawTimelines = rawData[FFD];
for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i)
{
const auto& rawTimeline = rawTimelines[i];
auto skinName = _getString(rawTimeline, SKIN, DEFAULT_NAME);
const auto& slotName = _getString(rawTimeline, SLOT, "");
const auto& displayName = _getString(rawTimeline, NAME, "");
if (skinName.empty()) //
{
skinName = DEFAULT_NAME;
}
_slot = _armature->getSlot(slotName);
_mesh = _armature->getMesh(skinName, slotName, displayName);
if (_slot == nullptr || _mesh == nullptr)
{
continue;
}
const auto timeline = _parseTimeline(
rawTimeline, FRAME, TimelineType::SlotDeform,
false, true, 0,
std::bind(&JSONDataParser::_parseSlotFFDFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addSlotTimeline(_slot, timeline);
}
_slot = nullptr;
_mesh = nullptr;
}
}
if (rawData.HasMember(IK))
{
const auto& rawTimelines = rawData[IK];
for (std::size_t i = 0, l = rawTimelines.Size(); i < l; ++i)
{
const auto& rawTimeline = rawTimelines[i];
const auto& constraintName = _getString(rawTimeline, NAME, "");
const auto constraint = _armature->getConstraint(constraintName);
if (constraint == nullptr)
{
continue;
}
const auto timeline = _parseTimeline(
rawTimeline, FRAME, TimelineType::IKConstraint,
true, false, 2,
std::bind(&JSONDataParser::_parseIKConstraintFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addConstraintTimeline(constraint, timeline);
}
}
}
if (_actionFrames.size() > 0)
{
std::sort(_actionFrames.begin(), _actionFrames.end());
const auto timeline = _animation->actionTimeline = BaseObject::borrowObject<TimelineData>();
const auto keyFrameCount = _actionFrames.size();
timeline->type = TimelineType::Action;
timeline->offset = _timelineArray.size();
_timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount);
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = 100;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = 0;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = 0;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = 0;
_timeline = timeline;
if (keyFrameCount == 1)
{
timeline->frameIndicesOffset = -1;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = _parseCacheActionFrame(_actionFrames[0]) - _animation->frameOffset;
}
else {
const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation.
auto& frameIndices = _data->frameIndices;
timeline->frameIndicesOffset = frameIndices.size();
frameIndices.resize(frameIndices.size() + totalFrameCount);
for (
std::size_t i = 0, iK = 0, frameStart = 0, frameCount = 0;
i < totalFrameCount;
++i
)
{
if (frameStart + frameCount <= i && iK < keyFrameCount)
{
auto& frame = _actionFrames[iK];
frameStart = frame.frameStart;
if (iK == keyFrameCount - 1)
{
frameCount = _animation->frameCount - frameStart;
}
else {
frameCount = _actionFrames[iK + 1].frameStart - frameStart;
}
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + iK] = _parseActionFrame(frame, frameStart, frameCount) - _animation->frameOffset;
iK++;
}
frameIndices[timeline->frameIndicesOffset + i] = iK - 1;
}
}
_timeline = nullptr;
_actionFrames.clear();
}
_animation = nullptr;
return animation;
}
TimelineData* JSONDataParser::_parseTimeline(
const rapidjson::Value& rawData, const char* framesKey, TimelineType type,
bool addIntOffset, bool addFloatOffset, unsigned frameValueCount,
const std::function<unsigned(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)>& frameParser
)
{
if (!rawData.HasMember(framesKey))
{
return nullptr;
}
const auto& rawFrames = rawData[framesKey];
const auto keyFrameCount = rawFrames.Size();
if (keyFrameCount == 0)
{
return nullptr;
}
const auto timeline = BaseObject::borrowObject<TimelineData>();
timeline->type = type;
timeline->offset = _timelineArray.size();
_timelineArray.resize(_timelineArray.size() + 1 + 1 + 1 + 1 + 1 + keyFrameCount);
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineScale] = _getNumber(rawData, SCALE, 1.0f) * 100.f;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineOffset] = _getNumber(rawData, OFFSET, 0.0f) * 100.f;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineKeyFrameCount] = keyFrameCount;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameValueCount;
if (addIntOffset)
{
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = _frameIntArray.size() - _animation->frameIntOffset;
}
else if (addFloatOffset)
{
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = _frameFloatArray.size() - _animation->frameFloatOffset;
}
else
{
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueOffset] = 0;
}
_timeline = timeline;
if (keyFrameCount == 1) // Only one frame.
{
timeline->frameIndicesOffset = -1;
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + 0] = frameParser(rawFrames[0], 0, 0) - _animation->frameOffset;
}
else {
unsigned frameIndicesOffset = 0;
auto& frameIndices = _data->frameIndices;
const auto totalFrameCount = _animation->frameCount + 1; // One more frame than animation.
frameIndicesOffset = frameIndices.size();
frameIndices.resize(frameIndicesOffset + totalFrameCount);
timeline->frameIndicesOffset = frameIndicesOffset;
for (
std::size_t i = 0, iK = 0, frameStart = 0, frameCount = 0;
i < totalFrameCount;
++i
)
{
if (frameStart + frameCount <= i && iK < keyFrameCount)
{
const auto& rawFrame = rawFrames[iK];
frameStart = i;
frameCount = _getNumber(rawFrame, DURATION, (unsigned)1);
if (iK == keyFrameCount - 1)
{
frameCount = _animation->frameCount - frameStart;
}
_timelineArray[timeline->offset + (unsigned)BinaryOffset::TimelineFrameOffset + iK] = frameParser(rawFrame, frameStart, frameCount) - _animation->frameOffset;
iK++;
}
frameIndices[frameIndicesOffset + i] = iK - 1;
}
}
_timeline = nullptr;
return timeline;
}
void JSONDataParser::_parseBoneTimeline(const rapidjson::Value& rawData)
{
const auto bone = _armature->getBone(_getString(rawData, NAME, ""));
if (bone == nullptr)
{
return;
}
_bone = bone;
_slot = _armature->getSlot(_bone->name);
if (rawData.HasMember(TRANSLATE_FRAME))
{
const auto timeline = _parseTimeline(
rawData, TRANSLATE_FRAME, TimelineType::BoneTranslate,
false, true, 2,
std::bind(&JSONDataParser::_parseBoneTranslateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addBoneTimeline(bone, timeline);
}
}
if (rawData.HasMember(ROTATE_FRAME))
{
const auto timeline = _parseTimeline(
rawData, ROTATE_FRAME, TimelineType::BoneRotate,
false, true, 2,
std::bind(&JSONDataParser::_parseBoneRotateFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addBoneTimeline(bone, timeline);
}
}
if (rawData.HasMember(SCALE_FRAME))
{
const auto timeline = _parseTimeline(
rawData, SCALE_FRAME, TimelineType::BoneScale,
false, true, 2,
std::bind(&JSONDataParser::_parseBoneScaleFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addBoneTimeline(bone, timeline);
}
}
if (rawData.HasMember(FRAME))
{
const auto timeline = _parseTimeline(
rawData, FRAME, TimelineType::BoneAll,
false, true, 6,
std::bind(&JSONDataParser::_parseBoneAllFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
if (timeline != nullptr)
{
_animation->addBoneTimeline(bone, timeline);
}
}
_bone = nullptr;
_slot = nullptr;
}
void JSONDataParser::_parseSlotTimeline(const rapidjson::Value& rawData)
{
const auto slot = _armature->getSlot(_getString(rawData, NAME, ""));
if (slot == nullptr)
{
return;
}
TimelineData* displayTimeline = nullptr;
TimelineData* colorTimeline = nullptr;
_slot = slot;
if (rawData.HasMember(DISPLAY_FRAME))
{
displayTimeline = _parseTimeline(
rawData, DISPLAY_FRAME, TimelineType::SlotDisplay,
false, false, 0,
std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
}
else
{
displayTimeline = _parseTimeline(
rawData, FRAME, TimelineType::SlotDisplay,
false, false, 0,
std::bind(&JSONDataParser::_parseSlotDisplayFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
}
if (rawData.HasMember(COLOR_FRAME))
{
colorTimeline = _parseTimeline(
rawData, COLOR_FRAME, TimelineType::SlotColor,
true, false, 1,
std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
}
else
{
colorTimeline = _parseTimeline(
rawData, FRAME, TimelineType::SlotColor,
true, false, 1,
std::bind(&JSONDataParser::_parseSlotColorFrame, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)
);
}
if (displayTimeline != nullptr)
{
_animation->addSlotTimeline(slot, displayTimeline);
}
if (colorTimeline != nullptr)
{
_animation->addSlotTimeline(slot, colorTimeline);
}
_slot = nullptr;
}
unsigned JSONDataParser::_parseFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _frameArray.size();
_frameArray.resize(_frameArray.size() + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart;
return frameOffset;
}
unsigned JSONDataParser::_parseTweenFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseFrame(rawData, frameStart, frameCount);
if (frameCount > 0)
{
if (rawData.HasMember(CURVE))
{
const auto sampleCount = frameCount + 1;
_helpArray.resize(sampleCount);
_samplingEasingCurve(rawData[CURVE], _helpArray);
_frameArray.resize(_frameArray.size() + 1 + 1 + _helpArray.size());
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int)TweenType::Curve;
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = sampleCount;
for (std::size_t i = 0; i < sampleCount; ++i)
{
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameCurveSamples + i] = _helpArray[i] * 10000.0f;
}
}
else
{
const auto noTween = -2.0f;
auto tweenEasing = noTween;
if (rawData.HasMember(TWEEN_EASING))
{
tweenEasing = _getNumber(rawData, TWEEN_EASING, noTween);
}
if (tweenEasing == noTween)
{
_frameArray.resize(_frameArray.size() + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::None;
}
else if (tweenEasing == 0.0f)
{
_frameArray.resize(_frameArray.size() + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::Line;
}
else if (tweenEasing < 0.0f)
{
_frameArray.resize(_frameArray.size() + 1 + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadIn;
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = -tweenEasing * 100.0f;
}
else if (tweenEasing <= 1.0f)
{
_frameArray.resize(_frameArray.size() + 1 + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadOut;
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f;
}
else
{
_frameArray.resize(_frameArray.size() + 1 + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::QuadInOut;
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenEasingOrCurveSampleCount] = tweenEasing * 100.0f - 100.0f;
}
}
}
else
{
_frameArray.resize(_frameArray.size() + 1);
_frameArray[frameOffset + (unsigned)BinaryOffset::FrameTweenType] = (int16_t)TweenType::None;
}
return frameOffset;
}
unsigned JSONDataParser::_parseActionFrame(const ActionFrame& frame, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _frameArray.size();
const auto actionCount = frame.actions.size();
_frameArray.resize(_frameArray.size() + 1 + 1 + actionCount);
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition] = frameStart;
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 1] = actionCount; // Action count.
for (std::size_t i = 0; i < actionCount; ++i) // Action offsets.
{
_frameArray[frameOffset + (unsigned)BinaryOffset::FramePosition + 2 + i] = frame.actions[i];
}
return frameOffset;
}
unsigned JSONDataParser::_parseZOrderFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseFrame(rawData, frameStart, frameCount);
if (rawData.HasMember(Z_ORDER))
{
const auto& rawZOrder = rawData[Z_ORDER];
if (!rawZOrder.Empty())
{
const auto slotCount = _armature->sortedSlots.size();
std::vector<int> unchanged;
std::vector<int> zOrders;
unchanged.resize(slotCount - rawZOrder.Size() / 2);
zOrders.resize(slotCount);
for (std::size_t i = 0; i < unchanged.size(); ++i)
{
unchanged[i] = 0;
}
for (std::size_t i = 0; i < slotCount; ++i)
{
zOrders[i] = -1;
}
unsigned originalIndex = 0;
unsigned unchangedIndex = 0;
for (std::size_t i = 0, l = rawZOrder.Size(); i < l; i += 2)
{
const auto slotIndex = rawZOrder[i].GetInt();
const auto zOrderOffset = rawZOrder[i + 1].GetInt();
while (originalIndex != (unsigned)slotIndex)
{
unchanged[unchangedIndex++] = originalIndex++;
}
unsigned index = originalIndex + zOrderOffset;
zOrders[index] = originalIndex++;
}
while (originalIndex < slotCount)
{
unchanged[unchangedIndex++] = originalIndex++;
}
_frameArray.resize(_frameArray.size() + 1 + slotCount);
_frameArray[frameOffset + 1] = slotCount;
int i = slotCount;
while (i--)
{
if (zOrders[i] == -1)
{
_frameArray[frameOffset + 2 + i] = unchanged[--unchangedIndex];
}
else {
_frameArray[frameOffset + 2 + i] = zOrders[i];
}
}
return frameOffset;
}
}
_frameArray.resize(_frameArray.size() + 1);
_frameArray[frameOffset + 1] = 0;
return frameOffset;
}
unsigned JSONDataParser::_parseBoneAllFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
_helpTransform.identity();
if (rawData.HasMember(TRANSFORM))
{
_parseTransform(rawData[TRANSFORM], _helpTransform, 1.0f);
}
// Modify rotation.
auto rotation = _helpTransform.rotation;
if (frameStart != 0)
{
if (_prevClockwise == 0)
{
rotation = _prevRotation + Transform::normalizeRadian(rotation - _prevRotation);
}
else
{
if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation)
{
_prevClockwise = _prevClockwise > 0 ? _prevClockwise - 1 : _prevClockwise + 1;
}
rotation = _prevRotation + rotation - _prevRotation + Transform::PI_D * _prevClockwise;
}
}
_prevClockwise = _getNumber(rawData, TWEEN_ROTATE, 0.0f);
_prevRotation = rotation;
//
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto frameFloatOffset = _frameFloatArray.size();
_frameFloatArray.resize(_frameFloatArray.size() + 6);
_frameFloatArray[frameFloatOffset++] = _helpTransform.x;
_frameFloatArray[frameFloatOffset++] = _helpTransform.y;
_frameFloatArray[frameFloatOffset++] = rotation;
_frameFloatArray[frameFloatOffset++] = _helpTransform.skew;
_frameFloatArray[frameFloatOffset++] = _helpTransform.scaleX;
_frameFloatArray[frameFloatOffset++] = _helpTransform.scaleY;
_parseActionDataInFrame(rawData, frameStart, _bone, _slot);
return frameOffset;
}
unsigned JSONDataParser::_parseBoneTranslateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto frameFloatOffset = _frameFloatArray.size();
_frameFloatArray.resize(_frameFloatArray.size() + 2);
_frameFloatArray[frameFloatOffset++] = _getNumber(rawData, X, 0.0f);
_frameFloatArray[frameFloatOffset++] = _getNumber(rawData, Y, 0.0f);
return frameOffset;
}
unsigned JSONDataParser::_parseBoneRotateFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
// Modify rotation.
auto rotation = _getNumber(rawData, ROTATE, 0.0f) * Transform::DEG_RAD;
if (frameStart != 0)
{
if (_prevClockwise == 0)
{
rotation = _prevRotation + Transform::normalizeRadian(rotation - _prevRotation);
}
else
{
if (_prevClockwise > 0 ? rotation >= _prevRotation : rotation <= _prevRotation)
{
_prevClockwise = _prevClockwise > 0 ? _prevClockwise - 1 : _prevClockwise + 1;
}
rotation = _prevRotation + rotation - _prevRotation + Transform::PI_D * _prevClockwise;
}
}
_prevClockwise = _getNumber(rawData, CLOCK_WISE, 0.0f);
_prevRotation = rotation;
//
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto frameFloatOffset = _frameFloatArray.size();
_frameFloatArray.resize(_frameFloatArray.size() + 2);
_frameFloatArray[frameFloatOffset++] = rotation;
_frameFloatArray[frameFloatOffset++] = _getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD;
return frameOffset;
}
unsigned JSONDataParser::_parseBoneScaleFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto frameFloatOffset = _frameFloatArray.size();
_frameFloatArray.resize(_frameFloatArray.size() + 2);
_frameFloatArray[frameFloatOffset++] = _getNumber(rawData, X, 1.0f);
_frameFloatArray[frameFloatOffset++] = _getNumber(rawData, Y, 1.0f);
return frameOffset;
}
unsigned JSONDataParser::_parseSlotDisplayFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseFrame(rawData, frameStart, frameCount);
_frameArray.resize(_frameArray.size() + 1);
if (rawData.HasMember(VALUE))
{
_frameArray[frameOffset + 1] = _getNumber(rawData, VALUE, 0);
}
else
{
_frameArray[frameOffset + 1] = _getNumber(rawData, DISPLAY_INDEX, 0);
}
_parseActionDataInFrame(rawData, frameStart, _slot->parent, _slot);
return frameOffset;
}
unsigned JSONDataParser::_parseSlotColorFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto colorOffset = -1;
if (rawData.HasMember(VALUE) || rawData.HasMember(COLOR))
{
const auto& rawColor = rawData.HasMember(VALUE) ? rawData[VALUE] : rawData[COLOR];
if (
rawColor.HasMember(ALPHA_MULTIPLIER) ||
rawColor.HasMember(RED_MULTIPLIER) ||
rawColor.HasMember(GREEN_MULTIPLIER) ||
rawColor.HasMember(BLUE_MULTIPLIER) ||
rawColor.HasMember(ALPHA_OFFSET) ||
rawColor.HasMember(RED_OFFSET) ||
rawColor.HasMember(GREEN_OFFSET) ||
rawColor.HasMember(BLUE_OFFSET)
)
{
_parseColorTransform(rawColor, _helpColorTransform);
colorOffset = _intArray.size();
_intArray.resize(_intArray.size() + 8);
_intArray[colorOffset++] = _helpColorTransform.alphaMultiplier * 100;
_intArray[colorOffset++] = _helpColorTransform.redMultiplier * 100;
_intArray[colorOffset++] = _helpColorTransform.greenMultiplier * 100;
_intArray[colorOffset++] = _helpColorTransform.blueMultiplier * 100;
_intArray[colorOffset++] = _helpColorTransform.alphaOffset;
_intArray[colorOffset++] = _helpColorTransform.redOffset;
_intArray[colorOffset++] = _helpColorTransform.greenOffset;
_intArray[colorOffset++] = _helpColorTransform.blueOffset;
colorOffset -= 8;
}
}
if (colorOffset < 0)
{
if (_defaultColorOffset < 0)
{
_defaultColorOffset = colorOffset = _intArray.size();
_intArray.resize(_intArray.size() + 8);
_intArray[colorOffset++] = 100;
_intArray[colorOffset++] = 100;
_intArray[colorOffset++] = 100;
_intArray[colorOffset++] = 100;
_intArray[colorOffset++] = 0;
_intArray[colorOffset++] = 0;
_intArray[colorOffset++] = 0;
_intArray[colorOffset++] = 0;
}
colorOffset = _defaultColorOffset;
}
const auto frameIntOffset = _frameIntArray.size();
_frameIntArray.resize(_frameIntArray.size() + 1);
_frameIntArray[frameIntOffset] = colorOffset;
return frameOffset;
}
unsigned JSONDataParser::_parseSlotFFDFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameFloatOffset = _frameFloatArray.size();
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
const auto offset = _getNumber(rawData, OFFSET, (unsigned)0);
const auto vertexCount = (unsigned)_intArray[_mesh->vertices.offset + (unsigned)BinaryOffset::MeshVertexCount];
const auto meshName = _mesh->parent->name + "_" + _slot->name + "_" + _mesh->name;
const auto weight = _mesh->vertices.weight;
auto x = 0.0f;
auto y = 0.0f;
unsigned iB = 0;
unsigned iV = 0;
if (weight != nullptr)
{
const auto& rawSlotPose = *(_weightSlotPose[meshName]);
_helpMatrixA.a = rawSlotPose[0].GetDouble();
_helpMatrixA.b = rawSlotPose[1].GetDouble();
_helpMatrixA.c = rawSlotPose[2].GetDouble();
_helpMatrixA.d = rawSlotPose[3].GetDouble();
_helpMatrixA.tx = rawSlotPose[4].GetDouble();
_helpMatrixA.ty = rawSlotPose[5].GetDouble();
_frameFloatArray.resize(_frameFloatArray.size() + weight->count * 2);
iB = weight->offset + (unsigned)BinaryOffset::WeigthBoneIndices + weight->bones.size();
}
else
{
_frameFloatArray.resize(_frameFloatArray.size() + vertexCount * 2);
}
for (
std::size_t i = 0;
i < vertexCount * 2;
i += 2
)
{
if (!rawData.HasMember(VERTICES)) // Fill 0.
{
x = 0.0f;
y = 0.0f;
}
else
{
if (i < offset || i - offset >= rawData[VERTICES].Size()) {
x = 0.0f;
}
else
{
x = rawData[VERTICES][i - offset].GetDouble();
}
if (i + 1 < offset || i + 1 - offset >= rawData[VERTICES].Size()) {
y = 0.0f;
}
else
{
y = rawData[VERTICES][i + 1 - offset].GetDouble();
}
}
if (weight != nullptr) // If mesh is skinned, transform point by bone bind pose.
{
const auto& rawBonePoses = *(_weightBonePoses[meshName]);
const unsigned vertexBoneCount = _intArray[iB++];
_helpMatrixA.transformPoint(x, y, _helpPoint, true);
x = _helpPoint.x;
y = _helpPoint.y;
for (std::size_t j = 0; j < vertexBoneCount; ++j)
{
const auto boneIndex = _intArray[iB++];
const auto matrixOffset = boneIndex * 7 + 1;
_helpMatrixB.a = rawBonePoses[matrixOffset + 0].GetDouble();
_helpMatrixB.b = rawBonePoses[matrixOffset + 1].GetDouble();
_helpMatrixB.c = rawBonePoses[matrixOffset + 2].GetDouble();
_helpMatrixB.d = rawBonePoses[matrixOffset + 3].GetDouble();
_helpMatrixB.tx = rawBonePoses[matrixOffset + 4].GetDouble();
_helpMatrixB.ty = rawBonePoses[matrixOffset + 5].GetDouble();
_helpMatrixB.invert();
_helpMatrixB.transformPoint(x, y, _helpPoint, true);
_frameFloatArray[frameFloatOffset + iV++] = _helpPoint.x;
_frameFloatArray[frameFloatOffset + iV++] = _helpPoint.y;
}
}
else
{
_frameFloatArray[frameFloatOffset + i] = x;
_frameFloatArray[frameFloatOffset + i + 1] = y;
}
}
if (frameStart == 0)
{
const auto frameIntOffset = _frameIntArray.size();
_frameIntArray.resize(_frameIntArray.size() + 1 + 1 + 1 + 1 + 1);
_frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformVertexOffset] = _mesh->vertices.offset;
_frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformCount] = _frameFloatArray.size() - frameFloatOffset;
_frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueCount] = _frameFloatArray.size() - frameFloatOffset;
_frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformValueOffset] = 0;
_frameIntArray[frameIntOffset + (unsigned)BinaryOffset::DeformFloatOffset] = frameFloatOffset;
_timelineArray[_timeline->offset + (unsigned)BinaryOffset::TimelineFrameValueCount] = frameIntOffset - _animation->frameIntOffset;
}
return frameOffset;
}
unsigned JSONDataParser::_parseIKConstraintFrame(const rapidjson::Value& rawData, unsigned frameStart, unsigned frameCount)
{
const auto frameOffset = _parseTweenFrame(rawData, frameStart, frameCount);
auto frameIntOffset = _frameIntArray.size();
_frameIntArray.resize(_frameIntArray.size() + 2);
_frameIntArray[frameIntOffset++] = _getBoolean(rawData, BEND_POSITIVE, true) ? 1 : 0;
_frameIntArray[frameIntOffset++] = round(_getNumber(rawData, WEIGHT, 1.0f) * 100.0f);
return frameOffset;
}
const std::vector<ActionData*>& JSONDataParser::_parseActionData(const rapidjson::Value& rawData, ActionType type, BoneData* bone, SlotData* slot)
{
static std::vector<ActionData*> actions;
actions.clear();
if (rawData.IsString())
{
const auto action = BaseObject::borrowObject<ActionData>();
action->type = type;
action->name = rawData.GetString();
action->bone = bone;
action->slot = slot;
actions.push_back(action);
}
else if (rawData.IsArray())
{
for (std::size_t iA = 0, lA = rawData.Size(); iA < lA; ++iA)
{
const auto& rawAction = rawData[iA];
const auto action = BaseObject::borrowObject<ActionData>();
if (rawAction.HasMember(GOTO_AND_PLAY))
{
action->type = ActionType::Play;
action->name = _getString(rawAction, GOTO_AND_PLAY, "");
}
else
{
if (rawAction.HasMember(TYPE) && rawAction[TYPE].IsString())
{
action->type = _getActionType(rawAction[TYPE].GetString());
}
else
{
action->type = (ActionType)_getNumber(rawAction, TYPE, (int)type);
}
action->name = _getString(rawAction, NAME, "");
}
if (rawAction.HasMember(BONE))
{
const auto& boneName = _getString(rawAction, BONE, "");
action->bone = _armature->getBone(boneName);
}
else {
action->bone = bone;
}
if (rawAction.HasMember(SLOT))
{
const auto& slotName = _getString(rawAction, SLOT, "");
action->slot = _armature->getSlot(slotName);
}
else
{
action->slot = slot;
}
if (rawAction.HasMember(INTS))
{
if (action->data == nullptr)
{
action->data = BaseObject::borrowObject<UserData>();
}
const auto& rawInts = rawAction[INTS];
for (std::size_t i = 0, l = rawInts.Size(); i < l; ++i)
{
action->data->addInt(rawInts[i].GetInt());
}
}
if (rawAction.HasMember(FLOATS))
{
if (action->data == nullptr)
{
action->data = BaseObject::borrowObject<UserData>();
}
const auto& rawFloats = rawAction[FLOATS];
for (std::size_t i = 0, l = rawFloats.Size(); i < l; ++i)
{
action->data->addFloat(rawFloats[i].GetDouble());
}
}
if (rawAction.HasMember(STRINGS))
{
if (action->data == nullptr)
{
action->data = BaseObject::borrowObject<UserData>();
}
const auto& rawStrings = rawAction[STRINGS];
for (std::size_t i = 0, l = rawStrings.Size(); i < l; ++i)
{
action->data->addString(rawStrings[i].GetString());
}
}
actions.push_back(action);
}
}
return actions;
}
void JSONDataParser::_parseTransform(const rapidjson::Value& rawData, Transform& transform, float scale)
{
transform.x = _getNumber(rawData, X, 0.0f) * scale;
transform.y = _getNumber(rawData, Y, 0.0f) * scale;
if (rawData.HasMember(ROTATE) || rawData.HasMember(SKEW))
{
transform.rotation = Transform::normalizeRadian(_getNumber(rawData, ROTATE, 0.0f) * Transform::DEG_RAD);
transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW, 0.0f) * Transform::DEG_RAD);
}
else if (rawData.HasMember(SKEW_X) || rawData.HasMember(SKEW_Y))
{
transform.rotation = Transform::normalizeRadian(_getNumber(rawData, SKEW_Y, 0.0f) * Transform::DEG_RAD);
transform.skew = Transform::normalizeRadian(_getNumber(rawData, SKEW_X, 0.0f) * Transform::DEG_RAD) - transform.rotation;
}
transform.scaleX = _getNumber(rawData, SCALE_X, 1.0f);
transform.scaleY = _getNumber(rawData, SCALE_Y, 1.0f);
}
void JSONDataParser::_parseColorTransform(const rapidjson::Value& rawData, ColorTransform& color)
{
color.alphaMultiplier = _getNumber(rawData, ALPHA_MULTIPLIER, (int)100) * 0.01f;
color.redMultiplier = _getNumber(rawData, RED_MULTIPLIER, (int)100) * 0.01f;
color.greenMultiplier = _getNumber(rawData, GREEN_MULTIPLIER, (int)100) * 0.01f;
color.blueMultiplier = _getNumber(rawData, BLUE_MULTIPLIER, (int)100) * 0.01f;
color.alphaOffset = _getNumber(rawData, ALPHA_OFFSET, (int)0);
color.redOffset = _getNumber(rawData, RED_OFFSET, (int)0);
color.greenOffset = _getNumber(rawData, GREEN_OFFSET, (int)0);
color.blueOffset = _getNumber(rawData, BLUE_OFFSET, (int)0);
}
void JSONDataParser::_parseArray(const rapidjson::Value& rawData)
{
_intArray.clear();
_floatArray.clear();
_frameIntArray.clear();
_frameFloatArray.clear();
_frameArray.clear();
_timelineArray.clear();
}
DragonBonesData* JSONDataParser::_parseDragonBonesData(const rapidjson::Value& rawData, float scale)
{
const auto& version = _getString(rawData, VERSION, "");
const auto& compatibleVersion = _getString(rawData, COMPATIBLE_VERSION, "");
if (
indexOf(DATA_VERSIONS, version) >= 0 ||
indexOf(DATA_VERSIONS, compatibleVersion) >= 0
)
{
const auto data = BaseObject::borrowObject<DragonBonesData>();
data->version = version;
data->name = _getString(rawData, NAME, "");
data->frameRate = _getNumber(rawData, FRAME_RATE, 24);
if (data->frameRate == 0) // Data error.
{
data->frameRate = 24;
}
if (rawData.HasMember(ARMATURE))
{
_data = data;
_parseArray(rawData);
const auto& rawArmatures = rawData[ARMATURE];
for (std::size_t i = 0, l = rawArmatures.Size(); i < l; ++i)
{
data->addArmature(_parseArmature(rawArmatures[i], scale));
}
if (data->binary == nullptr)
{
// Align.
if (fmod(_intArray.size(), 2) != 0)
{
_intArray.push_back(0);
}
if (fmod(_frameIntArray.size(), 2) != 0)
{
_frameIntArray.push_back(0);
}
if (fmod(_frameArray.size(), 2) != 0)
{
_frameArray.push_back(0);
}
if (fmod(_timelineArray.size(), 2) != 0)
{
_timelineArray.push_back(0);
}
const auto l1 = _intArray.size() * 2;
const auto l2 = _floatArray.size() * 4;
const auto l3 = _frameIntArray.size() * 2;
const auto l4 = _frameFloatArray.size() * 4;
const auto l5 = _frameArray.size() * 2;
const auto l6 = _timelineArray.size() * 2;
auto binary = new char[l1 + l2 + l3 + l4 + l5 + l6];
auto intArray = (int16_t*)binary;
auto floatArray = (float*)(binary + l1);
auto frameIntArray = (int16_t*)(binary + l1 + l2);
auto frameFloatArray = (float*)(binary + l1 + l2 + l3);
auto frameArray = (int16_t*)(binary + l1 + l2 + l3 + l4);
auto timelineArray = (uint16_t*)(binary + l1 + l2 + l3 + l4 + l5);
for (std::size_t i = 0, l = _intArray.size(); i < l; ++i)
{
intArray[i] = _intArray[i];
}
for (std::size_t i = 0, l = _floatArray.size(); i < l; ++i)
{
floatArray[i] = _floatArray[i];
}
for (std::size_t i = 0, l = _frameIntArray.size(); i < l; ++i)
{
frameIntArray[i] = _frameIntArray[i];
}
for (std::size_t i = 0, l = _frameFloatArray.size(); i < l; ++i)
{
frameFloatArray[i] = _frameFloatArray[i];
}
for (std::size_t i = 0, l = _frameArray.size(); i < l; ++i)
{
frameArray[i] = _frameArray[i];
}
for (std::size_t i = 0, l = _timelineArray.size(); i < l; ++i)
{
timelineArray[i] = _timelineArray[i];
}
data->binary = binary;
data->intArray = intArray;
data->floatArray = floatArray;
data->frameIntArray = frameIntArray;
data->frameFloatArray = frameFloatArray;
data->frameArray = frameArray;
data->timelineArray = timelineArray;
}
_defaultColorOffset = -1;
_data = nullptr;
}
if (rawData.HasMember(TEXTURE_ATLAS))
{
_rawTextureAtlases = (rapidjson::Value*)&(rawData[TEXTURE_ATLAS]);
}
return data;
}
else
{
DRAGONBONES_ASSERT(
false,
"Nonsupport data version: " + version + "\n" +
"Please convert DragonBones data to support version.\n" +
"Read more: https://github.com/DragonBones/Tools/"
);
}
return nullptr;
}
void JSONDataParser::_parseTextureAtlasData(const rapidjson::Value& rawData, TextureAtlasData& textureAtlasData, float scale)
{
textureAtlasData.format = _getTextureFormat(_getString(rawData, FORMAT, ""));
textureAtlasData.width = _getNumber(rawData, WIDTH, (unsigned)0);
textureAtlasData.height = _getNumber(rawData, HEIGHT, (unsigned)0);
textureAtlasData.scale = scale == 1.0f ? 1.0f / _getNumber(rawData, SCALE, 1.0f) : scale;
textureAtlasData.name = _getString(rawData, NAME, "");
textureAtlasData.imagePath = _getString(rawData, IMAGE_PATH, "");
if (rawData.HasMember(SUB_TEXTURE))
{
const auto& rawTextures = rawData[SUB_TEXTURE];
for (std::size_t i = 0, l = rawTextures.Size(); i < l; ++i)
{
const auto& rawTexture = rawTextures[i];
const auto textureData = textureAtlasData.createTexture();
textureData->rotated = _getBoolean(rawTexture, ROTATED, false);
textureData->name = _getString(rawTexture, NAME, "");
textureData->region.x = _getNumber(rawTexture, X, 0.0f);
textureData->region.y = _getNumber(rawTexture, Y, 0.0f);
textureData->region.width = _getNumber(rawTexture, WIDTH, 0.0f);
textureData->region.height = _getNumber(rawTexture, HEIGHT, 0.0f);
const auto frameWidth = _getNumber(rawTexture, FRAME_WIDTH, -1.0f);
const auto frameHeight = _getNumber(rawTexture, FRAME_HEIGHT, -1.0f);
if (frameWidth > 0.0f && frameHeight > 0.0f)
{
textureData->frame = TextureData::createRectangle();
textureData->frame->x = _getNumber(rawTexture, FRAME_X, 0.0f);
textureData->frame->y = _getNumber(rawTexture, FRAME_Y, 0.0f);
textureData->frame->width = frameWidth;
textureData->frame->height = frameHeight;
}
textureAtlasData.addTexture(textureData);
}
}
}
DragonBonesData* JSONDataParser::parseDragonBonesData(const char* rawData, float scale)
{
DRAGONBONES_ASSERT(rawData != nullptr, "");
rapidjson::Document document;
document.Parse(rawData);
return _parseDragonBonesData(document, scale);
}
bool JSONDataParser::parseTextureAtlasData(const char* rawData, TextureAtlasData& textureAtlasData, float scale)
{
if (rawData == nullptr)
{
if (_rawTextureAtlases == nullptr || _rawTextureAtlases->Empty())
{
return false;
}
const auto& rawTextureAtlas = (*_rawTextureAtlases)[_rawTextureAtlasIndex++];
_parseTextureAtlasData(rawTextureAtlas, textureAtlasData, scale);
if (_rawTextureAtlasIndex >= _rawTextureAtlases->Size())
{
_rawTextureAtlasIndex = 0;
_rawTextureAtlases = nullptr;
}
return true;
}
rapidjson::Document document;
document.Parse(rawData);
_parseTextureAtlasData(document, textureAtlasData, scale);
return true;
}
DRAGONBONES_NAMESPACE_END
|
{
"pile_set_name": "Github"
}
|
**build and run**
gradle installDebug runTwitter
|
{
"pile_set_name": "Github"
}
|
/** internal
* class ArgumentGroup
*
* Group arguments.
* By default, ArgumentParser groups command-line arguments
* into “positional arguments” and “optional arguments”
* when displaying help messages. When there is a better
* conceptual grouping of arguments than this default one,
* appropriate groups can be created using the addArgumentGroup() method
*
* This class inherited from [[ArgumentContainer]]
**/
'use strict';
var util = require('util');
var ActionContainer = require('../action_container');
/**
* new ArgumentGroup(container, options)
* - container (object): main container
* - options (object): hash of group options
*
* #### options
* - **prefixChars** group name prefix
* - **argumentDefault** default argument value
* - **title** group title
* - **description** group description
*
**/
var ArgumentGroup = module.exports = function ArgumentGroup(container, options) {
options = options || {};
// add any missing keyword arguments by checking the container
options.conflictHandler = (options.conflictHandler || container.conflictHandler);
options.prefixChars = (options.prefixChars || container.prefixChars);
options.argumentDefault = (options.argumentDefault || container.argumentDefault);
ActionContainer.call(this, options);
// group attributes
this.title = options.title;
this._groupActions = [];
// share most attributes with the container
this._container = container;
this._registries = container._registries;
this._actions = container._actions;
this._optionStringActions = container._optionStringActions;
this._defaults = container._defaults;
this._hasNegativeNumberOptionals = container._hasNegativeNumberOptionals;
this._mutuallyExclusiveGroups = container._mutuallyExclusiveGroups;
};
util.inherits(ArgumentGroup, ActionContainer);
ArgumentGroup.prototype._addAction = function (action) {
// Parent add action
action = ActionContainer.prototype._addAction.call(this, action);
this._groupActions.push(action);
return action;
};
ArgumentGroup.prototype._removeAction = function (action) {
// Parent remove action
ActionContainer.prototype._removeAction.call(this, action);
var actionIndex = this._groupActions.indexOf(action);
if (actionIndex >= 0) {
this._groupActions.splice(actionIndex, 1);
}
};
|
{
"pile_set_name": "Github"
}
|
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <string.h>
#include "tensor_computing.h"
#include "ut_util.h"
int scaleTest(int argc, char** argv, DataType dt){
CHECK_REQUIREMENT(argc == 5);
U32 in = atoi(argv[1]);
U32 ic = atoi(argv[2]);
U32 ih = atoi(argv[3]);
U32 iw = atoi(argv[4]);
I32 axis = 1;
DataFormat df = DF_NCHWC8;
TensorDesc data_desc = tensor4df(dt, df, in, ic, ih, iw);
U32 len = tensorNumElements(data_desc);
U8* alpha = ut_input_v(ic, dt, UT_INIT_RANDOM);
U8* beta = ut_input_v(ic, dt, UT_INIT_RANDOM);
U8* data = ut_input_v(len, dt, UT_INIT_RANDOM);
U8* data_ref = ut_input_v(len, dt, UT_INIT_ZERO);
memcpy(data_ref, data, len*bytesOf(dt));
if (UT_CHECK) {
CHECK_STATUS(scale(data_desc, data, axis, alpha, beta, data_desc, data, UT_ARCH));
// naive implement
CHECK_STATUS(scale(data_desc, data_ref, axis, alpha, beta, data_desc, data_ref, CPU_GENERAL));
// check
ut_check_v(data, data_ref, len, dt, 1.0, __FILE__, __LINE__);
}
// benchmark
double time_start = ut_time_ms();
for (int iter = 0; iter < UT_LOOPS; iter++) {
CHECK_STATUS(scale(data_desc, data, axis, alpha, beta, data_desc, data, UT_ARCH));
}
double time_end = ut_time_ms();
double time = (time_end - time_start) / UT_LOOPS;
// log performance data
char buffer[150];
char params[120];
sprintf(params, "(%u %u %u %u)=(%u %u %u %u)",
in, ic, ih, iw,
in, ic, ih, iw);
sprintf(buffer, "%20s, %80s", "Scale", params);
double ops = 2.0 * in * ic * ih * iw;
ut_log(dt, buffer, ops, time/UT_LOOPS);
free(data);
free(data_ref);
return 0;
}
int main(int argc, char** argv) {
#ifdef _USE_FP16
scaleTest(argc, argv, DT_F16);
#endif
#ifdef _USE_FP32
scaleTest(argc, argv, DT_F32);
#endif
return 0;
}
|
{
"pile_set_name": "Github"
}
|
libperf-$(CONFIG_DWARF) += dwarf-regs.o
|
{
"pile_set_name": "Github"
}
|
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package sts
const (
// ErrCodeExpiredTokenException for service response error code
// "ExpiredTokenException".
//
// The web identity token that was passed is expired or is not valid. Get a
// new identity token from the identity provider and then retry the request.
ErrCodeExpiredTokenException = "ExpiredTokenException"
// ErrCodeIDPCommunicationErrorException for service response error code
// "IDPCommunicationError".
//
// The request could not be fulfilled because the non-AWS identity provider
// (IDP) that was asked to verify the incoming identity token could not be reached.
// This is often a transient error caused by network conditions. Retry the request
// a limited number of times so that you don't exceed the request rate. If the
// error persists, the non-AWS identity provider might be down or not responding.
ErrCodeIDPCommunicationErrorException = "IDPCommunicationError"
// ErrCodeIDPRejectedClaimException for service response error code
// "IDPRejectedClaim".
//
// The identity provider (IdP) reported that authentication failed. This might
// be because the claim is invalid.
//
// If this error is returned for the AssumeRoleWithWebIdentity operation, it
// can also mean that the claim has expired or has been explicitly revoked.
ErrCodeIDPRejectedClaimException = "IDPRejectedClaim"
// ErrCodeInvalidAuthorizationMessageException for service response error code
// "InvalidAuthorizationMessageException".
//
// The error returned if the message passed to DecodeAuthorizationMessage was
// invalid. This can happen if the token contains invalid characters, such as
// linebreaks.
ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException"
// ErrCodeInvalidIdentityTokenException for service response error code
// "InvalidIdentityToken".
//
// The web identity token that was passed could not be validated by AWS. Get
// a new identity token from the identity provider and then retry the request.
ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken"
// ErrCodeMalformedPolicyDocumentException for service response error code
// "MalformedPolicyDocument".
//
// The request was rejected because the policy document was malformed. The error
// message describes the specific error.
ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument"
// ErrCodePackedPolicyTooLargeException for service response error code
// "PackedPolicyTooLarge".
//
// The request was rejected because the policy document was too large. The error
// message describes how big the policy document is, in packed form, as a percentage
// of what the API allows.
ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge"
// ErrCodeRegionDisabledException for service response error code
// "RegionDisabledException".
//
// STS is not activated in the requested region for the account that is being
// asked to generate credentials. The account administrator must use the IAM
// console to activate STS in that region. For more information, see Activating
// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)
// in the IAM User Guide.
ErrCodeRegionDisabledException = "RegionDisabledException"
)
|
{
"pile_set_name": "Github"
}
|
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
{
"pile_set_name": "Github"
}
|
/*!
* jQuery UI Disable Selection 1.12.0
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/
// This file is deprecated
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery", "./version" ], factory );
} else {
// Browser globals
factory( jQuery );
}
} ( function( $ ) {
return $.fn.extend( {
disableSelection: ( function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.on( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
} );
};
} )(),
enableSelection: function() {
return this.off( ".ui-disableSelection" );
}
} );
} ) );
|
{
"pile_set_name": "Github"
}
|
// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/golang/mock/sample (interfaces: Index,Embed,Embedded)
// Package mock_sample is a generated GoMock package.
package mock_sample
import (
bufio "bufio"
bytes "bytes"
gomock "github.com/golang/mock/gomock"
imp1 "github.com/golang/mock/sample/imp1"
imp2 "github.com/golang/mock/sample/imp2"
imp3 "github.com/golang/mock/sample/imp3"
imp4 "github.com/golang/mock/sample/imp4"
hash "hash"
template "html/template"
io "io"
http "net/http"
reflect "reflect"
template0 "text/template"
)
// MockIndex is a mock of Index interface
type MockIndex struct {
ctrl *gomock.Controller
recorder *MockIndexMockRecorder
}
// MockIndexMockRecorder is the mock recorder for MockIndex
type MockIndexMockRecorder struct {
mock *MockIndex
}
// NewMockIndex creates a new mock instance
func NewMockIndex(ctrl *gomock.Controller) *MockIndex {
mock := &MockIndex{ctrl: ctrl}
mock.recorder = &MockIndexMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockIndex) EXPECT() *MockIndexMockRecorder {
return m.recorder
}
// Anon mocks base method
func (m *MockIndex) Anon(arg0 string) {
m.ctrl.Call(m, "Anon", arg0)
}
// Anon indicates an expected call of Anon
func (mr *MockIndexMockRecorder) Anon(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Anon", reflect.TypeOf((*MockIndex)(nil).Anon), arg0)
}
// Chan mocks base method
func (m *MockIndex) Chan(arg0 chan int, arg1 chan<- hash.Hash) {
m.ctrl.Call(m, "Chan", arg0, arg1)
}
// Chan indicates an expected call of Chan
func (mr *MockIndexMockRecorder) Chan(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Chan", reflect.TypeOf((*MockIndex)(nil).Chan), arg0, arg1)
}
// ConcreteRet mocks base method
func (m *MockIndex) ConcreteRet() chan<- bool {
ret := m.ctrl.Call(m, "ConcreteRet")
ret0, _ := ret[0].(chan<- bool)
return ret0
}
// ConcreteRet indicates an expected call of ConcreteRet
func (mr *MockIndexMockRecorder) ConcreteRet() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConcreteRet", reflect.TypeOf((*MockIndex)(nil).ConcreteRet))
}
// Ellip mocks base method
func (m *MockIndex) Ellip(arg0 string, arg1 ...interface{}) {
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "Ellip", varargs...)
}
// Ellip indicates an expected call of Ellip
func (mr *MockIndexMockRecorder) Ellip(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ellip", reflect.TypeOf((*MockIndex)(nil).Ellip), varargs...)
}
// EllipOnly mocks base method
func (m *MockIndex) EllipOnly(arg0 ...string) {
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
m.ctrl.Call(m, "EllipOnly", varargs...)
}
// EllipOnly indicates an expected call of EllipOnly
func (mr *MockIndexMockRecorder) EllipOnly(arg0 ...interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EllipOnly", reflect.TypeOf((*MockIndex)(nil).EllipOnly), arg0...)
}
// ForeignFour mocks base method
func (m *MockIndex) ForeignFour(arg0 imp4.Imp4) {
m.ctrl.Call(m, "ForeignFour", arg0)
}
// ForeignFour indicates an expected call of ForeignFour
func (mr *MockIndexMockRecorder) ForeignFour(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignFour", reflect.TypeOf((*MockIndex)(nil).ForeignFour), arg0)
}
// ForeignOne mocks base method
func (m *MockIndex) ForeignOne(arg0 imp1.Imp1) {
m.ctrl.Call(m, "ForeignOne", arg0)
}
// ForeignOne indicates an expected call of ForeignOne
func (mr *MockIndexMockRecorder) ForeignOne(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignOne", reflect.TypeOf((*MockIndex)(nil).ForeignOne), arg0)
}
// ForeignThree mocks base method
func (m *MockIndex) ForeignThree(arg0 imp3.Imp3) {
m.ctrl.Call(m, "ForeignThree", arg0)
}
// ForeignThree indicates an expected call of ForeignThree
func (mr *MockIndexMockRecorder) ForeignThree(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignThree", reflect.TypeOf((*MockIndex)(nil).ForeignThree), arg0)
}
// ForeignTwo mocks base method
func (m *MockIndex) ForeignTwo(arg0 imp2.Imp2) {
m.ctrl.Call(m, "ForeignTwo", arg0)
}
// ForeignTwo indicates an expected call of ForeignTwo
func (mr *MockIndexMockRecorder) ForeignTwo(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignTwo", reflect.TypeOf((*MockIndex)(nil).ForeignTwo), arg0)
}
// Func mocks base method
func (m *MockIndex) Func(arg0 func(http.Request) (int, bool)) {
m.ctrl.Call(m, "Func", arg0)
}
// Func indicates an expected call of Func
func (mr *MockIndexMockRecorder) Func(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Func", reflect.TypeOf((*MockIndex)(nil).Func), arg0)
}
// Get mocks base method
func (m *MockIndex) Get(arg0 string) interface{} {
ret := m.ctrl.Call(m, "Get", arg0)
ret0, _ := ret[0].(interface{})
return ret0
}
// Get indicates an expected call of Get
func (mr *MockIndexMockRecorder) Get(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockIndex)(nil).Get), arg0)
}
// GetTwo mocks base method
func (m *MockIndex) GetTwo(arg0, arg1 string) (interface{}, interface{}) {
ret := m.ctrl.Call(m, "GetTwo", arg0, arg1)
ret0, _ := ret[0].(interface{})
ret1, _ := ret[1].(interface{})
return ret0, ret1
}
// GetTwo indicates an expected call of GetTwo
func (mr *MockIndexMockRecorder) GetTwo(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTwo", reflect.TypeOf((*MockIndex)(nil).GetTwo), arg0, arg1)
}
// Map mocks base method
func (m *MockIndex) Map(arg0 map[int]hash.Hash) {
m.ctrl.Call(m, "Map", arg0)
}
// Map indicates an expected call of Map
func (mr *MockIndexMockRecorder) Map(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Map", reflect.TypeOf((*MockIndex)(nil).Map), arg0)
}
// NillableRet mocks base method
func (m *MockIndex) NillableRet() error {
ret := m.ctrl.Call(m, "NillableRet")
ret0, _ := ret[0].(error)
return ret0
}
// NillableRet indicates an expected call of NillableRet
func (mr *MockIndexMockRecorder) NillableRet() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NillableRet", reflect.TypeOf((*MockIndex)(nil).NillableRet))
}
// Other mocks base method
func (m *MockIndex) Other() hash.Hash {
ret := m.ctrl.Call(m, "Other")
ret0, _ := ret[0].(hash.Hash)
return ret0
}
// Other indicates an expected call of Other
func (mr *MockIndexMockRecorder) Other() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Other", reflect.TypeOf((*MockIndex)(nil).Other))
}
// Ptr mocks base method
func (m *MockIndex) Ptr(arg0 *int) {
m.ctrl.Call(m, "Ptr", arg0)
}
// Ptr indicates an expected call of Ptr
func (mr *MockIndexMockRecorder) Ptr(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ptr", reflect.TypeOf((*MockIndex)(nil).Ptr), arg0)
}
// Put mocks base method
func (m *MockIndex) Put(arg0 string, arg1 interface{}) {
m.ctrl.Call(m, "Put", arg0, arg1)
}
// Put indicates an expected call of Put
func (mr *MockIndexMockRecorder) Put(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockIndex)(nil).Put), arg0, arg1)
}
// Slice mocks base method
func (m *MockIndex) Slice(arg0 []int, arg1 []byte) [3]int {
ret := m.ctrl.Call(m, "Slice", arg0, arg1)
ret0, _ := ret[0].([3]int)
return ret0
}
// Slice indicates an expected call of Slice
func (mr *MockIndexMockRecorder) Slice(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Slice", reflect.TypeOf((*MockIndex)(nil).Slice), arg0, arg1)
}
// Struct mocks base method
func (m *MockIndex) Struct(arg0 struct{}) {
m.ctrl.Call(m, "Struct", arg0)
}
// Struct indicates an expected call of Struct
func (mr *MockIndexMockRecorder) Struct(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Struct", reflect.TypeOf((*MockIndex)(nil).Struct), arg0)
}
// StructChan mocks base method
func (m *MockIndex) StructChan(arg0 chan struct{}) {
m.ctrl.Call(m, "StructChan", arg0)
}
// StructChan indicates an expected call of StructChan
func (mr *MockIndexMockRecorder) StructChan(arg0 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StructChan", reflect.TypeOf((*MockIndex)(nil).StructChan), arg0)
}
// Summary mocks base method
func (m *MockIndex) Summary(arg0 *bytes.Buffer, arg1 io.Writer) {
m.ctrl.Call(m, "Summary", arg0, arg1)
}
// Summary indicates an expected call of Summary
func (mr *MockIndexMockRecorder) Summary(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Summary", reflect.TypeOf((*MockIndex)(nil).Summary), arg0, arg1)
}
// Templates mocks base method
func (m *MockIndex) Templates(arg0 template.CSS, arg1 template0.FuncMap) {
m.ctrl.Call(m, "Templates", arg0, arg1)
}
// Templates indicates an expected call of Templates
func (mr *MockIndexMockRecorder) Templates(arg0, arg1 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Templates", reflect.TypeOf((*MockIndex)(nil).Templates), arg0, arg1)
}
// MockEmbed is a mock of Embed interface
type MockEmbed struct {
ctrl *gomock.Controller
recorder *MockEmbedMockRecorder
}
// MockEmbedMockRecorder is the mock recorder for MockEmbed
type MockEmbedMockRecorder struct {
mock *MockEmbed
}
// NewMockEmbed creates a new mock instance
func NewMockEmbed(ctrl *gomock.Controller) *MockEmbed {
mock := &MockEmbed{ctrl: ctrl}
mock.recorder = &MockEmbedMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockEmbed) EXPECT() *MockEmbedMockRecorder {
return m.recorder
}
// EmbeddedMethod mocks base method
func (m *MockEmbed) EmbeddedMethod() {
m.ctrl.Call(m, "EmbeddedMethod")
}
// EmbeddedMethod indicates an expected call of EmbeddedMethod
func (mr *MockEmbedMockRecorder) EmbeddedMethod() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).EmbeddedMethod))
}
// ForeignEmbeddedMethod mocks base method
func (m *MockEmbed) ForeignEmbeddedMethod() *bufio.Reader {
ret := m.ctrl.Call(m, "ForeignEmbeddedMethod")
ret0, _ := ret[0].(*bufio.Reader)
return ret0
}
// ForeignEmbeddedMethod indicates an expected call of ForeignEmbeddedMethod
func (mr *MockEmbedMockRecorder) ForeignEmbeddedMethod() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ForeignEmbeddedMethod", reflect.TypeOf((*MockEmbed)(nil).ForeignEmbeddedMethod))
}
// ImplicitPackage mocks base method
func (m *MockEmbed) ImplicitPackage(arg0 string, arg1 imp1.ImpT, arg2 []imp1.ImpT, arg3 *imp1.ImpT, arg4 chan imp1.ImpT) {
m.ctrl.Call(m, "ImplicitPackage", arg0, arg1, arg2, arg3, arg4)
}
// ImplicitPackage indicates an expected call of ImplicitPackage
func (mr *MockEmbedMockRecorder) ImplicitPackage(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImplicitPackage", reflect.TypeOf((*MockEmbed)(nil).ImplicitPackage), arg0, arg1, arg2, arg3, arg4)
}
// RegularMethod mocks base method
func (m *MockEmbed) RegularMethod() {
m.ctrl.Call(m, "RegularMethod")
}
// RegularMethod indicates an expected call of RegularMethod
func (mr *MockEmbedMockRecorder) RegularMethod() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegularMethod", reflect.TypeOf((*MockEmbed)(nil).RegularMethod))
}
// MockEmbedded is a mock of Embedded interface
type MockEmbedded struct {
ctrl *gomock.Controller
recorder *MockEmbeddedMockRecorder
}
// MockEmbeddedMockRecorder is the mock recorder for MockEmbedded
type MockEmbeddedMockRecorder struct {
mock *MockEmbedded
}
// NewMockEmbedded creates a new mock instance
func NewMockEmbedded(ctrl *gomock.Controller) *MockEmbedded {
mock := &MockEmbedded{ctrl: ctrl}
mock.recorder = &MockEmbeddedMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockEmbedded) EXPECT() *MockEmbeddedMockRecorder {
return m.recorder
}
// EmbeddedMethod mocks base method
func (m *MockEmbedded) EmbeddedMethod() {
m.ctrl.Call(m, "EmbeddedMethod")
}
// EmbeddedMethod indicates an expected call of EmbeddedMethod
func (mr *MockEmbeddedMockRecorder) EmbeddedMethod() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EmbeddedMethod", reflect.TypeOf((*MockEmbedded)(nil).EmbeddedMethod))
}
|
{
"pile_set_name": "Github"
}
|
({
baseUrl: '.',
optimize: 'none',
paths: {
fs: 'blank',
path: 'blank'
},
skipModuleInsertion: true,
name: '../build',
out: 'optotext.js'
})
|
{
"pile_set_name": "Github"
}
|
// cgo -godefs types_aix.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build ppc,aix
package unix
const (
SizeofPtr = 0x4
SizeofShort = 0x2
SizeofInt = 0x4
SizeofLong = 0x4
SizeofLongLong = 0x8
PathMax = 0x3ff
)
type (
_C_short int16
_C_int int32
_C_long int32
_C_long_long int64
)
type off64 int64
type off int32
type Mode_t uint32
type Timespec struct {
Sec int32
Nsec int32
}
type Timeval struct {
Sec int32
Usec int32
}
type Timeval32 struct {
Sec int32
Usec int32
}
type Timex struct{}
type Time_t int32
type Tms struct{}
type Utimbuf struct {
Actime int32
Modtime int32
}
type Timezone struct {
Minuteswest int32
Dsttime int32
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int32
Ixrss int32
Idrss int32
Isrss int32
Minflt int32
Majflt int32
Nswap int32
Inblock int32
Oublock int32
Msgsnd int32
Msgrcv int32
Nsignals int32
Nvcsw int32
Nivcsw int32
}
type Rlimit struct {
Cur uint64
Max uint64
}
type Pid_t int32
type _Gid_t uint32
type dev_t uint32
type Stat_t struct {
Dev uint32
Ino uint32
Mode uint32
Nlink int16
Flag uint16
Uid uint32
Gid uint32
Rdev uint32
Size int32
Atim Timespec
Mtim Timespec
Ctim Timespec
Blksize int32
Blocks int32
Vfstype int32
Vfs uint32
Type uint32
Gen uint32
Reserved [9]uint32
}
type StatxTimestamp struct{}
type Statx_t struct{}
type Dirent struct {
Offset uint32
Ino uint32
Reclen uint16
Namlen uint16
Name [256]uint8
}
type RawSockaddrInet4 struct {
Len uint8
Family uint8
Port uint16
Addr [4]byte /* in_addr */
Zero [8]uint8
}
type RawSockaddrInet6 struct {
Len uint8
Family uint8
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Len uint8
Family uint8
Path [1023]uint8
}
type RawSockaddrDatalink struct {
Len uint8
Family uint8
Index uint16
Type uint8
Nlen uint8
Alen uint8
Slen uint8
Data [120]uint8
}
type RawSockaddr struct {
Len uint8
Family uint8
Data [14]uint8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [1012]uint8
}
type _Socklen uint32
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type ICMPv6Filter struct {
Filt [8]uint32
}
type Iovec struct {
Base *byte
Len uint32
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type Linger struct {
Onoff int32
Linger int32
}
type Msghdr struct {
Name *byte
Namelen uint32
Iov *Iovec
Iovlen int32
Control *byte
Controllen uint32
Flags int32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x404
SizeofSockaddrUnix = 0x401
SizeofSockaddrDatalink = 0x80
SizeofLinger = 0x8
SizeofIPMreq = 0x8
SizeofIPv6Mreq = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofMsghdr = 0x1c
SizeofCmsghdr = 0xc
SizeofICMPv6Filter = 0x20
)
const (
SizeofIfMsghdr = 0x10
)
type IfMsgHdr struct {
Msglen uint16
Version uint8
Type uint8
Addrs int32
Flags int32
Index uint16
Addrlen uint8
_ [1]byte
}
type FdSet struct {
Bits [2048]int32
}
type Utsname struct {
Sysname [32]byte
Nodename [32]byte
Release [32]byte
Version [32]byte
Machine [32]byte
}
type Ustat_t struct{}
type Sigset_t struct {
Losigs uint32
Hisigs uint32
}
const (
AT_FDCWD = -0x2
AT_REMOVEDIR = 0x1
AT_SYMLINK_NOFOLLOW = 0x1
)
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Cc [16]uint8
}
type Termio struct {
Iflag uint16
Oflag uint16
Cflag uint16
Lflag uint16
Line uint8
Cc [8]uint8
_ [1]byte
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type PollFd struct {
Fd int32
Events uint16
Revents uint16
}
const (
POLLERR = 0x4000
POLLHUP = 0x2000
POLLIN = 0x1
POLLNVAL = 0x8000
POLLOUT = 0x2
POLLPRI = 0x4
POLLRDBAND = 0x20
POLLRDNORM = 0x10
POLLWRBAND = 0x40
POLLWRNORM = 0x2
)
type Flock_t struct {
Type int16
Whence int16
Sysid uint32
Pid int32
Vfs int32
Start int64
Len int64
}
type Fsid_t struct {
Val [2]uint32
}
type Fsid64_t struct {
Val [2]uint64
}
type Statfs_t struct {
Version int32
Type int32
Bsize uint32
Blocks uint32
Bfree uint32
Bavail uint32
Files uint32
Ffree uint32
Fsid Fsid_t
Vfstype int32
Fsize uint32
Vfsnumber int32
Vfsoff int32
Vfslen int32
Vfsvers int32
Fname [32]uint8
Fpack [32]uint8
Name_max int32
}
const RNDGETENTCNT = 0x80045200
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Mods
{
public interface IUpdatableByPlayfield : IApplicableMod
{
void Update(Playfield playfield);
}
}
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr>
// Copyright (C) 2012 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/*
* NOTE: This file is the modified version of [s,d,c,z]panel_bmod.c file in SuperLU
* -- SuperLU routine (version 3.0) --
* Univ. of California Berkeley, Xerox Palo Alto Research Center,
* and Lawrence Berkeley National Lab.
* October 15, 2003
*
* Copyright (c) 1994 by Xerox Corporation. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
* EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program for any
* purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is
* granted, provided the above notices are retained, and a notice that
* the code was modified is included with the above copyright notice.
*/
#ifndef SPARSELU_PANEL_BMOD_H
#define SPARSELU_PANEL_BMOD_H
namespace Eigen {
namespace internal {
/**
* \brief Performs numeric block updates (sup-panel) in topological order.
*
* Before entering this routine, the original nonzeros in the panel
* were already copied i nto the spa[m,w]
*
* \param m number of rows in the matrix
* \param w Panel size
* \param jcol Starting column of the panel
* \param nseg Number of segments in the U part
* \param dense Store the full representation of the panel
* \param tempv working array
* \param segrep segment representative... first row in the segment
* \param repfnz First nonzero rows
* \param glu Global LU data.
*
*
*/
template <typename Scalar, typename Index>
void SparseLUImpl<Scalar,Index>::panel_bmod(const Index m, const Index w, const Index jcol,
const Index nseg, ScalarVector& dense, ScalarVector& tempv,
IndexVector& segrep, IndexVector& repfnz, GlobalLU_t& glu)
{
Index ksub,jj,nextl_col;
Index fsupc, nsupc, nsupr, nrow;
Index krep, kfnz;
Index lptr; // points to the row subscripts of a supernode
Index luptr; // ...
Index segsize,no_zeros ;
// For each nonz supernode segment of U[*,j] in topological order
Index k = nseg - 1;
const Index PacketSize = internal::packet_traits<Scalar>::size;
for (ksub = 0; ksub < nseg; ksub++)
{ // For each updating supernode
/* krep = representative of current k-th supernode
* fsupc = first supernodal column
* nsupc = number of columns in a supernode
* nsupr = number of rows in a supernode
*/
krep = segrep(k); k--;
fsupc = glu.xsup(glu.supno(krep));
nsupc = krep - fsupc + 1;
nsupr = glu.xlsub(fsupc+1) - glu.xlsub(fsupc);
nrow = nsupr - nsupc;
lptr = glu.xlsub(fsupc);
// loop over the panel columns to detect the actual number of columns and rows
Index u_rows = 0;
Index u_cols = 0;
for (jj = jcol; jj < jcol + w; jj++)
{
nextl_col = (jj-jcol) * m;
VectorBlock<IndexVector> repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row
kfnz = repfnz_col(krep);
if ( kfnz == emptyIdxLU )
continue; // skip any zero segment
segsize = krep - kfnz + 1;
u_cols++;
u_rows = (std::max)(segsize,u_rows);
}
if(nsupc >= 2)
{
Index ldu = internal::first_multiple<Index>(u_rows, PacketSize);
Map<Matrix<Scalar,Dynamic,Dynamic>, Aligned, OuterStride<> > U(tempv.data(), u_rows, u_cols, OuterStride<>(ldu));
// gather U
Index u_col = 0;
for (jj = jcol; jj < jcol + w; jj++)
{
nextl_col = (jj-jcol) * m;
VectorBlock<IndexVector> repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row
VectorBlock<ScalarVector> dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here
kfnz = repfnz_col(krep);
if ( kfnz == emptyIdxLU )
continue; // skip any zero segment
segsize = krep - kfnz + 1;
luptr = glu.xlusup(fsupc);
no_zeros = kfnz - fsupc;
Index isub = lptr + no_zeros;
Index off = u_rows-segsize;
for (Index i = 0; i < off; i++) U(i,u_col) = 0;
for (Index i = 0; i < segsize; i++)
{
Index irow = glu.lsub(isub);
U(i+off,u_col) = dense_col(irow);
++isub;
}
u_col++;
}
// solve U = A^-1 U
luptr = glu.xlusup(fsupc);
Index lda = glu.xlusup(fsupc+1) - glu.xlusup(fsupc);
no_zeros = (krep - u_rows + 1) - fsupc;
luptr += lda * no_zeros + no_zeros;
Map<Matrix<Scalar,Dynamic,Dynamic>, 0, OuterStride<> > A(glu.lusup.data()+luptr, u_rows, u_rows, OuterStride<>(lda) );
U = A.template triangularView<UnitLower>().solve(U);
// update
luptr += u_rows;
Map<Matrix<Scalar,Dynamic,Dynamic>, 0, OuterStride<> > B(glu.lusup.data()+luptr, nrow, u_rows, OuterStride<>(lda) );
eigen_assert(tempv.size()>w*ldu + nrow*w + 1);
Index ldl = internal::first_multiple<Index>(nrow, PacketSize);
Index offset = (PacketSize-internal::first_aligned(B.data(), PacketSize)) % PacketSize;
Map<Matrix<Scalar,Dynamic,Dynamic>, 0, OuterStride<> > L(tempv.data()+w*ldu+offset, nrow, u_cols, OuterStride<>(ldl));
L.setZero();
internal::sparselu_gemm<Scalar>(L.rows(), L.cols(), B.cols(), B.data(), B.outerStride(), U.data(), U.outerStride(), L.data(), L.outerStride());
// scatter U and L
u_col = 0;
for (jj = jcol; jj < jcol + w; jj++)
{
nextl_col = (jj-jcol) * m;
VectorBlock<IndexVector> repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row
VectorBlock<ScalarVector> dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here
kfnz = repfnz_col(krep);
if ( kfnz == emptyIdxLU )
continue; // skip any zero segment
segsize = krep - kfnz + 1;
no_zeros = kfnz - fsupc;
Index isub = lptr + no_zeros;
Index off = u_rows-segsize;
for (Index i = 0; i < segsize; i++)
{
Index irow = glu.lsub(isub++);
dense_col(irow) = U.coeff(i+off,u_col);
U.coeffRef(i+off,u_col) = 0;
}
// Scatter l into SPA dense[]
for (Index i = 0; i < nrow; i++)
{
Index irow = glu.lsub(isub++);
dense_col(irow) -= L.coeff(i,u_col);
L.coeffRef(i,u_col) = 0;
}
u_col++;
}
}
else // level 2 only
{
// Sequence through each column in the panel
for (jj = jcol; jj < jcol + w; jj++)
{
nextl_col = (jj-jcol) * m;
VectorBlock<IndexVector> repfnz_col(repfnz, nextl_col, m); // First nonzero column index for each row
VectorBlock<ScalarVector> dense_col(dense, nextl_col, m); // Scatter/gather entire matrix column from/to here
kfnz = repfnz_col(krep);
if ( kfnz == emptyIdxLU )
continue; // skip any zero segment
segsize = krep - kfnz + 1;
luptr = glu.xlusup(fsupc);
Index lda = glu.xlusup(fsupc+1)-glu.xlusup(fsupc);// nsupr
// Perform a trianglar solve and block update,
// then scatter the result of sup-col update to dense[]
no_zeros = kfnz - fsupc;
if(segsize==1) LU_kernel_bmod<1>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros);
else if(segsize==2) LU_kernel_bmod<2>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros);
else if(segsize==3) LU_kernel_bmod<3>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros);
else LU_kernel_bmod<Dynamic>::run(segsize, dense_col, tempv, glu.lusup, luptr, lda, nrow, glu.lsub, lptr, no_zeros);
} // End for each column in the panel
}
} // End for each updating supernode
} // end panel bmod
} // end namespace internal
} // end namespace Eigen
#endif // SPARSELU_PANEL_BMOD_H
|
{
"pile_set_name": "Github"
}
|
<!--
This file contains Runtime Directives used by .NET Native. The defaults here are suitable for most
developers. However, you can modify these parameters to modify the behavior of the .NET Native
optimizer.
Runtime Directives are documented at http://go.microsoft.com/fwlink/?LinkID=391919
To fully enable reflection for App1.MyClass and all of its public/private members
<Type Name="App1.MyClass" Dynamic="Required All"/>
To enable dynamic creation of the specific instantiation of AppClass<T> over System.Int32
<TypeInstantiation Name="App1.AppClass" Arguments="System.Int32" Activate="Required Public" />
Using the Namespace directive to apply reflection policy to all the types in a particular namespace
<Namespace Name="DataClasses.ViewModels" Seralize="All" />
-->
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Application>
<!--
An Assembly element with Name="*Application*" applies to all assemblies in
the application package. The asterisks are not wildcards.
-->
<Assembly Name="*Application*" Dynamic="Required All" />
<!-- Add your application specific runtime directives here. -->
</Application>
</Directives>
|
{
"pile_set_name": "Github"
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.rpc.boot.config;
import static org.junit.Assert.*;
import org.junit.Test;
import com.alipay.sofa.rpc.config.RegistryConfig;
/**
*
* @author zhuoyu.sjw
* @version $Id: MeshConfiguratorTest.java, v 0.1 2018-12-03 17:39 zhuoyu.sjw Exp $$
*/
public class MeshConfiguratorTest {
@Test
public void buildFromAddress() {
String address = "mesh://127.0.0.1:12220";
MeshConfigurator meshConfigurator = new MeshConfigurator();
RegistryConfig registryConfig = meshConfigurator.buildFromAddress(address);
assertEquals("mesh", registryConfig.getProtocol());
assertEquals("http://127.0.0.1:12220", registryConfig.getAddress());
}
}
|
{
"pile_set_name": "Github"
}
|
<html >
<head ><STYLE TYPE="text/css">@import "../stylesheet.css";</STYLE><title ></title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script language='JavaScript'>
function doClick(imageHref) {
if (parent.imageFrame != null)
parent.imageFrame.location.href = imageHref;
}
</script></head><table border='0' width='100%' cellpadding='1' cellspacing='0'>
<tr >
<td colspan='2' class='NavBarCellCommon'>
<table border='0' cellpadding='0' cellspacing='3'>
<tr align='center' valign='top'>
<td class='NavBarCellCommon'>
<a href='../overview-summary.html'>
<font size='+1' class='NavBarFont1'>
<b >Overview</b></font></a> </td><td class='NavBarCellCommon'>
<a href='package-summary.html'>
<font size='+1' class='NavBarFont1'>
<b >Namespace</b></font></a> </td><td class='NavBarCellCommonRev'>
<font size='+1' class='NavBarFont1'>
<b >Classifier</b></font> </td><td class='NavBarCellCommon'>
<font size='+1' class='NavBarFont1'>Tree</font> </td><td class='NavBarCellCommon'>
<a href='../index-all.html'>
<font size='+1' class='NavBarFont1'>
<b >Index</b></font></a> </td><td class='NavBarCellCommon'>
<a href='../help-doc.html'>
<font size='+1' class='NavBarFont1'>
<b >Help</b></font></a> </td></tr></table><td align='right' valign='top' rowspan='3'>
<em ></em></td></td></tr><tr >
<td class='NavBarCellPrevNext'>
<font size='-2'><a href="../OtlContainerObserver/TOmniContainerSubject.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">PREV </a> <a href="../OtlContainerObserver/TOmniContainerWindowsEventObserver.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">NEXT </a> </font></td><td class='NavBarCellPrevNext'>
<font size='-2'>
<a href='../index.html' target='_top'>
<b >FRAMES</b></a> <a href='../OtlContainerObserver/TOmniContainerObserver.html' target='_top'>
<b >NO FRAMES</b></a></font></td></tr><tr >
<td valign='top' class='NavBarCell3'>
<font size='-2'>SUMMARY: INNER | FIELD | <a href='#constructor_summary'>CONSTR</a> | DESTR | <a href='#method_summary'>METHOD</a></font></td><td valign='top' class='NavBarCell3'>
<font size='-2'>DETAIL: FIELD | <a href='#constructor_detail'>CONSTR</a> | DESTR | <a href='#method_detail'>METHOD</a></font></td></tr></table><hr /><h2 >
<font size='-1'>
<i >Namespace: </i>OtlContainerObserver<br /></font><br />Class TOmniContainerObserver</h2><pre >
OtlContainerObserver.TOmniContainerObserver
</pre><dl >
<dt /><b >Direct Known Subclasses: </b><dd ><a href="../OtlContainerObserver/TOmniContainerWindowsEventObserver.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">TOmniContainerWindowsEventObserver</a> , <a href="../OtlContainerObserver/TOmniContainerWindowsMessageObserver.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">TOmniContainerWindowsMessageObserver</a> , <a href="../OtlContainerObserver/TOmniContainerEventObserver.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">TOmniContainerEventObserver</a> </dd></dl><hr /><dl >
<dt />public class <b >TOmniContainerObserver</b></dl><p /><dl >
<dt /><b >Sealed</b><dd >False</dd></dl><dl >
<dt /><b >summary</b><dd >Container observer. Class based for performance.</dd></dl><dl >
<dt /><b >Abstract</b><dd >False</dd></dl><dl >
<dt /><b >Persistent</b><dd >False</dd></dl><hr /><p /><a name='constructor_summary'/><table border='1' cellpadding='3' cellspacing='0' width='100%'>
<tr class='TableHeaderStyle'>
<td colspan='2'>
<font size='+2'>
<b >Constructor Summary</b></font></td></tr><tr class='TableRow'>
<td >
<code >
<b >
<a href='../OtlContainerObserver/TOmniContainerObserver.html#Create()'>Create</a></b>()</code><br /> </td></tr></table> <p /><a name='method_summary'/><table border='1' cellpadding='3' cellspacing='0' width='100%'>
<tr class='TableHeaderStyle'>
<td colspan='2'>
<font size='+2'>
<b >Method Summary</b></font></td></tr><tr class='TableRow'>
<td align='right' valign='top' width='20%'>
<font size='-1'>
<code >
public <b >Sub </b></code></font></td><td >
<code >
<b >
<a href='../OtlContainerObserver/TOmniContainerObserver.html#Activate()'>Activate</a></b>()</code><br /> </td></tr><tr class='TableRow'>
<td align='right' valign='top' width='20%'>
<font size='-1'>
<code >
public <b >function boolean</b></code></font></td><td >
<code >
<b >
<a href='../OtlContainerObserver/TOmniContainerObserver.html#CanNotify()'>CanNotify</a></b>()</code><br /> </td></tr><tr class='TableRow'>
<td align='right' valign='top' width='20%'>
<font size='-1'>
<code >
public <b >Sub </b></code></font></td><td >
<code >
<b >
<a href='../OtlContainerObserver/TOmniContainerObserver.html#Deactivate()'>Deactivate</a></b>()</code><br /> </td></tr><tr class='TableRow'>
<td align='right' valign='top' width='20%'>
<font size='-1'>
<code >
public <b >Sub </b></code></font></td><td >
<code >
<b >
<a href='../OtlContainerObserver/TOmniContainerObserver.html#Notify()'>Notify</a></b>()</code><br /> </td></tr></table> <p /><p /><a Name='constructor_detail'/><table border='1' cellpadding='3' cellspacing='0' width='100%'>
<tr class='TableHeaderStyle'>
<td colspan='2'>
<font size='+2'>
<b >Constructor Detail</b></font></td></tr></table><br /><a name='Create()'>
<h3 >Create</h3></a><pre >public constructor Create()</pre><dl >
<dt /><b >Final</b><dd >False</dd></dl><dl >
<dt /><b >Reintroduce</b><dd >False</dd></dl><dl >
<dt /><b >Virtual</b><dd >False</dd></dl><dl >
<dt /><b >Override</b><dd >False</dd></dl><dl >
<dt /><b >Abstract</b><dd >False</dd></dl><hr /><a name='method_detail'/><table border='1' cellpadding='3' cellspacing='0' width='100%'>
<tr class='TableHeaderStyle'>
<td colspan='2'>
<font size='+2'>
<b >Method Detail</b></font></td></tr></table><br /><a name='Activate()'>
<h3 >Activate</h3></a><pre >public procedure Activate()</pre><dl >
<dt /><b >Final</b><dd >False</dd></dl><dl >
<dt /><b >Reintroduce</b><dd >False</dd></dl><dl >
<dt /><b >Abstract</b><dd >False</dd></dl><dl >
<dt /><b >Override</b><dd >False</dd></dl><dl >
<dt /><b >Virtual</b><dd >False</dd></dl><dl >
<dt /><b >Class</b><dd >False</dd></dl><hr /><a name='CanNotify()'>
<h3 >CanNotify</h3></a><pre >public function CanNotify(): boolean</pre><dl >
<dt /><b >Final</b><dd >False</dd></dl><dl >
<dt /><b >Reintroduce</b><dd >False</dd></dl><dl >
<dt /><b >Abstract</b><dd >False</dd></dl><dl >
<dt /><b >Returns</b><dd >boolean</dd></dl><dl >
<dt /><b >Override</b><dd >False</dd></dl><dl >
<dt /><b >Virtual</b><dd >False</dd></dl><dl >
<dt /><b >Class</b><dd >False</dd></dl><hr /><a name='Deactivate()'>
<h3 >Deactivate</h3></a><pre >public procedure Deactivate()</pre><dl >
<dt /><b >Final</b><dd >False</dd></dl><dl >
<dt /><b >Reintroduce</b><dd >False</dd></dl><dl >
<dt /><b >Abstract</b><dd >False</dd></dl><dl >
<dt /><b >Override</b><dd >False</dd></dl><dl >
<dt /><b >Virtual</b><dd >False</dd></dl><dl >
<dt /><b >Class</b><dd >False</dd></dl><hr /><a name='Notify()'>
<h3 >Notify</h3></a><pre >public procedure Notify()</pre><dl >
<dt /><b >Final</b><dd >False</dd></dl><dl >
<dt /><b >Reintroduce</b><dd >False</dd></dl><dl >
<dt /><b >Abstract</b><dd >True</dd></dl><dl >
<dt /><b >Override</b><dd >False</dd></dl><dl >
<dt /><b >Virtual</b><dd >True</dd></dl><dl >
<dt /><b >Class</b><dd >False</dd></dl><hr /><p /><table border='0' cellpadding='0' cellspacing='0'>
<tr class='TableHeaderStyle'>
<td >
<font size='+0'>
<b >Association Link</b></font></td></tr></table><br />to Struct <a href="../OtlCommon/TOmniAlignedInt32.html" target="classFrame" onclick="doClick('../OtlCommon/doc-files/default.txvpck.html')">TOmniAlignedInt32</a> <p /><dl >
<dt /><b >Supplier</b><dd >TOmniAlignedInt32</dd></dl><dl >
<dt /><b >Directed</b><dd >False</dd></dl><dl >
<dt /><b >Client</b><dd >coIsActivated</dd></dl><dl >
<dt /><b >Type</b><dd >association</dd></dl><br /><hr /><table border='0' width='100%' cellpadding='1' cellspacing='0'>
<tr >
<td colspan='2' class='NavBarCellCommon'>
<table border='0' cellpadding='0' cellspacing='3'>
<tr align='center' valign='top'>
<td class='NavBarCellCommon'>
<a href='../overview-summary.html'>
<font size='+1' class='NavBarFont1'>
<b >Overview</b></font></a> </td><td class='NavBarCellCommon'>
<a href='package-summary.html'>
<font size='+1' class='NavBarFont1'>
<b >Namespace</b></font></a> </td><td class='NavBarCellCommonRev'>
<font size='+1' class='NavBarFont1'>
<b >Classifier</b></font> </td><td class='NavBarCellCommon'>
<font size='+1' class='NavBarFont1'>Tree</font> </td><td class='NavBarCellCommon'>
<a href='../index-all.html'>
<font size='+1' class='NavBarFont1'>
<b >Index</b></font></a> </td><td class='NavBarCellCommon'>
<a href='../help-doc.html'>
<font size='+1' class='NavBarFont1'>
<b >Help</b></font></a> </td></tr></table><td align='right' valign='top' rowspan='3'>
<em ></em></td></td></tr><tr >
<td class='NavBarCellPrevNext'>
<font size='-2'><a href="../OtlContainerObserver/TOmniContainerSubject.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">PREV </a> <a href="../OtlContainerObserver/TOmniContainerWindowsEventObserver.html" target="classFrame" onclick="doClick('../OtlContainerObserver/doc-files/default.txvpck.html')">NEXT </a> </font></td><td class='NavBarCellPrevNext'>
<font size='-2'>
<a href='../index.html' target='_top'>
<b >FRAMES</b></a> <a href='../OtlContainerObserver/TOmniContainerObserver.html' target='_top'>
<b >NO FRAMES</b></a></font></td></tr><tr >
<td valign='top' class='NavBarCell3'>
<font size='-2'>SUMMARY: INNER | FIELD | <a href='#constructor_summary'>CONSTR</a> | DESTR | <a href='#method_summary'>METHOD</a></font></td><td valign='top' class='NavBarCell3'>
<font size='-2'>DETAIL: FIELD | <a href='#constructor_detail'>CONSTR</a> | DESTR | <a href='#method_detail'>METHOD</a></font></td></tr></table><br /><p /></html>
|
{
"pile_set_name": "Github"
}
|
fa9a195dca8cc8cbcddbfa13b1bea8f4df5f27d6
|
{
"pile_set_name": "Github"
}
|
/*
* This file is part of WebLookAndFeel library.
*
* WebLookAndFeel library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WebLookAndFeel library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WebLookAndFeel library. If not, see <http://www.gnu.org/licenses/>.
*/
package com.alee.laf.rootpane;
import com.alee.api.annotations.NotNull;
import com.alee.api.annotations.Nullable;
import com.alee.extended.behavior.VisibilityBehavior;
import com.alee.managers.settings.Configuration;
import com.alee.managers.settings.SettingsProcessor;
import com.alee.utils.CoreSwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* {@link SettingsProcessor} implementation that handles {@link JRootPane}'s ancestor {@link Window} position and state.
* {@link JRootPane} is used instead of {@link Window} since it is a {@link JComponent} and {@link Window} is not.
*
* @author bspkrs
* @author Mikle Garin
* @see <a href="https://github.com/mgarin/weblaf/wiki/How-to-use-SettingsManager">How to use SettingsManager</a>
* @see WindowState
* @see com.alee.managers.settings.UISettingsManager
* @see com.alee.managers.settings.SettingsManager
* @see SettingsProcessor
*/
public class RootPaneSettingsProcessor extends SettingsProcessor<JRootPane, WindowState, Configuration<WindowState>>
{
/**
* {@link ComponentListener} for tracking {@link Window} movement.
*/
protected transient ComponentListener componentListener;
/**
* {@link WindowStateListener} for tracking {@link Window} state.
*/
protected transient WindowStateListener windowStateListener;
/**
* {@link VisibilityBehavior } for updating {@link JRootPane}'s {@link Window} listeners appropriately.
*/
protected transient VisibilityBehavior<Window> windowVisibilityBehavior;
/**
* Constructs new {@link RootPaneSettingsProcessor}.
*
* @param rootPane {@link JRootPane} which settings are being managed
* @param configuration {@link Configuration}
*/
public RootPaneSettingsProcessor ( @NotNull final JRootPane rootPane, @NotNull final Configuration configuration )
{
super ( rootPane, configuration );
}
@Override
protected void register ( @NotNull final JRootPane rootPane )
{
final Window window = CoreSwingUtils.getNonNullWindowAncestor ( rootPane );
/**
* Tracking {@link Window} movement.
*/
componentListener = new ComponentAdapter ()
{
@Override
public void componentResized ( @NotNull final ComponentEvent e )
{
save ();
}
@Override
public void componentMoved ( @NotNull final ComponentEvent e )
{
save ();
}
};
/**
* Tracking {@link Window} state.
*/
windowStateListener = new WindowStateListener ()
{
@Override
public void windowStateChanged ( @NotNull final WindowEvent e )
{
save ();
}
};
/**
* Ensure listeners are only used when {@link Window} is displayed.
*/
windowVisibilityBehavior = new VisibilityBehavior<Window> ( window, true )
{
@Override
protected void displayed ( @NotNull final Window window )
{
window.addComponentListener ( componentListener );
window.addWindowStateListener ( windowStateListener );
}
@Override
protected void hidden ( @NotNull final Window window )
{
window.removeWindowStateListener ( windowStateListener );
window.removeComponentListener ( componentListener );
}
};
windowVisibilityBehavior.install ();
}
@Override
protected void unregister ( @NotNull final JRootPane rootPane )
{
windowVisibilityBehavior.uninstall ();
windowVisibilityBehavior = null;
windowStateListener = null;
componentListener = null;
}
@Nullable
@Override
protected WindowState createDefaultValue ()
{
return new WindowState ( component () );
}
@Override
protected void loadSettings ( @NotNull final JRootPane rootPane )
{
loadSettings ().apply ( rootPane );
}
@Override
protected void saveSettings ( @NotNull final JRootPane rootPane )
{
saveSettings ( loadSettings ().retrieve ( rootPane ) );
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
namespace test {
macro ElementsKindTestHelper1(kind: constexpr ElementsKind): bool {
if constexpr ((kind == UINT8_ELEMENTS) || (kind == UINT16_ELEMENTS)) {
return true;
} else {
return false;
}
}
macro ElementsKindTestHelper2(kind: constexpr ElementsKind): constexpr bool {
return ((kind == UINT8_ELEMENTS) || (kind == UINT16_ELEMENTS));
}
macro LabelTestHelper1(): never
labels Label1 {
goto Label1;
}
macro LabelTestHelper2(): never
labels Label2(Smi) {
goto Label2(42);
}
macro LabelTestHelper3(): never
labels Label3(Oddball, Smi) {
goto Label3(Null, 7);
}
@export
macro TestConstexpr1() {
check(FromConstexpr<bool>(IsFastElementsKind(PACKED_SMI_ELEMENTS)));
}
@export
macro TestConstexprIf() {
check(ElementsKindTestHelper1(UINT8_ELEMENTS));
check(ElementsKindTestHelper1(UINT16_ELEMENTS));
check(!ElementsKindTestHelper1(UINT32_ELEMENTS));
}
@export
macro TestConstexprReturn() {
check(FromConstexpr<bool>(ElementsKindTestHelper2(UINT8_ELEMENTS)));
check(FromConstexpr<bool>(ElementsKindTestHelper2(UINT16_ELEMENTS)));
check(!FromConstexpr<bool>(ElementsKindTestHelper2(UINT32_ELEMENTS)));
check(FromConstexpr<bool>(!ElementsKindTestHelper2(UINT32_ELEMENTS)));
}
@export
macro TestGotoLabel(): Boolean {
try {
LabelTestHelper1() otherwise Label1;
}
label Label1 {
return True;
}
}
@export
macro TestGotoLabelWithOneParameter(): Boolean {
try {
LabelTestHelper2() otherwise Label2;
}
label Label2(smi: Smi) {
check(smi == 42);
return True;
}
}
@export
macro TestGotoLabelWithTwoParameters(): Boolean {
try {
LabelTestHelper3() otherwise Label3;
}
label Label3(o: Oddball, smi: Smi) {
check(o == Null);
check(smi == 7);
return True;
}
}
builtin GenericBuiltinTest<T: type>(_c: Context, _param: T): JSAny {
return Null;
}
GenericBuiltinTest<JSAny>(_c: Context, param: JSAny): JSAny {
return param;
}
@export
macro TestBuiltinSpecialization(c: Context) {
check(GenericBuiltinTest<Smi>(c, 0) == Null);
check(GenericBuiltinTest<Smi>(c, 1) == Null);
check(GenericBuiltinTest<JSAny>(c, Undefined) == Undefined);
check(GenericBuiltinTest<JSAny>(c, Undefined) == Undefined);
}
macro LabelTestHelper4(flag: constexpr bool): never
labels Label4, Label5 {
if constexpr (flag) {
goto Label4;
} else {
goto Label5;
}
}
macro CallLabelTestHelper4(flag: constexpr bool): bool {
try {
LabelTestHelper4(flag) otherwise Label4, Label5;
}
label Label4 {
return true;
}
label Label5 {
return false;
}
}
@export
macro TestPartiallyUnusedLabel(): Boolean {
const r1: bool = CallLabelTestHelper4(true);
const r2: bool = CallLabelTestHelper4(false);
if (r1 && !r2) {
return True;
} else {
return False;
}
}
macro GenericMacroTest<T: type>(_param: T): Object {
return Undefined;
}
GenericMacroTest<Object>(param2: Object): Object {
return param2;
}
macro GenericMacroTestWithLabels<T: type>(_param: T): Object
labels _X {
return Undefined;
}
GenericMacroTestWithLabels<Object>(param2: Object): Object
labels Y {
return Cast<Smi>(param2) otherwise Y;
}
@export
macro TestMacroSpecialization() {
try {
const _smi0: Smi = 0;
check(GenericMacroTest<Smi>(0) == Undefined);
check(GenericMacroTest<Smi>(1) == Undefined);
check(GenericMacroTest<Object>(Null) == Null);
check(GenericMacroTest<Object>(False) == False);
check(GenericMacroTest<Object>(True) == True);
check((GenericMacroTestWithLabels<Smi>(0) otherwise Fail) == Undefined);
check((GenericMacroTestWithLabels<Smi>(0) otherwise Fail) == Undefined);
try {
GenericMacroTestWithLabels<Object>(False) otherwise Expected;
}
label Expected {}
}
label Fail {
unreachable;
}
}
builtin TestHelperPlus1(_context: Context, x: Smi): Smi {
return x + 1;
}
builtin TestHelperPlus2(_context: Context, x: Smi): Smi {
return x + 2;
}
@export
macro TestFunctionPointers(implicit context: Context)(): Boolean {
let fptr: builtin(Context, Smi) => Smi = TestHelperPlus1;
check(fptr(context, 42) == 43);
fptr = TestHelperPlus2;
check(fptr(context, 42) == 44);
return True;
}
@export
macro TestVariableRedeclaration(implicit context: Context)(): Boolean {
let _var1: int31 = FromConstexpr<bool>(42 == 0) ? 0 : 1;
let _var2: int31 = FromConstexpr<bool>(42 == 0) ? 1 : 0;
return True;
}
@export
macro TestTernaryOperator(x: Smi): Smi {
const b: bool = x < 0 ? true : false;
return b ? x - 10 : x + 100;
}
@export
macro TestFunctionPointerToGeneric(c: Context) {
const fptr1: builtin(Context, Smi) => JSAny = GenericBuiltinTest<Smi>;
const fptr2: builtin(Context, JSAny) => JSAny = GenericBuiltinTest<JSAny>;
check(fptr1(c, 0) == Null);
check(fptr1(c, 1) == Null);
check(fptr2(c, Undefined) == Undefined);
check(fptr2(c, Undefined) == Undefined);
}
type ObjectToObject = builtin(Context, JSAny) => JSAny;
@export
macro TestTypeAlias(x: ObjectToObject): BuiltinPtr {
return x;
}
@export
macro TestUnsafeCast(implicit context: Context)(n: Number): Boolean {
if (TaggedIsSmi(n)) {
const m: Smi = UnsafeCast<Smi>(n);
check(TestHelperPlus1(context, m) == 11);
return True;
}
return False;
}
@export
macro TestHexLiteral() {
check(Convert<intptr>(0xffff) + 1 == 0x10000);
check(Convert<intptr>(-0xffff) == -65535);
}
@export
macro TestLargeIntegerLiterals(implicit c: Context)() {
let _x: int32 = 0x40000000;
let _y: int32 = 0x7fffffff;
}
@export
macro TestMultilineAssert() {
const someVeryLongVariableNameThatWillCauseLineBreaks: Smi = 5;
check(
someVeryLongVariableNameThatWillCauseLineBreaks > 0 &&
someVeryLongVariableNameThatWillCauseLineBreaks < 10);
}
@export
macro TestNewlineInString() {
Print('Hello, World!\n');
}
const kConstexprConst: constexpr int31 = 5;
const kIntptrConst: intptr = 4;
const kSmiConst: Smi = 3;
@export
macro TestModuleConstBindings() {
check(kConstexprConst == Int32Constant(5));
check(kIntptrConst == 4);
check(kSmiConst == 3);
}
@export
macro TestLocalConstBindings() {
const x: constexpr int31 = 3;
const xSmi: Smi = x;
{
const x: Smi = x + FromConstexpr<Smi>(1);
check(x == xSmi + 1);
const xSmi: Smi = x;
check(x == xSmi);
check(x == 4);
}
check(xSmi == 3);
check(x == xSmi);
}
struct TestStructA {
indexes: FixedArray;
i: Smi;
k: Number;
}
struct TestStructB {
x: TestStructA;
y: Smi;
}
@export
macro TestStruct1(i: TestStructA): Smi {
return i.i;
}
@export
macro TestStruct2(implicit context: Context)(): TestStructA {
return TestStructA{
indexes: UnsafeCast<FixedArray>(kEmptyFixedArray),
i: 27,
k: 31
};
}
@export
macro TestStruct3(implicit context: Context)(): TestStructA {
let a: TestStructA =
TestStructA{indexes: UnsafeCast<FixedArray>(kEmptyFixedArray), i: 13, k: 5};
let _b: TestStructA = a;
const c: TestStructA = TestStruct2();
a.i = TestStruct1(c);
a.k = a.i;
let d: TestStructB;
d.x = a;
d = TestStructB{x: a, y: 7};
let _e: TestStructA = d.x;
let f: Smi = TestStructA{
indexes: UnsafeCast<FixedArray>(kEmptyFixedArray),
i: 27,
k: 31
}.i;
f = TestStruct2().i;
return a;
}
struct TestStructC {
x: TestStructA;
y: TestStructA;
}
@export
macro TestStruct4(implicit context: Context)(): TestStructC {
return TestStructC{x: TestStruct2(), y: TestStruct2()};
}
macro TestStructInLabel(implicit context: Context)(): never labels
Foo(TestStructA) {
goto Foo(TestStruct2());
}
@export // Silence unused warning.
macro CallTestStructInLabel(implicit context: Context)() {
try {
TestStructInLabel() otherwise Foo;
}
label Foo(_s: TestStructA) {}
}
// This macro tests different versions of the for-loop where some parts
// are (not) present.
@export
macro TestForLoop() {
let sum: Smi = 0;
for (let i: Smi = 0; i < 5; ++i) sum += i;
check(sum == 10);
sum = 0;
let j: Smi = 0;
for (; j < 5; ++j) sum += j;
check(sum == 10);
sum = 0;
j = 0;
for (; j < 5;) sum += j++;
check(sum == 10);
// Check that break works. No test expression.
sum = 0;
for (let i: Smi = 0;; ++i) {
if (i == 5) break;
sum += i;
}
check(sum == 10);
sum = 0;
j = 0;
for (;;) {
if (j == 5) break;
sum += j;
j++;
}
check(sum == 10);
// The following tests are the same as above, but use continue to skip
// index 3.
sum = 0;
for (let i: Smi = 0; i < 5; ++i) {
if (i == 3) continue;
sum += i;
}
check(sum == 7);
sum = 0;
j = 0;
for (; j < 5; ++j) {
if (j == 3) continue;
sum += j;
}
check(sum == 7);
sum = 0;
j = 0;
for (; j < 5;) {
if (j == 3) {
j++;
continue;
}
sum += j;
j++;
}
check(sum == 7);
sum = 0;
for (let i: Smi = 0;; ++i) {
if (i == 3) continue;
if (i == 5) break;
sum += i;
}
check(sum == 7);
sum = 0;
j = 0;
for (;;) {
if (j == 3) {
j++;
continue;
}
if (j == 5) break;
sum += j;
j++;
}
check(sum == 7);
j = 0;
try {
for (;;) {
if (++j == 10) goto Exit;
}
}
label Exit {
check(j == 10);
}
// Test if we can handle uninitialized values on the stack.
let _i: Smi;
for (let j: Smi = 0; j < 10; ++j) {
}
}
@export
macro TestSubtyping(x: Smi) {
const _foo: JSAny = x;
}
macro IncrementIfSmi<A: type>(x: A): A {
typeswitch (x) {
case (x: Smi): {
return x + 1;
}
case (o: A): {
return o;
}
}
}
type NumberOrFixedArray = Number | FixedArray;
macro TypeswitchExample(implicit context: Context)(x: NumberOrFixedArray):
int32 {
let result: int32 = 0;
typeswitch (IncrementIfSmi(x)) {
case (_x: FixedArray): {
result = result + 1;
}
case (Number): {
result = result + 2;
}
}
result = result * 10;
typeswitch (IncrementIfSmi(x)) {
case (x: Smi): {
result = result + Convert<int32>(x);
}
case (a: FixedArray): {
result = result + Convert<int32>(a.length);
}
case (_x: HeapNumber): {
result = result + 7;
}
}
return result;
}
@export
macro TestTypeswitch(implicit context: Context)() {
check(TypeswitchExample(FromConstexpr<Smi>(5)) == 26);
const a: FixedArray = AllocateZeroedFixedArray(3);
check(TypeswitchExample(a) == 13);
check(TypeswitchExample(FromConstexpr<Number>(0.5)) == 27);
}
@export
macro TestTypeswitchAsanLsanFailure(implicit context: Context)(obj: Object) {
typeswitch (obj) {
case (_o: Smi): {
}
case (_o: JSTypedArray): {
}
case (_o: JSReceiver): {
}
case (_o: HeapObject): {
}
}
}
macro ExampleGenericOverload<A: type>(o: Object): A {
return o;
}
macro ExampleGenericOverload<A: type>(o: Smi): A {
return o + 1;
}
@export
macro TestGenericOverload(implicit context: Context)() {
const xSmi: Smi = 5;
const xObject: Object = xSmi;
check(ExampleGenericOverload<Smi>(xSmi) == 6);
check(UnsafeCast<Smi>(ExampleGenericOverload<Object>(xObject)) == 5);
}
@export
macro TestEquality(implicit context: Context)() {
const notEqual: bool =
AllocateHeapNumberWithValue(0.5) != AllocateHeapNumberWithValue(0.5);
check(!notEqual);
const equal: bool =
AllocateHeapNumberWithValue(0.5) == AllocateHeapNumberWithValue(0.5);
check(equal);
}
@export
macro TestOrAnd(x: bool, y: bool, z: bool): bool {
return x || y && z ? true : false;
}
@export
macro TestAndOr(x: bool, y: bool, z: bool): bool {
return x && y || z ? true : false;
}
@export
macro TestLogicalOperators() {
check(TestAndOr(true, true, true));
check(TestAndOr(true, true, false));
check(TestAndOr(true, false, true));
check(!TestAndOr(true, false, false));
check(TestAndOr(false, true, true));
check(!TestAndOr(false, true, false));
check(TestAndOr(false, false, true));
check(!TestAndOr(false, false, false));
check(TestOrAnd(true, true, true));
check(TestOrAnd(true, true, false));
check(TestOrAnd(true, false, true));
check(TestOrAnd(true, false, false));
check(TestOrAnd(false, true, true));
check(!TestOrAnd(false, true, false));
check(!TestOrAnd(false, false, true));
check(!TestOrAnd(false, false, false));
}
@export
macro TestCall(i: Smi): Smi labels A {
if (i < 5) return i;
goto A;
}
@export
macro TestOtherwiseWithCode1() {
let v: Smi = 0;
let s: Smi = 1;
try {
TestCall(10) otherwise goto B(++s);
}
label B(v1: Smi) {
v = v1;
}
assert(v == 2);
}
@export
macro TestOtherwiseWithCode2() {
let s: Smi = 0;
for (let i: Smi = 0; i < 10; ++i) {
TestCall(i) otherwise break;
++s;
}
assert(s == 5);
}
@export
macro TestOtherwiseWithCode3() {
let s: Smi = 0;
for (let i: Smi = 0; i < 10; ++i) {
s += TestCall(i) otherwise break;
}
assert(s == 10);
}
@export
macro TestForwardLabel() {
try {
goto A;
}
label A {
goto B(5);
}
label B(b: Smi) {
assert(b == 5);
}
}
@export
macro TestQualifiedAccess(implicit context: Context)() {
const s: Smi = 0;
check(!Is<JSArray>(s));
}
@export
macro TestCatch1(implicit context: Context)(): Smi {
let r: Smi = 0;
try {
ThrowTypeError(kInvalidArrayLength);
} catch (_e) {
r = 1;
return r;
}
}
@export
macro TestCatch2Wrapper(implicit context: Context)(): never {
ThrowTypeError(kInvalidArrayLength);
}
@export
macro TestCatch2(implicit context: Context)(): Smi {
let r: Smi = 0;
try {
TestCatch2Wrapper();
} catch (_e) {
r = 2;
return r;
}
}
@export
macro TestCatch3WrapperWithLabel(implicit context: Context)():
never labels _Abort {
ThrowTypeError(kInvalidArrayLength);
}
@export
macro TestCatch3(implicit context: Context)(): Smi {
let r: Smi = 0;
try {
TestCatch3WrapperWithLabel() otherwise Abort;
}
label Abort {
return -1;
}
catch (_e) {
r = 2;
return r;
}
}
// This test doesn't actually test the functionality of iterators,
// it's only purpose is to make sure tha the CSA macros in the
// IteratorBuiltinsAssembler match the signatures provided in
// iterator.tq.
@export
macro TestIterator(implicit context: Context)(o: JSReceiver, map: Map) {
try {
const t1: JSAny = iterator::GetIteratorMethod(o);
const t2: iterator::IteratorRecord = iterator::GetIterator(o);
const _t3: JSAny = iterator::IteratorStep(t2) otherwise Fail;
const _t4: JSAny = iterator::IteratorStep(t2, map) otherwise Fail;
const t5: JSAny = iterator::IteratorValue(o);
const _t6: JSAny = iterator::IteratorValue(o, map);
const _t7: JSArray = iterator::IterableToList(t1, t1);
iterator::IteratorCloseOnException(t2, t5);
}
label Fail {}
}
@export
macro TestFrame1(implicit context: Context)() {
const f: Frame = LoadFramePointer();
const frameType: FrameType =
Cast<FrameType>(f.context_or_frame_type) otherwise unreachable;
assert(frameType == STUB_FRAME);
assert(f.caller == LoadParentFramePointer());
typeswitch (f) {
case (_f: StandardFrame): {
unreachable;
}
case (_f: ArgumentsAdaptorFrame): {
unreachable;
}
case (_f: StubFrame): {
}
}
}
@export
macro TestNew(implicit context: Context)() {
const f: JSArray = NewJSArray();
check(f.IsEmpty());
f.length = 0;
}
struct TestInner {
SetX(newValue: int32) {
this.x = newValue;
}
GetX(): int32 {
return this.x;
}
x: int32;
y: int32;
}
struct TestOuter {
a: int32;
b: TestInner;
c: int32;
}
@export
macro TestStructConstructor(implicit context: Context)() {
// Test default constructor
let a: TestOuter = TestOuter{a: 5, b: TestInner{x: 6, y: 7}, c: 8};
check(a.a == 5);
check(a.b.x == 6);
check(a.b.y == 7);
check(a.c == 8);
a.b.x = 1;
check(a.b.x == 1);
a.b.SetX(2);
check(a.b.x == 2);
check(a.b.GetX() == 2);
}
class InternalClass extends Struct {
Flip() labels NotASmi {
const tmp = Cast<Smi>(this.b) otherwise NotASmi;
this.b = this.a;
this.a = tmp;
}
a: Smi;
b: Number;
}
macro NewInternalClass(x: Smi): InternalClass {
return new InternalClass{a: x, b: x + 1};
}
@export
macro TestInternalClass(implicit context: Context)() {
const o = NewInternalClass(5);
o.Flip() otherwise unreachable;
check(o.a == 6);
check(o.b == 5);
}
struct StructWithConst {
TestMethod1(): int32 {
return this.b;
}
TestMethod2(): Object {
return this.a;
}
a: Object;
const b: int32;
}
@export
macro TestConstInStructs() {
const x = StructWithConst{a: Null, b: 1};
let y = StructWithConst{a: Null, b: 1};
y.a = Undefined;
const _copy = x;
check(x.TestMethod1() == 1);
check(x.TestMethod2() == Null);
}
struct TestIterator {
Next(): Object labels NoMore {
if (this.count-- == 0) goto NoMore;
return TheHole;
}
count: Smi;
}
@export
macro TestNewFixedArrayFromSpread(implicit context: Context)(): Object {
let i = TestIterator{count: 5};
return new FixedArray{map: kFixedArrayMap, length: 5, objects: ...i};
}
class SmiPair extends Struct {
GetA():&Smi {
return & this.a;
}
a: Smi;
b: Smi;
}
macro Swap<T: type>(a:&T, b:&T) {
const tmp = * a;
* a = * b;
* b = tmp;
}
@export
macro TestReferences() {
const array = new SmiPair{a: 7, b: 2};
const ref:&Smi = & array.a;
* ref = 3 + * ref;
-- * ref;
Swap(& array.b, array.GetA());
check(array.a == 2);
check(array.b == 9);
}
@export
macro TestSlices() {
const it = TestIterator{count: 3};
const a = new FixedArray{map: kFixedArrayMap, length: 3, objects: ...it};
check(a.length == 3);
const oneTwoThree = Convert<Smi>(123);
a.objects[0] = oneTwoThree;
const firstRef:&Object = & a.objects[0];
check(TaggedEqual(* firstRef, oneTwoThree));
const slice: torque_internal::Slice<Object> = & a.objects;
const firstRefAgain:&Object = slice.TryAtIndex(0) otherwise unreachable;
check(TaggedEqual(* firstRefAgain, oneTwoThree));
const threeTwoOne = Convert<Smi>(321);
* firstRefAgain = threeTwoOne;
check(TaggedEqual(a.objects[0], threeTwoOne));
// *slice; // error, not allowed
// a.objects; // error, not allowed
// a.objects = slice; // error, not allowed
// TODO(gsps): Currently errors, but should be allowed:
// const _sameSlice: torque_internal::Slice<Object> = &(*slice);
// (*slice)[0] : Smi
}
@export
macro TestSliceEnumeration(implicit context: Context)(): Undefined {
const fixedArray: FixedArray = AllocateZeroedFixedArray(3);
for (let i: intptr = 0; i < 3; i++) {
check(UnsafeCast<Smi>(fixedArray.objects[i]) == 0);
fixedArray.objects[i] = Convert<Smi>(i) + 3;
}
let slice = & fixedArray.objects;
for (let i: intptr = 0; i < slice.length; i++) {
let ref = slice.TryAtIndex(i) otherwise unreachable;
const value = UnsafeCast<Smi>(* ref);
check(value == Convert<Smi>(i) + 3);
* ref = value + 4;
}
let it = slice.Iterator();
let count: Smi = 0;
while (true) {
let ref = it.Next() otherwise break;
const value = UnsafeCast<Smi>(* ref);
check(value == count + 7);
count++;
}
check(count == 3);
check(it.Empty());
return Undefined;
}
@export
macro TestStaticAssert() {
StaticAssert(1 + 2 == 3);
}
class SmiBox extends Struct {
value: Smi;
unrelated: Smi;
}
builtin NewSmiBox(implicit context: Context)(value: Smi): SmiBox {
return new SmiBox{value, unrelated: 0};
}
@export
macro TestLoadEliminationFixed(implicit context: Context)() {
const box = NewSmiBox(123);
const v1 = box.value;
box.unrelated = 999;
const v2 = (box.unrelated == 0) ? box.value : box.value;
StaticAssert(TaggedEqual(v1, v2));
box.value = 11;
const v3 = box.value;
const eleven: Smi = 11;
StaticAssert(TaggedEqual(v3, eleven));
}
@export
macro TestLoadEliminationVariable(implicit context: Context)() {
const a = UnsafeCast<FixedArray>(kEmptyFixedArray);
const box = NewSmiBox(1);
const v1 = a.objects[box.value];
const u1 = a.objects[box.value + 2];
const v2 = a.objects[box.value];
const u2 = a.objects[box.value + 2];
StaticAssert(TaggedEqual(v1, v2));
StaticAssert(TaggedEqual(u1, u2));
}
@export
macro TestRedundantArrayElementCheck(implicit context: Context)(): Smi {
const a = kEmptyFixedArray;
for (let i: Smi = 0; i < a.length; i++) {
if (a.objects[i] == TheHole) {
if (a.objects[i] == TheHole) {
return -1;
} else {
StaticAssert(false);
}
}
}
return 1;
}
@export
macro TestRedundantSmiCheck(implicit context: Context)(): Smi {
const a = kEmptyFixedArray;
const x = a.objects[1];
typeswitch (x) {
case (Smi): {
Cast<Smi>(x) otherwise VerifiedUnreachable();
return -1;
}
case (Object): {
}
}
return 1;
}
struct SBox<T: type> {
value: T;
}
@export
macro TestGenericStruct1(): intptr {
const i: intptr = 123;
let box = SBox{value: i};
let boxbox: SBox<SBox<intptr>> = SBox{value: box};
check(box.value == 123);
boxbox.value.value *= 2;
check(boxbox.value.value == 246);
return boxbox.value.value;
}
struct TestTuple<T1: type, T2: type> {
const fst: T1;
const snd: T2;
}
macro TupleSwap<T1: type, T2: type>(tuple: TestTuple<T1, T2>):
TestTuple<T2, T1> {
return TestTuple{fst: tuple.snd, snd: tuple.fst};
}
@export
macro TestGenericStruct2():
TestTuple<TestTuple<intptr, Smi>, TestTuple<Smi, intptr>> {
const intptrAndSmi = TestTuple<intptr, Smi>{fst: 1, snd: 2};
const smiAndIntptr = TupleSwap(intptrAndSmi);
check(intptrAndSmi.fst == smiAndIntptr.snd);
check(intptrAndSmi.snd == smiAndIntptr.fst);
const tupleTuple =
TestTuple<TestTuple<intptr, Smi>>{fst: intptrAndSmi, snd: smiAndIntptr};
return tupleTuple;
}
macro BranchAndWriteResult(x: Smi, box: SmiBox): bool {
if (x > 5 || x < 0) {
box.value = 1;
return true;
} else {
box.value = 2;
return false;
}
}
@export
macro TestBranchOnBoolOptimization(implicit context: Context)(input: Smi) {
const box = NewSmiBox(1);
// If the two branches get combined into one, we should be able to determine
// the value of {box} statically.
if (BranchAndWriteResult(input, box)) {
StaticAssert(box.value == 1);
} else {
StaticAssert(box.value == 2);
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
This file is part of the Grantlee template system.
Copyright (c) 2008 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plaintextmarkupbuilder.h"
namespace Grantlee
{
class PlainTextMarkupBuilderPrivate
{
public:
PlainTextMarkupBuilderPrivate(PlainTextMarkupBuilder *b) : q_ptr(b) {}
/**
Get a letter string to represent a number.
The numbers 1-26 are represented by a-z, and 27-52 by aa-az, 53-79 by
ba-bz etc.
@param The number to convert
@return The letter string representation of the number.
*/
QString getLetterString(int itemNumber);
QString getRomanString(int itemNumber);
/**
Gets a block of references in the body of the text.
This is an ordered list of links and images in the text.
*/
QString getReferences();
QStringList m_urls;
QList<QTextListFormat::Style> currentListItemStyles;
QList<int> currentListItemNumbers;
QString activeLink;
QString m_text;
PlainTextMarkupBuilder *q_ptr;
Q_DECLARE_PUBLIC(PlainTextMarkupBuilder)
};
}
using namespace Grantlee;
QString PlainTextMarkupBuilderPrivate::getRomanString(int item)
{
QString result;
// Code based to gui/text/qtextlist.cpp
if (item < 5000) {
QString romanNumeral;
// works for up to 4999 items
auto romanSymbols = QStringLiteral("iiivixxxlxcccdcmmmm");
int c[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
auto n = item;
for (auto i = 12; i >= 0; n %= c[i], i--) {
auto q = n / c[i];
if (q > 0) {
auto startDigit = i + (i + 3) / 4;
int numDigits;
if (i % 4) {
// c[i] == 4|5|9|40|50|90|400|500|900
if ((i - 2) % 4) {
// c[i] == 4|9|40|90|400|900
// => with subtraction (IV, IX, XL, XC, ...)
numDigits = 2;
} else {
// c[i] == 5|50|500 (V, L, D)
numDigits = 1;
}
} else {
// c[i] == 1|10|100|1000 (I, II, III, X, XX, ...)
numDigits = q;
}
romanNumeral.append(romanSymbols.mid(startDigit, numDigits));
}
}
result = romanNumeral;
} else {
result = QStringLiteral("?");
}
return result;
}
QString PlainTextMarkupBuilderPrivate::getLetterString(int itemNumber)
{
QString letterString;
while (true) {
// Create the letter string by prepending one char at a time.
// The itemNumber is converted to a number in the base 36 (number of
// letters in the alphabet plus 10) after being increased by 10
// (to pass out the digits 0 to 9).
letterString.prepend(QStringLiteral("%1").arg(
(itemNumber % LETTERSINALPHABET) + DIGITSOFFSET,
0, // no padding while building this string.
LETTERSINALPHABET + DIGITSOFFSET));
if ((itemNumber >= LETTERSINALPHABET)) {
itemNumber = itemNumber / LETTERSINALPHABET;
itemNumber--;
} else {
break;
}
}
return letterString;
}
QString PlainTextMarkupBuilderPrivate::getReferences()
{
QString refs;
if (!m_urls.isEmpty()) {
refs.append(QStringLiteral("\n--------\n"));
auto index = 1;
while (!m_urls.isEmpty()) {
refs.append(
QStringLiteral("[%1] %2\n").arg(index++).arg(m_urls.takeFirst()));
}
}
return refs;
}
PlainTextMarkupBuilder::PlainTextMarkupBuilder()
: d_ptr(new PlainTextMarkupBuilderPrivate(this))
{
}
PlainTextMarkupBuilder::~PlainTextMarkupBuilder() { delete d_ptr; }
void PlainTextMarkupBuilder::beginStrong()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('*'));
}
void PlainTextMarkupBuilder::endStrong()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('*'));
}
void PlainTextMarkupBuilder::beginEmph()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('/'));
}
void PlainTextMarkupBuilder::endEmph()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('/'));
}
void PlainTextMarkupBuilder::beginUnderline()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('_'));
}
void PlainTextMarkupBuilder::endUnderline()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('_'));
}
void PlainTextMarkupBuilder::beginStrikeout()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('-'));
}
void PlainTextMarkupBuilder::endStrikeout()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('-'));
}
void PlainTextMarkupBuilder::beginAnchor(const QString &href,
const QString &name)
{
Q_D(PlainTextMarkupBuilder);
Q_UNUSED(name);
if (!d->m_urls.contains(href)) {
d->m_urls.append(href);
}
d->activeLink = href;
}
void PlainTextMarkupBuilder::endAnchor()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(
QStringLiteral("[%1]").arg(d->m_urls.indexOf(d->activeLink) + 1));
}
void PlainTextMarkupBuilder::endParagraph()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('\n'));
}
void PlainTextMarkupBuilder::addNewline()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('\n'));
}
void PlainTextMarkupBuilder::insertHorizontalRule(int width)
{
Q_UNUSED(width)
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QStringLiteral("--------------------\n"));
}
int PlainTextMarkupBuilder::addReference(const QString &reference)
{
Q_D(PlainTextMarkupBuilder);
if (!d->m_urls.contains(reference))
d->m_urls.append(reference);
return d->m_urls.indexOf(reference) + 1;
}
void PlainTextMarkupBuilder::insertImage(const QString &src, qreal width,
qreal height)
{
Q_D(PlainTextMarkupBuilder);
Q_UNUSED(width)
Q_UNUSED(height)
auto ref = addReference(src);
d->m_text.append(QStringLiteral("[%1]").arg(ref));
}
void PlainTextMarkupBuilder::beginList(QTextListFormat::Style style)
{
Q_D(PlainTextMarkupBuilder);
d->currentListItemStyles.append(style);
d->currentListItemNumbers.append(0);
}
void PlainTextMarkupBuilder::endList()
{
Q_D(PlainTextMarkupBuilder);
if (!d->currentListItemNumbers.isEmpty()) {
d->currentListItemStyles.removeLast();
d->currentListItemNumbers.removeLast();
}
}
void PlainTextMarkupBuilder::beginListItem()
{
Q_D(PlainTextMarkupBuilder);
for (auto i = 0; i < d->currentListItemNumbers.size(); i++) {
d->m_text.append(QStringLiteral(" "));
}
auto itemNumber = d->currentListItemNumbers.last();
switch (d->currentListItemStyles.last()) {
case QTextListFormat::ListDisc:
d->m_text.append(QStringLiteral(" * "));
break;
case QTextListFormat::ListCircle:
d->m_text.append(QStringLiteral(" o "));
break;
case QTextListFormat::ListSquare:
d->m_text.append(QStringLiteral(" - "));
break;
case QTextListFormat::ListDecimal:
d->m_text.append(QStringLiteral(" %1. ").arg(itemNumber + 1));
break;
case QTextListFormat::ListLowerAlpha:
d->m_text.append(
QStringLiteral(" %1. ").arg(d->getLetterString(itemNumber)));
break;
case QTextListFormat::ListUpperAlpha:
d->m_text.append(
QStringLiteral(" %1. ").arg(d->getLetterString(itemNumber).toUpper()));
break;
case QTextListFormat::ListLowerRoman:
d->m_text.append(
QStringLiteral(" %1. ").arg(d->getRomanString(itemNumber + 1)));
break;
case QTextListFormat::ListUpperRoman:
d->m_text.append(QStringLiteral(" %1. ").arg(
d->getRomanString(itemNumber + 1).toUpper()));
break;
default:
break;
}
}
void PlainTextMarkupBuilder::endListItem()
{
Q_D(PlainTextMarkupBuilder);
d->currentListItemNumbers.last() = d->currentListItemNumbers.last() + 1;
d->m_text.append(QLatin1Char('\n'));
}
void PlainTextMarkupBuilder::beginSuperscript()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QStringLiteral("^{"));
}
void PlainTextMarkupBuilder::endSuperscript()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('}'));
}
void PlainTextMarkupBuilder::beginSubscript()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QStringLiteral("_{"));
}
void PlainTextMarkupBuilder::endSubscript()
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(QLatin1Char('}'));
}
void PlainTextMarkupBuilder::appendLiteralText(const QString &text)
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(text);
}
void PlainTextMarkupBuilder::appendRawText(const QString &text)
{
Q_D(PlainTextMarkupBuilder);
d->m_text.append(text);
}
QString PlainTextMarkupBuilder::getResult()
{
Q_D(PlainTextMarkupBuilder);
auto ret = d->m_text;
ret.append(d->getReferences());
d->m_text.clear();
return ret;
}
void PlainTextMarkupBuilder::beginBackground(const QBrush &brush)
{
Q_UNUSED(brush);
}
void PlainTextMarkupBuilder::beginFontFamily(const QString &family)
{
Q_UNUSED(family);
}
void PlainTextMarkupBuilder::beginFontPointSize(int size) { Q_UNUSED(size); }
void PlainTextMarkupBuilder::beginForeground(const QBrush &brush)
{
Q_UNUSED(brush);
}
void PlainTextMarkupBuilder::beginHeader(int level) { Q_UNUSED(level); }
void PlainTextMarkupBuilder::beginParagraph(Qt::Alignment a, qreal top,
qreal bottom, qreal left,
qreal right)
{
Q_UNUSED(a);
Q_UNUSED(top);
Q_UNUSED(bottom);
Q_UNUSED(left);
Q_UNUSED(right);
}
void PlainTextMarkupBuilder::beginTable(qreal cellpadding, qreal cellspacing,
const QString &width)
{
Q_UNUSED(cellpadding);
Q_UNUSED(cellspacing);
Q_UNUSED(width);
}
void PlainTextMarkupBuilder::beginTableCell(const QString &width, int colSpan,
int rowSpan)
{
Q_UNUSED(width);
Q_UNUSED(colSpan);
Q_UNUSED(rowSpan);
}
void PlainTextMarkupBuilder::beginTableHeaderCell(const QString &width,
int colSpan, int rowSpan)
{
Q_UNUSED(width);
Q_UNUSED(colSpan);
Q_UNUSED(rowSpan);
}
void PlainTextMarkupBuilder::beginTableRow() {}
void PlainTextMarkupBuilder::endBackground() {}
void PlainTextMarkupBuilder::endFontFamily() {}
void PlainTextMarkupBuilder::endFontPointSize() {}
void PlainTextMarkupBuilder::endForeground() {}
void PlainTextMarkupBuilder::endHeader(int level) { Q_UNUSED(level) }
void PlainTextMarkupBuilder::endTable() {}
void PlainTextMarkupBuilder::endTableCell() {}
void PlainTextMarkupBuilder::endTableHeaderCell() {}
void Grantlee::PlainTextMarkupBuilder::endTableRow() {}
|
{
"pile_set_name": "Github"
}
|
<p>Dramatically increase both your swarmlings' meat cost and territory captured.</p><p>This will destroy all {{ game.unit('swarmling').count() | longnum }} of your swarmlings.</p>
|
{
"pile_set_name": "Github"
}
|
&FORCE_EVAL
METHOD QMMM
&DFT
BASIS_SET_FILE_NAME ../GTH_BASIS_SETS
POTENTIAL_FILE_NAME ../POTENTIAL
&MGRID
COMMENSURATE
CUTOFF 100.0
&END MGRID
&SCF
SCF_GUESS atomic
&END SCF
&XC
&XC_FUNCTIONAL PADE
&END XC_FUNCTIONAL
&END XC
LSD
&END DFT
&MM
&FORCEFIELD
PARMTYPE CHM
PARM_FILE_NAME ../../../Fist/sample_pot/charmm.pot
&END FORCEFIELD
&POISSON
&EWALD
EWALD_TYPE ewald
ALPHA 0.44
GMAX 25
&END EWALD
&END POISSON
&END MM
&QMMM
USE_GEEP_LIB 6
&CELL
ABC 8.000 8.000 8.000
PERIODIC XYZ
&END CELL
ECOUPL GAUSS
&MM_KIND H
RADIUS 0.440
&END MM_KIND
&MM_KIND O
RADIUS 0.780
&END MM_KIND
&QM_KIND H
MM_INDEX 4
&END QM_KIND
&QM_KIND O
MM_INDEX 3
&END QM_KIND
&LINK
QM_INDEX 3
QM_KIND H
MM_INDEX 5
&END LINK
&END QMMM
&SUBSYS
&CELL
A 20.082045 0.000000 0.000000
B 0.000000 20.082045 0.000000
C 0.000000 0.000000 20.082045
PERIODIC XYZ
&END CELL
&TOPOLOGY
&GENERATE
CREATE_MOLECULES
&ISOLATED_ATOMS
LIST 1 2
&END ISOLATED_ATOMS
&END GENERATE
CHARGE_EXTENDED
COORD_FILE_NAME ../sample_pdb/wat_nacl.pdb
COORD_FILE_FORMAT PDB
&END TOPOLOGY
&KIND H
BASIS_SET SZV-GTH
POTENTIAL GTH-PADE-q1
&END KIND
&KIND O
BASIS_SET SZV-GTH
POTENTIAL GTH-PADE-q6
&END KIND
&END SUBSYS
&END FORCE_EVAL
&GLOBAL
PROJECT wat_nacl
RUN_TYPE ENERGY_FORCE
&END GLOBAL
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/developer_prefs_category" >
<ListPreference
android:defaultValue="-1"
android:entries="@array/dev_hardware_decoder_list"
android:entryValues="@array/dev_hardware_decoder_values"
android:key="dev_hardware_decoder"
android:summary="@string/dev_hardware_decoder_summary"
android:title="@string/dev_hardware_decoder" />
<CheckBoxPreference
android:defaultValue="true"
android:key="enable_verbose_mode"
android:summary="@string/enable_verbose_mode_summary"
android:title="@string/enable_verbose_mode" />
<PreferenceScreen
android:key="debug_logs"
android:title="@string/debug_logs" />
</PreferenceScreen>
|
{
"pile_set_name": "Github"
}
|
<h3>Manage Roles By User</h3>
<p>
<b>Select a User:</b>
<asp:DropDownList ID="UserList" runat="server" AutoPostBack="True"
DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
</p>
<p>
<asp:Repeater ID="UsersRoleList" runat="server">
<ItemTemplate>
<asp:CheckBox runat="server" ID="RoleCheckBox" AutoPostBack="true"
Text='<%# Container.DataItem %>' />
<br />
</ItemTemplate>
</asp:Repeater>
</p>
|
{
"pile_set_name": "Github"
}
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class FormSingle
Inherits ChaoForm.Form
'Form 重写 Dispose,以清理组件列表。
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
Sub New()
' 此调用是设计器所必需的。
InitializeComponent()
' 在 InitializeComponent() 调用之后添加任何初始化。
End Sub
'Windows 窗体设计器所必需的
Private components As System.ComponentModel.IContainer
'注意: 以下过程是 Windows 窗体设计器所必需的
'可以使用 Windows 窗体设计器修改它。
'不要使用代码编辑器修改它。
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FormSingle))
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.TextBox2 = New System.Windows.Forms.TextBox()
Me.Label4 = New System.Windows.Forms.Label()
Me.TextBox3 = New System.Windows.Forms.TextBox()
Me.Label5 = New System.Windows.Forms.Label()
Me.Label6 = New System.Windows.Forms.Label()
Me.Label7 = New System.Windows.Forms.Label()
Me.TextBox6 = New System.Windows.Forms.TextBox()
Me.Label8 = New System.Windows.Forms.Label()
Me.TextBox7 = New System.Windows.Forms.TextBox()
Me.Label9 = New System.Windows.Forms.Label()
Me.TextBox8 = New System.Windows.Forms.TextBox()
Me.ComboBox1 = New System.Windows.Forms.ComboBox()
Me.DateTimePicker1 = New System.Windows.Forms.DateTimePicker()
Me.Label10 = New System.Windows.Forms.Label()
Me.TextBox1 = New System.Windows.Forms.TextBox()
Me.Label11 = New System.Windows.Forms.Label()
Me.TextBox4 = New System.Windows.Forms.TextBox()
Me.Label12 = New System.Windows.Forms.Label()
Me.TextBox5 = New System.Windows.Forms.TextBox()
Me.Label13 = New System.Windows.Forms.Label()
Me.TextBox9 = New System.Windows.Forms.TextBox()
Me.Label14 = New System.Windows.Forms.Label()
Me.Label15 = New System.Windows.Forms.Label()
Me.TextBox10 = New System.Windows.Forms.TextBox()
Me.ComboBox2 = New System.Windows.Forms.ComboBox()
Me.Chao_Button1 = New ChaoControls.Chao_Button()
Me.Chao_Button2 = New ChaoControls.Chao_Button()
Me.Button1 = New System.Windows.Forms.Button()
Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog()
Me.TextBox11 = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.Label16 = New System.Windows.Forms.Label()
Me.Chao_CheckBox1 = New ChaoControls.Chao_CheckBox()
Me.Label17 = New System.Windows.Forms.Label()
CType(Me.FormIconPicB, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.SetPicB, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.TitlePicB, System.ComponentModel.ISupportInitialize).BeginInit()
Me.TitlePanel.SuspendLayout()
CType(Me.SkinPicB, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'FormIconPicB
'
Me.FormIconPicB.Location = New System.Drawing.Point(16, 16)
'
'FormTextLabel
'
Me.FormTextLabel.Location = New System.Drawing.Point(64, 18)
Me.FormTextLabel.Size = New System.Drawing.Size(132, 27)
Me.FormTextLabel.Text = "导入单个视频"
'
'SetPicB
'
Me.SetPicB.Image = CType(resources.GetObject("SetPicB.Image"), System.Drawing.Image)
Me.SetPicB.Location = New System.Drawing.Point(358, 18)
'
'TitlePanel
'
Me.TitlePanel.BackgroundImage = Global.database.My.Resources.Picture.panel_bg
Me.TitlePanel.Size = New System.Drawing.Size(548, 64)
'
'SkinPicB
'
Me.SkinPicB.Location = New System.Drawing.Point(350, 16)
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.BackColor = System.Drawing.Color.White
Me.Label2.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label2.Location = New System.Drawing.Point(28, 70)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(92, 27)
Me.Label2.TabIndex = 66
Me.Label2.Text = "选择文件"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.BackColor = System.Drawing.Color.White
Me.Label3.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label3.Location = New System.Drawing.Point(30, 108)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(72, 27)
Me.Label3.TabIndex = 68
Me.Label3.Text = "识别码"
'
'TextBox2
'
Me.TextBox2.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox2.BackColor = System.Drawing.Color.White
Me.TextBox2.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox2.Location = New System.Drawing.Point(133, 108)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New System.Drawing.Size(404, 25)
Me.TextBox2.TabIndex = 67
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.BackColor = System.Drawing.Color.White
Me.Label4.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label4.Location = New System.Drawing.Point(38, 250)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(52, 27)
Me.Label4.TabIndex = 70
Me.Label4.Text = "名称"
'
'TextBox3
'
Me.TextBox3.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox3.BackColor = System.Drawing.Color.White
Me.TextBox3.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox3.Location = New System.Drawing.Point(134, 250)
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.Size = New System.Drawing.Size(404, 25)
Me.TextBox3.TabIndex = 69
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.BackColor = System.Drawing.Color.White
Me.Label5.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label5.Location = New System.Drawing.Point(18, 201)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(92, 27)
Me.Label5.TabIndex = 72
Me.Label5.Text = "视频类型"
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.BackColor = System.Drawing.Color.White
Me.Label6.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label6.Location = New System.Drawing.Point(18, 297)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(92, 27)
Me.Label6.TabIndex = 74
Me.Label6.Text = "发行日期"
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.BackColor = System.Drawing.Color.White
Me.Label7.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label7.Location = New System.Drawing.Point(18, 338)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(92, 27)
Me.Label7.TabIndex = 76
Me.Label7.Text = "播放时长"
'
'TextBox6
'
Me.TextBox6.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox6.BackColor = System.Drawing.Color.White
Me.TextBox6.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox6.Location = New System.Drawing.Point(134, 338)
Me.TextBox6.Name = "TextBox6"
Me.TextBox6.Size = New System.Drawing.Size(346, 25)
Me.TextBox6.TabIndex = 75
'
'Label8
'
Me.Label8.AutoSize = True
Me.Label8.BackColor = System.Drawing.Color.White
Me.Label8.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label8.Location = New System.Drawing.Point(28, 379)
Me.Label8.Name = "Label8"
Me.Label8.Size = New System.Drawing.Size(72, 27)
Me.Label8.TabIndex = 78
Me.Label8.Text = "制作商"
'
'TextBox7
'
Me.TextBox7.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox7.BackColor = System.Drawing.Color.White
Me.TextBox7.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox7.Location = New System.Drawing.Point(134, 379)
Me.TextBox7.Name = "TextBox7"
Me.TextBox7.Size = New System.Drawing.Size(404, 25)
Me.TextBox7.TabIndex = 77
'
'Label9
'
Me.Label9.AutoSize = True
Me.Label9.BackColor = System.Drawing.Color.White
Me.Label9.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label9.Location = New System.Drawing.Point(28, 420)
Me.Label9.Name = "Label9"
Me.Label9.Size = New System.Drawing.Size(72, 27)
Me.Label9.TabIndex = 80
Me.Label9.Text = "发行商"
'
'TextBox8
'
Me.TextBox8.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox8.BackColor = System.Drawing.Color.White
Me.TextBox8.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox8.Location = New System.Drawing.Point(133, 420)
Me.TextBox8.Name = "TextBox8"
Me.TextBox8.Size = New System.Drawing.Size(404, 25)
Me.TextBox8.TabIndex = 79
'
'ComboBox1
'
Me.ComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ComboBox1.FormattingEnabled = True
Me.ComboBox1.Items.AddRange(New Object() {"0-其它", "1-步兵", "2-骑兵", "3-欧美"})
Me.ComboBox1.Location = New System.Drawing.Point(134, 201)
Me.ComboBox1.Name = "ComboBox1"
Me.ComboBox1.Size = New System.Drawing.Size(200, 23)
Me.ComboBox1.TabIndex = 81
'
'DateTimePicker1
'
Me.DateTimePicker1.CustomFormat = "yyyy-MM-dd"
Me.DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom
Me.DateTimePicker1.Location = New System.Drawing.Point(133, 297)
Me.DateTimePicker1.MinDate = New Date(1900, 1, 1, 0, 0, 0, 0)
Me.DateTimePicker1.Name = "DateTimePicker1"
Me.DateTimePicker1.Size = New System.Drawing.Size(200, 25)
Me.DateTimePicker1.TabIndex = 82
'
'Label10
'
Me.Label10.AutoSize = True
Me.Label10.BackColor = System.Drawing.Color.White
Me.Label10.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label10.Location = New System.Drawing.Point(38, 461)
Me.Label10.Name = "Label10"
Me.Label10.Size = New System.Drawing.Size(52, 27)
Me.Label10.TabIndex = 84
Me.Label10.Text = "导演"
'
'TextBox1
'
Me.TextBox1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox1.BackColor = System.Drawing.Color.White
Me.TextBox1.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox1.Location = New System.Drawing.Point(134, 461)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(404, 25)
Me.TextBox1.TabIndex = 83
'
'Label11
'
Me.Label11.AutoSize = True
Me.Label11.BackColor = System.Drawing.Color.White
Me.Label11.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label11.Location = New System.Drawing.Point(38, 502)
Me.Label11.Name = "Label11"
Me.Label11.Size = New System.Drawing.Size(52, 27)
Me.Label11.TabIndex = 86
Me.Label11.Text = "类别"
'
'TextBox4
'
Me.TextBox4.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox4.BackColor = System.Drawing.Color.White
Me.TextBox4.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox4.Location = New System.Drawing.Point(133, 502)
Me.TextBox4.Name = "TextBox4"
Me.TextBox4.Size = New System.Drawing.Size(404, 25)
Me.TextBox4.TabIndex = 85
'
'Label12
'
Me.Label12.AutoSize = True
Me.Label12.BackColor = System.Drawing.Color.White
Me.Label12.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label12.Location = New System.Drawing.Point(38, 543)
Me.Label12.Name = "Label12"
Me.Label12.Size = New System.Drawing.Size(52, 27)
Me.Label12.TabIndex = 88
Me.Label12.Text = "演员"
'
'TextBox5
'
Me.TextBox5.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox5.BackColor = System.Drawing.Color.White
Me.TextBox5.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox5.Location = New System.Drawing.Point(133, 543)
Me.TextBox5.Name = "TextBox5"
Me.TextBox5.Size = New System.Drawing.Size(404, 25)
Me.TextBox5.TabIndex = 87
'
'Label13
'
Me.Label13.AutoSize = True
Me.Label13.BackColor = System.Drawing.Color.White
Me.Label13.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label13.Location = New System.Drawing.Point(38, 584)
Me.Label13.Name = "Label13"
Me.Label13.Size = New System.Drawing.Size(52, 27)
Me.Label13.TabIndex = 90
Me.Label13.Text = "系列"
'
'TextBox9
'
Me.TextBox9.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox9.BackColor = System.Drawing.Color.White
Me.TextBox9.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox9.Location = New System.Drawing.Point(133, 584)
Me.TextBox9.Name = "TextBox9"
Me.TextBox9.Size = New System.Drawing.Size(404, 25)
Me.TextBox9.TabIndex = 89
'
'Label14
'
Me.Label14.AutoSize = True
Me.Label14.BackColor = System.Drawing.Color.White
Me.Label14.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label14.Location = New System.Drawing.Point(18, 625)
Me.Label14.Name = "Label14"
Me.Label14.Size = New System.Drawing.Size(92, 27)
Me.Label14.TabIndex = 91
Me.Label14.Text = "喜爱程度"
'
'Label15
'
Me.Label15.AutoSize = True
Me.Label15.BackColor = System.Drawing.Color.White
Me.Label15.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label15.Location = New System.Drawing.Point(38, 666)
Me.Label15.Name = "Label15"
Me.Label15.Size = New System.Drawing.Size(52, 27)
Me.Label15.TabIndex = 93
Me.Label15.Text = "标签"
'
'TextBox10
'
Me.TextBox10.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox10.BackColor = System.Drawing.Color.White
Me.TextBox10.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper
Me.TextBox10.Location = New System.Drawing.Point(133, 666)
Me.TextBox10.Name = "TextBox10"
Me.TextBox10.Size = New System.Drawing.Size(404, 25)
Me.TextBox10.TabIndex = 92
'
'ComboBox2
'
Me.ComboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ComboBox2.FormattingEnabled = True
Me.ComboBox2.Items.AddRange(New Object() {"0-不喜欢", "1", "2", "3", "4", "5"})
Me.ComboBox2.Location = New System.Drawing.Point(134, 625)
Me.ComboBox2.Name = "ComboBox2"
Me.ComboBox2.Size = New System.Drawing.Size(199, 23)
Me.ComboBox2.TabIndex = 95
'
'Chao_Button1
'
Me.Chao_Button1.AccessibleRole = Nothing
Me.Chao_Button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom
Me.Chao_Button1.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.Chao_Button1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.Chao_Button1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Chao_Button1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Chao_Button1.BorderColor = System.Drawing.Color.FromArgb(CType(CType(110, Byte), Integer), CType(CType(20, Byte), Integer), CType(CType(239, Byte), Integer))
Me.Chao_Button1.ButtonBackColor = System.Drawing.Color.White
Me.Chao_Button1.ButtonColor = System.Drawing.Color.FromArgb(CType(CType(25, Byte), Integer), CType(CType(117, Byte), Integer), CType(CType(200, Byte), Integer))
Me.Chao_Button1.ButtonFont = New System.Drawing.Font("微软雅黑", 12.0!)
Me.Chao_Button1.ButtonShape = "RoundedRectangle"
Me.Chao_Button1.ButtonText = "导入"
Me.Chao_Button1.ButtonType = "ContainedButton"
Me.Chao_Button1.Cursor = System.Windows.Forms.Cursors.Hand
Me.Chao_Button1.Image = Nothing
Me.Chao_Button1.ImagePosition = "Left"
Me.Chao_Button1.Location = New System.Drawing.Point(99, 758)
Me.Chao_Button1.MinimumSize = New System.Drawing.Size(50, 50)
Me.Chao_Button1.Name = "Chao_Button1"
Me.Chao_Button1.Size = New System.Drawing.Size(119, 50)
Me.Chao_Button1.TabIndex = 98
Me.Chao_Button1.TextColor = System.Drawing.Color.White
'
'Chao_Button2
'
Me.Chao_Button2.AccessibleRole = Nothing
Me.Chao_Button2.Anchor = System.Windows.Forms.AnchorStyles.Bottom
Me.Chao_Button2.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.Chao_Button2.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.Chao_Button2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Chao_Button2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Chao_Button2.BorderColor = System.Drawing.Color.FromArgb(CType(CType(110, Byte), Integer), CType(CType(20, Byte), Integer), CType(CType(239, Byte), Integer))
Me.Chao_Button2.ButtonBackColor = System.Drawing.Color.White
Me.Chao_Button2.ButtonColor = System.Drawing.Color.FromArgb(CType(CType(25, Byte), Integer), CType(CType(117, Byte), Integer), CType(CType(200, Byte), Integer))
Me.Chao_Button2.ButtonFont = New System.Drawing.Font("微软雅黑", 12.0!)
Me.Chao_Button2.ButtonShape = "RoundedRectangle"
Me.Chao_Button2.ButtonText = "关闭"
Me.Chao_Button2.ButtonType = "ContainedButton"
Me.Chao_Button2.Cursor = System.Windows.Forms.Cursors.Hand
Me.Chao_Button2.Image = Nothing
Me.Chao_Button2.ImagePosition = "Left"
Me.Chao_Button2.Location = New System.Drawing.Point(316, 758)
Me.Chao_Button2.MinimumSize = New System.Drawing.Size(50, 50)
Me.Chao_Button2.Name = "Chao_Button2"
Me.Chao_Button2.Size = New System.Drawing.Size(132, 50)
Me.Chao_Button2.TabIndex = 99
Me.Chao_Button2.TextColor = System.Drawing.Color.White
'
'Button1
'
Me.Button1.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Button1.Location = New System.Drawing.Point(437, 70)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(101, 27)
Me.Button1.TabIndex = 100
Me.Button1.Text = "选择文件"
Me.Button1.UseVisualStyleBackColor = True
'
'OpenFileDialog1
'
Me.OpenFileDialog1.FileName = "OpenFileDialog1"
'
'TextBox11
'
Me.TextBox11.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.TextBox11.Location = New System.Drawing.Point(134, 72)
Me.TextBox11.Name = "TextBox11"
Me.TextBox11.ReadOnly = True
Me.TextBox11.Size = New System.Drawing.Size(297, 25)
Me.TextBox11.TabIndex = 101
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.BackColor = System.Drawing.Color.White
Me.Label1.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label1.Location = New System.Drawing.Point(28, 152)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(92, 27)
Me.Label1.TabIndex = 102
Me.Label1.Text = "文件大小"
'
'Label16
'
Me.Label16.AutoSize = True
Me.Label16.BackColor = System.Drawing.Color.White
Me.Label16.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label16.Location = New System.Drawing.Point(129, 152)
Me.Label16.Name = "Label16"
Me.Label16.Size = New System.Drawing.Size(24, 27)
Me.Label16.TabIndex = 103
Me.Label16.Text = "0"
'
'Chao_CheckBox1
'
Me.Chao_CheckBox1.AccessibleRole = Nothing
Me.Chao_CheckBox1.AutoScrollMargin = New System.Drawing.Size(0, 0)
Me.Chao_CheckBox1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
Me.Chao_CheckBox1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
Me.Chao_CheckBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Chao_CheckBox1.BorderColor = System.Drawing.Color.Black
Me.Chao_CheckBox1.BorderWidth = 2.0!
Me.Chao_CheckBox1.Checked = False
Me.Chao_CheckBox1.CheckedInBackColor = System.Drawing.Color.FromArgb(CType(CType(76, Byte), Integer), CType(CType(217, Byte), Integer), CType(CType(100, Byte), Integer))
Me.Chao_CheckBox1.CheckedInForeColor = System.Drawing.Color.White
Me.Chao_CheckBox1.CheckText = "覆盖原有信息"
Me.Chao_CheckBox1.CheckTextColor = System.Drawing.Color.Black
Me.Chao_CheckBox1.CheckTextFont = New System.Drawing.Font("微软雅黑", 12.0!)
Me.Chao_CheckBox1.Cursor = System.Windows.Forms.Cursors.Hand
Me.Chao_CheckBox1.Location = New System.Drawing.Point(133, 708)
Me.Chao_CheckBox1.Margin = New System.Windows.Forms.Padding(4)
Me.Chao_CheckBox1.MinimumSize = New System.Drawing.Size(20, 20)
Me.Chao_CheckBox1.Name = "Chao_CheckBox1"
Me.Chao_CheckBox1.Size = New System.Drawing.Size(184, 25)
Me.Chao_CheckBox1.TabIndex = 104
Me.Chao_CheckBox1.Visible = False
'
'Label17
'
Me.Label17.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.Label17.AutoSize = True
Me.Label17.BackColor = System.Drawing.Color.White
Me.Label17.Font = New System.Drawing.Font("微软雅黑", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(134, Byte))
Me.Label17.Location = New System.Drawing.Point(486, 338)
Me.Label17.Name = "Label17"
Me.Label17.Size = New System.Drawing.Size(52, 27)
Me.Label17.TabIndex = 105
Me.Label17.Text = "分钟"
'
'FormSingle
'
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None
Me.BackColor = System.Drawing.Color.White
Me.ClientSize = New System.Drawing.Size(550, 820)
Me.Controls.Add(Me.Label17)
Me.Controls.Add(Me.Chao_CheckBox1)
Me.Controls.Add(Me.Label16)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.TextBox11)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.Chao_Button2)
Me.Controls.Add(Me.Chao_Button1)
Me.Controls.Add(Me.ComboBox2)
Me.Controls.Add(Me.Label15)
Me.Controls.Add(Me.TextBox10)
Me.Controls.Add(Me.Label14)
Me.Controls.Add(Me.Label13)
Me.Controls.Add(Me.TextBox9)
Me.Controls.Add(Me.Label12)
Me.Controls.Add(Me.TextBox5)
Me.Controls.Add(Me.Label11)
Me.Controls.Add(Me.TextBox4)
Me.Controls.Add(Me.Label10)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.DateTimePicker1)
Me.Controls.Add(Me.ComboBox1)
Me.Controls.Add(Me.Label9)
Me.Controls.Add(Me.TextBox8)
Me.Controls.Add(Me.Label8)
Me.Controls.Add(Me.TextBox7)
Me.Controls.Add(Me.Label7)
Me.Controls.Add(Me.TextBox6)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.TextBox3)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.TextBox2)
Me.Controls.Add(Me.Label2)
Me.MinimumSize = New System.Drawing.Size(550, 820)
Me.Name = "FormSingle"
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.Text = "导入单个视频"
Me.Controls.SetChildIndex(Me.TitlePanel, 0)
Me.Controls.SetChildIndex(Me.Label2, 0)
Me.Controls.SetChildIndex(Me.TextBox2, 0)
Me.Controls.SetChildIndex(Me.Label3, 0)
Me.Controls.SetChildIndex(Me.TextBox3, 0)
Me.Controls.SetChildIndex(Me.Label4, 0)
Me.Controls.SetChildIndex(Me.Label5, 0)
Me.Controls.SetChildIndex(Me.Label6, 0)
Me.Controls.SetChildIndex(Me.TextBox6, 0)
Me.Controls.SetChildIndex(Me.Label7, 0)
Me.Controls.SetChildIndex(Me.TextBox7, 0)
Me.Controls.SetChildIndex(Me.Label8, 0)
Me.Controls.SetChildIndex(Me.TextBox8, 0)
Me.Controls.SetChildIndex(Me.Label9, 0)
Me.Controls.SetChildIndex(Me.ComboBox1, 0)
Me.Controls.SetChildIndex(Me.DateTimePicker1, 0)
Me.Controls.SetChildIndex(Me.TextBox1, 0)
Me.Controls.SetChildIndex(Me.Label10, 0)
Me.Controls.SetChildIndex(Me.TextBox4, 0)
Me.Controls.SetChildIndex(Me.Label11, 0)
Me.Controls.SetChildIndex(Me.TextBox5, 0)
Me.Controls.SetChildIndex(Me.Label12, 0)
Me.Controls.SetChildIndex(Me.TextBox9, 0)
Me.Controls.SetChildIndex(Me.Label13, 0)
Me.Controls.SetChildIndex(Me.Label14, 0)
Me.Controls.SetChildIndex(Me.TextBox10, 0)
Me.Controls.SetChildIndex(Me.Label15, 0)
Me.Controls.SetChildIndex(Me.ComboBox2, 0)
Me.Controls.SetChildIndex(Me.Chao_Button1, 0)
Me.Controls.SetChildIndex(Me.Chao_Button2, 0)
Me.Controls.SetChildIndex(Me.Button1, 0)
Me.Controls.SetChildIndex(Me.TextBox11, 0)
Me.Controls.SetChildIndex(Me.Label1, 0)
Me.Controls.SetChildIndex(Me.Label16, 0)
Me.Controls.SetChildIndex(Me.Chao_CheckBox1, 0)
Me.Controls.SetChildIndex(Me.Label17, 0)
CType(Me.FormIconPicB, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.SetPicB, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.TitlePicB, System.ComponentModel.ISupportInitialize).EndInit()
Me.TitlePanel.ResumeLayout(False)
Me.TitlePanel.PerformLayout()
CType(Me.SkinPicB, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label2 As Label
Friend WithEvents Label3 As Label
Friend WithEvents TextBox2 As TextBox
Friend WithEvents Label4 As Label
Friend WithEvents TextBox3 As TextBox
Friend WithEvents Label5 As Label
Friend WithEvents Label6 As Label
Friend WithEvents Label7 As Label
Friend WithEvents TextBox6 As TextBox
Friend WithEvents Label8 As Label
Friend WithEvents TextBox7 As TextBox
Friend WithEvents Label9 As Label
Friend WithEvents TextBox8 As TextBox
Friend WithEvents ComboBox1 As ComboBox
Friend WithEvents DateTimePicker1 As DateTimePicker
Friend WithEvents Label10 As Label
Friend WithEvents TextBox1 As TextBox
Friend WithEvents Label11 As Label
Friend WithEvents TextBox4 As TextBox
Friend WithEvents Label12 As Label
Friend WithEvents TextBox5 As TextBox
Friend WithEvents Label13 As Label
Friend WithEvents TextBox9 As TextBox
Friend WithEvents Label14 As Label
Friend WithEvents Label15 As Label
Friend WithEvents TextBox10 As TextBox
Friend WithEvents ComboBox2 As ComboBox
Friend WithEvents Chao_Button1 As ChaoControls.Chao_Button
Friend WithEvents Chao_Button2 As ChaoControls.Chao_Button
Friend WithEvents Button1 As Button
Friend WithEvents OpenFileDialog1 As OpenFileDialog
Friend WithEvents TextBox11 As TextBox
Friend WithEvents Label1 As Label
Friend WithEvents Label16 As Label
Friend WithEvents Chao_CheckBox1 As ChaoControls.Chao_CheckBox
Friend WithEvents Label17 As Label
End Class
|
{
"pile_set_name": "Github"
}
|
package cloudwatch
import (
"bufio"
"bytes"
"fmt"
"io"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
type RejectedLogEventsInfoError struct {
Info *cloudwatchlogs.RejectedLogEventsInfo
}
func (e *RejectedLogEventsInfoError) Error() string {
return fmt.Sprintf("log messages were rejected")
}
// Writer is an io.Writer implementation that writes lines to a cloudwatch logs
// stream.
type Writer struct {
group, stream, sequenceToken *string
client client
closed bool
err error
events eventsBuffer
throttle <-chan time.Time
sync.Mutex // This protects calls to flush.
}
func NewWriter(group, stream string, client *cloudwatchlogs.CloudWatchLogs) *Writer {
w := &Writer{
group: aws.String(group),
stream: aws.String(stream),
client: client,
throttle: time.Tick(writeThrottle),
}
go w.start() // start flushing
return w
}
// Write takes b, and creates cloudwatch log events for each individual line.
// If Flush returns an error, subsequent calls to Write will fail.
func (w *Writer) Write(b []byte) (int, error) {
if w.closed {
return 0, io.ErrClosedPipe
}
if w.err != nil {
return 0, w.err
}
return w.buffer(b)
}
// starts continously flushing the buffered events.
func (w *Writer) start() error {
for {
// Exit if the stream is closed.
if w.closed {
return nil
}
<-w.throttle
if err := w.Flush(); err != nil {
return err
}
}
}
// Closes the writer. Any subsequent calls to Write will return
// io.ErrClosedPipe.
func (w *Writer) Close() error {
w.closed = true
return w.Flush() // Flush remaining buffer.
}
// Flush flushes the events that are currently buffered.
func (w *Writer) Flush() error {
w.Lock()
defer w.Unlock()
events := w.events.drain()
// No events to flush.
if len(events) == 0 {
return nil
}
w.err = w.flush(events)
return w.err
}
// flush flashes a slice of log events. This method should be called
// sequentially to ensure that the sequence token is updated properly.
func (w *Writer) flush(events []*cloudwatchlogs.InputLogEvent) error {
resp, err := w.client.PutLogEvents(&cloudwatchlogs.PutLogEventsInput{
LogEvents: events,
LogGroupName: w.group,
LogStreamName: w.stream,
SequenceToken: w.sequenceToken,
})
if err != nil {
return err
}
if resp.RejectedLogEventsInfo != nil {
w.err = &RejectedLogEventsInfoError{Info: resp.RejectedLogEventsInfo}
return w.err
}
w.sequenceToken = resp.NextSequenceToken
return nil
}
// buffer splits up b into individual log events and inserts them into the
// buffer.
func (w *Writer) buffer(b []byte) (int, error) {
r := bufio.NewReader(bytes.NewReader(b))
var (
n int
eof bool
)
for !eof {
b, err := r.ReadBytes('\n')
if err != nil {
if err == io.EOF {
eof = true
} else {
break
}
}
if len(b) == 0 {
continue
}
w.events.add(&cloudwatchlogs.InputLogEvent{
Message: aws.String(string(b)),
Timestamp: aws.Int64(now().UnixNano() / 1000000),
})
n += len(b)
}
return n, nil
}
// eventsBuffer represents a buffer of cloudwatch events that are protected by a
// mutex.
type eventsBuffer struct {
sync.Mutex
events []*cloudwatchlogs.InputLogEvent
}
func (b *eventsBuffer) add(event *cloudwatchlogs.InputLogEvent) {
b.Lock()
defer b.Unlock()
b.events = append(b.events, event)
}
func (b *eventsBuffer) drain() []*cloudwatchlogs.InputLogEvent {
b.Lock()
defer b.Unlock()
events := b.events[:]
b.events = nil
return events
}
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright 2009-2016 Jörg Müller
*
* 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.
******************************************************************************/
#pragma once
/**
* @file Square.h
* @ingroup generator
* The Square class.
*/
#include "ISound.h"
#include "respec/Specification.h"
AUD_NAMESPACE_BEGIN
/**
* This sound creates a reader that plays a square tone.
*/
class AUD_API Square : public ISound
{
private:
/**
* The frequence of the square wave.
*/
const float m_frequency;
/**
* The target sample rate for output.
*/
const SampleRate m_sampleRate;
// delete copy constructor and operator=
Square(const Square&) = delete;
Square& operator=(const Square&) = delete;
public:
/**
* Creates a new square sound.
* \param frequency The desired frequency.
* \param sampleRate The target sample rate for playback.
*/
Square(float frequency,
SampleRate sampleRate = RATE_48000);
/**
* Returns the frequency of the square wave.
*/
float getFrequency() const;
virtual std::shared_ptr<IReader> createReader();
};
AUD_NAMESPACE_END
|
{
"pile_set_name": "Github"
}
|
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1040:5263#TTAGGC/1
---
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1040:5263#TTAGGC/2
---
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1043:19446#TTAGGC/1
---
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1043:19446#TTAGGC/2
---
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1045:16499#TTAGGC/1
---
SEQ_NAME: ILLUMINA-52179E_0004:2:1:1045:16499#TTAGGC/2
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2412:2210 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2412:2210 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2284:2226 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2284:2226 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2037:2173 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2037:2173 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:1958:2175 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:1958:2175 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2155:2169 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2155:2169 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2326:2175 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2326:2175 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2139:2216 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2139:2216 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2110:2236 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2110:2236 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2326:2150 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:2326:2150 2:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:1832:2218 1:N:0:TAGCTG
---
SEQ_NAME: HWI-ST575:107:C0HE6ACXX:5:1101:1832:2218 2:N:0:TAGCTG
---
|
{
"pile_set_name": "Github"
}
|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.MSHTMLApi
{
/// <summary>
/// DispatchInterface IHTMLDOMTextNode
/// SupportByVersion MSHTML, 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
[EntityType(EntityType.IsDispatchInterface), BaseType]
public class IHTMLDOMTextNode : DispHTMLDOMTextNode
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(IHTMLDOMTextNode);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public IHTMLDOMTextNode(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public IHTMLDOMTextNode(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public IHTMLDOMTextNode(string progId) : base(progId)
{
}
#endregion
#region Properties
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Google Analytics tracking pixel for the freely hosted version of Video.js
* at vjs.zencdn.net. We'll use this data to develop a support matrix of
* browsers and devices, and possibly track errors.
*
* This code generates the GA tracking URL without requiring the GA javascript
* library.
*
* @type {Image}
*/
;(function(i,w,n,e,l){
l=w.location;
// Setting the source of an image will load the URL even without adding to dom
// Using //www, still seems to work for https even though ssl.google is used by google
i.src='//www.google-analytics.com/__utm.gif'
// Version
+'?utmwv=5.4.2'
// ID
+'&utmac=UA-16505296-2'
// Sessions
// &utms=2
// Cache breaker (using utmcc to do this)
+'&utmn='+1
+'&utmhn='+e(l.hostname)
// Encoding
// &utmcs=UTF-8
+'&utmsr='+w.screen.availWidth+'x'+w.screen.availHeight
// Browser window
// &utmvp=1057x1105
// Color depth
// &utmsc=24-bit
+'&utmul='+(n.language||n.userLanguage||'').toLowerCase()
// Java
// &utmje=1
// Flash version
// &utmfl=11.7%20r700
// Page title
// &utmdt=HTML5%20Video%20Player%20%7C%20Video.js
// Adsense
// &utmhid=1112291628
// Referrer, '-' is none
// Using current page as referrer so stats show up cleaner than "Direct"
+'&utmr='+e(l.href)
+'&utmp='+e(l.hostname+l.pathname)
// Current time stamp
// &utmht=1370890439353
// ?
// &utmu=q
// Cookies! Manually setting visitor ID and setting everything else to 1
// Random number used as cache buster instead of utmn
+'&utmcc=__utma%3D1.'+Math.floor(Math.random()*1e10)+'.1.1.1.1%3B'
// Custom Var: vjsv is the variable name and 1.0.0 is the VJS version
+'&utme=8(vjsv)9(v0.0.0)'
;
})(new Image(),window,navigator,encodeURIComponent);
|
{
"pile_set_name": "Github"
}
|
*> \brief \b ZSTEIN
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download ZSTEIN + dependencies
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zstein.f">
*> [TGZ]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zstein.f">
*> [ZIP]</a>
*> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zstein.f">
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE ZSTEIN( N, D, E, M, W, IBLOCK, ISPLIT, Z, LDZ, WORK,
* IWORK, IFAIL, INFO )
*
* .. Scalar Arguments ..
* INTEGER INFO, LDZ, M, N
* ..
* .. Array Arguments ..
* INTEGER IBLOCK( * ), IFAIL( * ), ISPLIT( * ),
* $ IWORK( * )
* DOUBLE PRECISION D( * ), E( * ), W( * ), WORK( * )
* COMPLEX*16 Z( LDZ, * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> ZSTEIN computes the eigenvectors of a real symmetric tridiagonal
*> matrix T corresponding to specified eigenvalues, using inverse
*> iteration.
*>
*> The maximum number of iterations allowed for each eigenvector is
*> specified by an internal parameter MAXITS (currently set to 5).
*>
*> Although the eigenvectors are real, they are stored in a complex
*> array, which may be passed to ZUNMTR or ZUPMTR for back
*> transformation to the eigenvectors of a complex Hermitian matrix
*> which was reduced to tridiagonal form.
*>
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The order of the matrix. N >= 0.
*> \endverbatim
*>
*> \param[in] D
*> \verbatim
*> D is DOUBLE PRECISION array, dimension (N)
*> The n diagonal elements of the tridiagonal matrix T.
*> \endverbatim
*>
*> \param[in] E
*> \verbatim
*> E is DOUBLE PRECISION array, dimension (N-1)
*> The (n-1) subdiagonal elements of the tridiagonal matrix
*> T, stored in elements 1 to N-1.
*> \endverbatim
*>
*> \param[in] M
*> \verbatim
*> M is INTEGER
*> The number of eigenvectors to be found. 0 <= M <= N.
*> \endverbatim
*>
*> \param[in] W
*> \verbatim
*> W is DOUBLE PRECISION array, dimension (N)
*> The first M elements of W contain the eigenvalues for
*> which eigenvectors are to be computed. The eigenvalues
*> should be grouped by split-off block and ordered from
*> smallest to largest within the block. ( The output array
*> W from DSTEBZ with ORDER = 'B' is expected here. )
*> \endverbatim
*>
*> \param[in] IBLOCK
*> \verbatim
*> IBLOCK is INTEGER array, dimension (N)
*> The submatrix indices associated with the corresponding
*> eigenvalues in W; IBLOCK(i)=1 if eigenvalue W(i) belongs to
*> the first submatrix from the top, =2 if W(i) belongs to
*> the second submatrix, etc. ( The output array IBLOCK
*> from DSTEBZ is expected here. )
*> \endverbatim
*>
*> \param[in] ISPLIT
*> \verbatim
*> ISPLIT is INTEGER array, dimension (N)
*> The splitting points, at which T breaks up into submatrices.
*> The first submatrix consists of rows/columns 1 to
*> ISPLIT( 1 ), the second of rows/columns ISPLIT( 1 )+1
*> through ISPLIT( 2 ), etc.
*> ( The output array ISPLIT from DSTEBZ is expected here. )
*> \endverbatim
*>
*> \param[out] Z
*> \verbatim
*> Z is COMPLEX*16 array, dimension (LDZ, M)
*> The computed eigenvectors. The eigenvector associated
*> with the eigenvalue W(i) is stored in the i-th column of
*> Z. Any vector which fails to converge is set to its current
*> iterate after MAXITS iterations.
*> The imaginary parts of the eigenvectors are set to zero.
*> \endverbatim
*>
*> \param[in] LDZ
*> \verbatim
*> LDZ is INTEGER
*> The leading dimension of the array Z. LDZ >= max(1,N).
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*> WORK is DOUBLE PRECISION array, dimension (5*N)
*> \endverbatim
*>
*> \param[out] IWORK
*> \verbatim
*> IWORK is INTEGER array, dimension (N)
*> \endverbatim
*>
*> \param[out] IFAIL
*> \verbatim
*> IFAIL is INTEGER array, dimension (M)
*> On normal exit, all elements of IFAIL are zero.
*> If one or more eigenvectors fail to converge after
*> MAXITS iterations, then their indices are stored in
*> array IFAIL.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: successful exit
*> < 0: if INFO = -i, the i-th argument had an illegal value
*> > 0: if INFO = i, then i eigenvectors failed to converge
*> in MAXITS iterations. Their indices are stored in
*> array IFAIL.
*> \endverbatim
*
*> \par Internal Parameters:
* =========================
*>
*> \verbatim
*> MAXITS INTEGER, default = 5
*> The maximum number of iterations performed.
*>
*> EXTRA INTEGER, default = 2
*> The number of iterations performed after norm growth
*> criterion is satisfied, should be at least 1.
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date December 2016
*
*> \ingroup complex16OTHERcomputational
*
* =====================================================================
SUBROUTINE ZSTEIN( N, D, E, M, W, IBLOCK, ISPLIT, Z, LDZ, WORK,
$ IWORK, IFAIL, INFO )
*
* -- LAPACK computational routine (version 3.7.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* December 2016
*
* .. Scalar Arguments ..
INTEGER INFO, LDZ, M, N
* ..
* .. Array Arguments ..
INTEGER IBLOCK( * ), IFAIL( * ), ISPLIT( * ),
$ IWORK( * )
DOUBLE PRECISION D( * ), E( * ), W( * ), WORK( * )
COMPLEX*16 Z( LDZ, * )
* ..
*
* =====================================================================
*
* .. Parameters ..
COMPLEX*16 CZERO, CONE
PARAMETER ( CZERO = ( 0.0D+0, 0.0D+0 ),
$ CONE = ( 1.0D+0, 0.0D+0 ) )
DOUBLE PRECISION ZERO, ONE, TEN, ODM3, ODM1
PARAMETER ( ZERO = 0.0D+0, ONE = 1.0D+0, TEN = 1.0D+1,
$ ODM3 = 1.0D-3, ODM1 = 1.0D-1 )
INTEGER MAXITS, EXTRA
PARAMETER ( MAXITS = 5, EXTRA = 2 )
* ..
* .. Local Scalars ..
INTEGER B1, BLKSIZ, BN, GPIND, I, IINFO, INDRV1,
$ INDRV2, INDRV3, INDRV4, INDRV5, ITS, J, J1,
$ JBLK, JMAX, JR, NBLK, NRMCHK
DOUBLE PRECISION DTPCRT, EPS, EPS1, NRM, ONENRM, ORTOL, PERTOL,
$ SCL, SEP, TOL, XJ, XJM, ZTR
* ..
* .. Local Arrays ..
INTEGER ISEED( 4 )
* ..
* .. External Functions ..
INTEGER IDAMAX
DOUBLE PRECISION DLAMCH, DNRM2
EXTERNAL IDAMAX, DLAMCH, DNRM2
* ..
* .. External Subroutines ..
EXTERNAL DCOPY, DLAGTF, DLAGTS, DLARNV, DSCAL, XERBLA
* ..
* .. Intrinsic Functions ..
INTRINSIC ABS, DBLE, DCMPLX, MAX, SQRT
* ..
* .. Executable Statements ..
*
* Test the input parameters.
*
INFO = 0
DO 10 I = 1, M
IFAIL( I ) = 0
10 CONTINUE
*
IF( N.LT.0 ) THEN
INFO = -1
ELSE IF( M.LT.0 .OR. M.GT.N ) THEN
INFO = -4
ELSE IF( LDZ.LT.MAX( 1, N ) ) THEN
INFO = -9
ELSE
DO 20 J = 2, M
IF( IBLOCK( J ).LT.IBLOCK( J-1 ) ) THEN
INFO = -6
GO TO 30
END IF
IF( IBLOCK( J ).EQ.IBLOCK( J-1 ) .AND. W( J ).LT.W( J-1 ) )
$ THEN
INFO = -5
GO TO 30
END IF
20 CONTINUE
30 CONTINUE
END IF
*
IF( INFO.NE.0 ) THEN
CALL XERBLA( 'ZSTEIN', -INFO )
RETURN
END IF
*
* Quick return if possible
*
IF( N.EQ.0 .OR. M.EQ.0 ) THEN
RETURN
ELSE IF( N.EQ.1 ) THEN
Z( 1, 1 ) = CONE
RETURN
END IF
*
* Get machine constants.
*
EPS = DLAMCH( 'Precision' )
*
* Initialize seed for random number generator DLARNV.
*
DO 40 I = 1, 4
ISEED( I ) = 1
40 CONTINUE
*
* Initialize pointers.
*
INDRV1 = 0
INDRV2 = INDRV1 + N
INDRV3 = INDRV2 + N
INDRV4 = INDRV3 + N
INDRV5 = INDRV4 + N
*
* Compute eigenvectors of matrix blocks.
*
J1 = 1
DO 180 NBLK = 1, IBLOCK( M )
*
* Find starting and ending indices of block nblk.
*
IF( NBLK.EQ.1 ) THEN
B1 = 1
ELSE
B1 = ISPLIT( NBLK-1 ) + 1
END IF
BN = ISPLIT( NBLK )
BLKSIZ = BN - B1 + 1
IF( BLKSIZ.EQ.1 )
$ GO TO 60
GPIND = J1
*
* Compute reorthogonalization criterion and stopping criterion.
*
ONENRM = ABS( D( B1 ) ) + ABS( E( B1 ) )
ONENRM = MAX( ONENRM, ABS( D( BN ) )+ABS( E( BN-1 ) ) )
DO 50 I = B1 + 1, BN - 1
ONENRM = MAX( ONENRM, ABS( D( I ) )+ABS( E( I-1 ) )+
$ ABS( E( I ) ) )
50 CONTINUE
ORTOL = ODM3*ONENRM
*
DTPCRT = SQRT( ODM1 / BLKSIZ )
*
* Loop through eigenvalues of block nblk.
*
60 CONTINUE
JBLK = 0
DO 170 J = J1, M
IF( IBLOCK( J ).NE.NBLK ) THEN
J1 = J
GO TO 180
END IF
JBLK = JBLK + 1
XJ = W( J )
*
* Skip all the work if the block size is one.
*
IF( BLKSIZ.EQ.1 ) THEN
WORK( INDRV1+1 ) = ONE
GO TO 140
END IF
*
* If eigenvalues j and j-1 are too close, add a relatively
* small perturbation.
*
IF( JBLK.GT.1 ) THEN
EPS1 = ABS( EPS*XJ )
PERTOL = TEN*EPS1
SEP = XJ - XJM
IF( SEP.LT.PERTOL )
$ XJ = XJM + PERTOL
END IF
*
ITS = 0
NRMCHK = 0
*
* Get random starting vector.
*
CALL DLARNV( 2, ISEED, BLKSIZ, WORK( INDRV1+1 ) )
*
* Copy the matrix T so it won't be destroyed in factorization.
*
CALL DCOPY( BLKSIZ, D( B1 ), 1, WORK( INDRV4+1 ), 1 )
CALL DCOPY( BLKSIZ-1, E( B1 ), 1, WORK( INDRV2+2 ), 1 )
CALL DCOPY( BLKSIZ-1, E( B1 ), 1, WORK( INDRV3+1 ), 1 )
*
* Compute LU factors with partial pivoting ( PT = LU )
*
TOL = ZERO
CALL DLAGTF( BLKSIZ, WORK( INDRV4+1 ), XJ, WORK( INDRV2+2 ),
$ WORK( INDRV3+1 ), TOL, WORK( INDRV5+1 ), IWORK,
$ IINFO )
*
* Update iteration count.
*
70 CONTINUE
ITS = ITS + 1
IF( ITS.GT.MAXITS )
$ GO TO 120
*
* Normalize and scale the righthand side vector Pb.
*
JMAX = IDAMAX( BLKSIZ, WORK( INDRV1+1 ), 1 )
SCL = BLKSIZ*ONENRM*MAX( EPS,
$ ABS( WORK( INDRV4+BLKSIZ ) ) ) /
$ ABS( WORK( INDRV1+JMAX ) )
CALL DSCAL( BLKSIZ, SCL, WORK( INDRV1+1 ), 1 )
*
* Solve the system LU = Pb.
*
CALL DLAGTS( -1, BLKSIZ, WORK( INDRV4+1 ), WORK( INDRV2+2 ),
$ WORK( INDRV3+1 ), WORK( INDRV5+1 ), IWORK,
$ WORK( INDRV1+1 ), TOL, IINFO )
*
* Reorthogonalize by modified Gram-Schmidt if eigenvalues are
* close enough.
*
IF( JBLK.EQ.1 )
$ GO TO 110
IF( ABS( XJ-XJM ).GT.ORTOL )
$ GPIND = J
IF( GPIND.NE.J ) THEN
DO 100 I = GPIND, J - 1
ZTR = ZERO
DO 80 JR = 1, BLKSIZ
ZTR = ZTR + WORK( INDRV1+JR )*
$ DBLE( Z( B1-1+JR, I ) )
80 CONTINUE
DO 90 JR = 1, BLKSIZ
WORK( INDRV1+JR ) = WORK( INDRV1+JR ) -
$ ZTR*DBLE( Z( B1-1+JR, I ) )
90 CONTINUE
100 CONTINUE
END IF
*
* Check the infinity norm of the iterate.
*
110 CONTINUE
JMAX = IDAMAX( BLKSIZ, WORK( INDRV1+1 ), 1 )
NRM = ABS( WORK( INDRV1+JMAX ) )
*
* Continue for additional iterations after norm reaches
* stopping criterion.
*
IF( NRM.LT.DTPCRT )
$ GO TO 70
NRMCHK = NRMCHK + 1
IF( NRMCHK.LT.EXTRA+1 )
$ GO TO 70
*
GO TO 130
*
* If stopping criterion was not satisfied, update info and
* store eigenvector number in array ifail.
*
120 CONTINUE
INFO = INFO + 1
IFAIL( INFO ) = J
*
* Accept iterate as jth eigenvector.
*
130 CONTINUE
SCL = ONE / DNRM2( BLKSIZ, WORK( INDRV1+1 ), 1 )
JMAX = IDAMAX( BLKSIZ, WORK( INDRV1+1 ), 1 )
IF( WORK( INDRV1+JMAX ).LT.ZERO )
$ SCL = -SCL
CALL DSCAL( BLKSIZ, SCL, WORK( INDRV1+1 ), 1 )
140 CONTINUE
DO 150 I = 1, N
Z( I, J ) = CZERO
150 CONTINUE
DO 160 I = 1, BLKSIZ
Z( B1+I-1, J ) = DCMPLX( WORK( INDRV1+I ), ZERO )
160 CONTINUE
*
* Save the shift to check eigenvalue spacing at next
* iteration.
*
XJM = XJ
*
170 CONTINUE
180 CONTINUE
*
RETURN
*
* End of ZSTEIN
*
END
|
{
"pile_set_name": "Github"
}
|
http://24.media.tumblr.com/005ef71a8c720baef958916ebec7e677/tumblr_mo70r1AxEB1soidbso1_1280.jpg
http://25.media.tumblr.com/5ec60d2a9bb64b7695749d15893f1cf1/tumblr_mz3xs9eF4K1rb4iemo1_1280.jpg
http://25.media.tumblr.com/b8fbe7a81158c7e3800f0dff14a63f75/tumblr_mz3x5nQzJ51rb4iemo1_1280.jpg
http://31.media.tumblr.com/56a351d8738a754751ee7c2c06f3b69a/tumblr_mz3yjjb1Pm1rb4iemo1_1280.jpg
http://i.imgur.com/0lJaaaF.jpg
http://i.imgur.com/0OyWlNB.jpg
http://i.imgur.com/0qHy4uH.jpg
http://i.imgur.com/0rqcwKh.jpg
http://i.imgur.com/0rYzebQ.jpg
http://i.imgur.com/1gd247S.jpg
http://i.imgur.com/1iE0JJy.jpg
http://i.imgur.com/1NZyfRj.jpg
http://i.imgur.com/1XBjfhQ.jpg
http://i.imgur.com/23rVyDS.jpg
http://i.imgur.com/2hNFHHM.jpg
http://i.imgur.com/2m8dzAw.jpg
http://i.imgur.com/2TEbJjt.jpg
http://i.imgur.com/2UEZAJW.jpg
http://i.imgur.com/2x458zz.jpg
http://i.imgur.com/32YQ2dX.jpg
http://i.imgur.com/3AKSPh0.jpg
http://i.imgur.com/3oSKe80.jpg
http://i.imgur.com/3R2DaXG.jpg
http://i.imgur.com/3tG1q82.jpg
http://i.imgur.com/3v5T2pv.jpg
http://i.imgur.com/3Zemlmm.jpg
http://i.imgur.com/43po0UF.jpg
http://i.imgur.com/4aRkkxy.jpg
http://i.imgur.com/4AvUT07.jpg
http://i.imgur.com/4Clv7t7.jpg
http://i.imgur.com/4dULkBi.jpg
http://i.imgur.com/4dUpTu2.jpg
http://i.imgur.com/4exDYFx.jpg
http://i.imgur.com/4fJbLzG.jpg
http://i.imgur.com/4KPCDIC.jpg
http://i.imgur.com/4tCp9J7.jpg
http://i.imgur.com/4UkKVE8.jpg
http://i.imgur.com/4wjUhEU.jpg
http://i.imgur.com/5aGybk0.jpg
http://i.imgur.com/5GXxmeM.jpg
http://i.imgur.com/5kOCDC7.jpg
http://i.imgur.com/5LSklQt.jpg
http://i.imgur.com/5LtSaF4.jpg
http://i.imgur.com/5N7GkJp.jpg
http://i.imgur.com/5P2Gop4.jpg
http://i.imgur.com/5PvPT4w.jpg
http://i.imgur.com/5uts5YF.jpg
http://i.imgur.com/5yDh5HZ.jpg
http://i.imgur.com/6ok53Ki.jpg
http://i.imgur.com/6QecYOf.jpg
http://i.imgur.com/6ygMxtX.jpg
http://i.imgur.com/713RR2l.jpg
http://i.imgur.com/73YVv1G.jpg
http://i.imgur.com/74cuvzW.jpg
http://i.imgur.com/76XUMRf.jpg
http://i.imgur.com/7ah8C4Z.jpg
http://i.imgur.com/7B8AVo4.jpg
http://i.imgur.com/7Bo1U6U.jpg
http://i.imgur.com/7DWXiZb.jpg
http://i.imgur.com/7F3D2jK.jpg
http://i.imgur.com/7JrU1c9.jpg
http://i.imgur.com/7M7ei5q.jpg
http://i.imgur.com/7nWpX0n.jpg
http://i.imgur.com/7ujDqSg.jpg
http://i.imgur.com/87q3KuE.jpg
http://i.imgur.com/8iJlK4h.jpg
http://i.imgur.com/9CPv1Nf.jpg
http://i.imgur.com/9Qphi3B.jpg
http://i.imgur.com/9rGSCZf.jpg
http://i.imgur.com/9Zndtezh.jpg
http://i.imgur.com/A4Pc7XQ.jpg
http://i.imgur.com/aA9V5nT.jpg
http://i.imgur.com/aaBhhWA.jpg
http://i.imgur.com/aaIV2Op.jpg
http://i.imgur.com/aAzcpgi.jpg
http://i.imgur.com/abw9Bte.jpg
http://i.imgur.com/aJkPtp5.jpg
http://i.imgur.com/aKReyN8.jpg
http://i.imgur.com/akZxB3Z.jpg
http://i.imgur.com/Alj4axx.jpg
http://i.imgur.com/AofNYJKl.jpg
http://i.imgur.com/ARGFlmp.jpg
http://i.imgur.com/AtQCl0C.jpg
http://i.imgur.com/aTv8Ixu.jpg
http://i.imgur.com/Aur7zZX.jpg
http://i.imgur.com/aXgaWrs.jpg
http://i.imgur.com/aZrNUba.jpg
http://i.imgur.com/azU6TxP.jpg
http://i.imgur.com/B7k3qKN.jpg
http://i.imgur.com/bDQSrhr.jpg
http://i.imgur.com/bg75Pz0.jpg
http://i.imgur.com/BGSNpXE.jpg
http://i.imgur.com/BKWMl11.jpg
http://i.imgur.com/Bmlag6p.jpg
http://i.imgur.com/br2c4jC.jpg
http://i.imgur.com/BYDLD8b.jpg
http://i.imgur.com/bZ4APgK.jpg
http://i.imgur.com/BzQ66ey.jpg
http://i.imgur.com/C1Eqnw4.jpg
http://i.imgur.com/c1imYfL.jpg
http://i.imgur.com/c6x3TEv.jpg
http://i.imgur.com/Cb64N5E.jpg
http://i.imgur.com/CBL1LiR.jpg
http://i.imgur.com/cCQqzTd.jpg
http://i.imgur.com/Cg7xeTL.jpg
http://i.imgur.com/cgJGQe5.jpg
http://i.imgur.com/CjgTfj3.jpg
http://i.imgur.com/cKNVLWO.jpg
http://i.imgur.com/cL6bfS1.jpg
http://i.imgur.com/cMT9UoV.jpg
http://i.imgur.com/cnlCDs3.jpg
http://i.imgur.com/cQEhHTT.jpg
http://i.imgur.com/csiy8zE.jpg
http://i.imgur.com/csQ02GO.jpg
http://i.imgur.com/cSsobaN.jpg
http://i.imgur.com/cUGHvg2.jpg
http://i.imgur.com/CuvMqR2.jpg
http://i.imgur.com/czaochu.jpg
http://i.imgur.com/D0JvICX.jpg
http://i.imgur.com/D1X2Agf.jpg
http://i.imgur.com/D2gQ6gq.jpg
http://i.imgur.com/d2r0rAC.jpg
http://i.imgur.com/D3YYcNb.jpg
http://i.imgur.com/d44UAgw.jpg
http://i.imgur.com/d49fFm8.jpg
http://i.imgur.com/d4UtWZp.jpg
http://i.imgur.com/d4WDkLC.jpg
http://i.imgur.com/DA2EaDm.jpg
http://i.imgur.com/Df2Qmh0.jpg
http://i.imgur.com/DgAe0bW.jpg
http://i.imgur.com/dH7owB6.jpg
http://i.imgur.com/dJsOw9L.jpg
http://i.imgur.com/dkBFiz1.jpg
http://i.imgur.com/dR4a8cE.jpg
http://i.imgur.com/dRriEKy.jpg
http://i.imgur.com/DtuftqZ.jpg
http://i.imgur.com/dU6H9hG.jpg
http://i.imgur.com/DZyVmMz.jpg
http://i.imgur.com/E0fqU8m.jpg
http://i.imgur.com/E2ibO4K.jpg
http://i.imgur.com/e2YXaIs.jpg
http://i.imgur.com/E5o8hi7.jpg
http://i.imgur.com/E9DDspt.jpg
http://i.imgur.com/E9Eljn3.jpg
http://i.imgur.com/eavmwWr.jpg
http://i.imgur.com/eBkCuBX.jpg
http://i.imgur.com/EC0cZdl.jpg
http://i.imgur.com/Ec7QpNJ.jpg
http://i.imgur.com/eeQoab9.jpg
http://i.imgur.com/EJwRi7N.jpg
http://i.imgur.com/EltBIuK.jpg
http://i.imgur.com/eMRh0rt.jpg
http://i.imgur.com/ePIYAbl.jpg
http://i.imgur.com/EpjmMFl.jpg
http://i.imgur.com/EugpFTA.jpg
http://i.imgur.com/euQUd8E.jpg
http://i.imgur.com/ev5uiao.jpg
http://i.imgur.com/EWn53FD.jpg
http://i.imgur.com/eWrXd8V.jpg
http://i.imgur.com/ex6Ul78.jpg
http://i.imgur.com/eXhGIO9.jpg
http://i.imgur.com/F3aeUEQ.jpg
http://i.imgur.com/F4RKTgA.jpg
http://i.imgur.com/F6e1MYZ.jpg
http://i.imgur.com/fAnBt4S.jpg
http://i.imgur.com/fhOMnHT.jpg
http://i.imgur.com/fHxO7rC.jpg
http://i.imgur.com/FID20YK.jpg
http://i.imgur.com/fjeZkFX.jpg
http://i.imgur.com/FJnlov2.jpg
http://i.imgur.com/FRFs5eG.jpg
http://i.imgur.com/FRhUjdy.jpg
http://i.imgur.com/fSQtBMw.jpg
http://i.imgur.com/fvi9BA5.jpg
http://i.imgur.com/fvufQEf.jpg
http://i.imgur.com/FXlJEns.jpg
http://i.imgur.com/g0tkv0Y.jpg
http://i.imgur.com/g54cB36.jpg
http://i.imgur.com/g5l7ZgQ.jpg
http://i.imgur.com/g6usFGM.jpg
http://i.imgur.com/g72XRTU.jpg
http://i.imgur.com/G75TLJN.jpg
http://i.imgur.com/gaPcX0D.jpg
http://i.imgur.com/gckd9O7.jpg
http://i.imgur.com/gcMEmR7.jpg
http://i.imgur.com/GcOIM5i.jpg
http://i.imgur.com/glsDJIh.jpg
http://i.imgur.com/gPGbwuX.jpg
http://i.imgur.com/gqIZmzB.jpg
http://i.imgur.com/GQs1tEl.jpg
http://i.imgur.com/gUMOBGz.jpg
http://i.imgur.com/guoYb9u.jpg
http://i.imgur.com/GWTj5Vm.jpg
http://i.imgur.com/GxKMwfY.jpg
http://i.imgur.com/H1I8Cq5.jpg
http://i.imgur.com/h2RskHF.jpg
http://i.imgur.com/H44EfMC.jpg
http://i.imgur.com/H6w1hGe.jpg
http://i.imgur.com/h6w4xxR.jpg
http://i.imgur.com/hblxIsS.jpg
http://i.imgur.com/HbXgPuP.jpg
http://i.imgur.com/hDtCTZi.jpg
http://i.imgur.com/HE1fvkW.jpg
http://i.imgur.com/HFSmwyq.jpg
http://i.imgur.com/hJKTyW6.jpg
http://i.imgur.com/hK7VqTT.jpg
http://i.imgur.com/HkWyaWY.jpg
http://i.imgur.com/hmEx4a3.jpg
http://i.imgur.com/HMlTbqn.jpg
http://i.imgur.com/HNZ3LXk.jpg
http://i.imgur.com/hqDEZZq.jpg
http://i.imgur.com/HtRg5GZ.jpg
http://i.imgur.com/Hv218Vf.jpg
http://i.imgur.com/hwsNB80.jpg
http://i.imgur.com/I37TnFq.jpg
http://i.imgur.com/i4oQUlS.jpg
http://i.imgur.com/I6L39.jpg
http://i.imgur.com/IF6aKPn.jpg
http://i.imgur.com/IFJSb5U.jpg
http://i.imgur.com/IGHJgfD.jpg
http://i.imgur.com/IGrrO9N.jpg
http://i.imgur.com/IL04r1m.jpg
http://i.imgur.com/Ilf8S21.jpg
http://i.imgur.com/imL4cXt.jpg
http://i.imgur.com/ImWpF3X.jpg
http://i.imgur.com/IScunfJ.jpg
http://i.imgur.com/itAdWfu.jpg
http://i.imgur.com/itfOWHH.jpg
http://i.imgur.com/IWIYxFf.jpg
http://i.imgur.com/j05AaUI.jpg
http://i.imgur.com/J0I4AQS.jpg
http://i.imgur.com/J6qDgIk.jpg
http://i.imgur.com/J74nMFg.jpg
http://i.imgur.com/j9qZuF7.jpg
http://i.imgur.com/jaaxT8b.jpg
http://i.imgur.com/JcCkqte.jpg
http://i.imgur.com/JeMtzhk.jpg
http://i.imgur.com/jfYsuHS.jpg
http://i.imgur.com/jjr45n6.jpg
http://i.imgur.com/jknBypP.jpg
http://i.imgur.com/jLzCgye.jpg
http://i.imgur.com/jmMuJZ5.jpg
http://i.imgur.com/jnCejXc.jpg
http://i.imgur.com/jogWVCw.jpg
http://i.imgur.com/joiJX4B.jpg
http://i.imgur.com/JpXtnrI.jpg
http://i.imgur.com/JQVqAAs.jpg
http://i.imgur.com/JsTUpH1.jpg
http://i.imgur.com/JUeIjLR.jpg
http://i.imgur.com/JViiNth.jpg
http://i.imgur.com/jY8LMjI.jpg
http://i.imgur.com/jzdhATC.jpg
http://i.imgur.com/JzQhvHu.jpg
http://i.imgur.com/k31NVht.jpg
http://i.imgur.com/kcwrYtp.jpg
http://i.imgur.com/kdu28xm.jpg
http://i.imgur.com/KE7kx21.jpg
http://i.imgur.com/kEkb9FC.jpg
http://i.imgur.com/kFz7RER.jpg
http://i.imgur.com/khHxOlb.jpg
http://i.imgur.com/kkSG5qG.jpg
http://i.imgur.com/klEi0cf.jpg
http://i.imgur.com/KMPGYKH.jpg
http://i.imgur.com/KODJOh5.jpg
http://i.imgur.com/KpUAWlP.jpg
http://i.imgur.com/KqtMAXB.jpg
http://i.imgur.com/KSoJxXh.jpg
http://i.imgur.com/kTjQaxp.jpg
http://i.imgur.com/KuPx6Y0.jpg
http://i.imgur.com/kzsm11j.jpg
http://i.imgur.com/kztgJq5.jpg
http://i.imgur.com/l0GtW2S.jpg
http://i.imgur.com/l3nYf0z.jpg
http://i.imgur.com/lGZPhWz.jpg
http://i.imgur.com/LIY1gZr.jpg
http://i.imgur.com/LJnC1AS.jpg
http://i.imgur.com/lLbuHRH.jpg
http://i.imgur.com/lLjj3X4.jpg
http://i.imgur.com/lrU0sqJ.jpg
http://i.imgur.com/LRYBVE1.jpg
http://i.imgur.com/LVuoiP4.jpg
http://i.imgur.com/m0cwtEB.jpg
http://i.imgur.com/m5w5BgB.jpg
http://i.imgur.com/m9PViy0.jpg
http://i.imgur.com/MdAjXGm.jpg
http://i.imgur.com/mDqKOK1.jpg
http://i.imgur.com/Mi2BuVa.jpg
http://i.imgur.com/mNNmUp7.jpg
http://i.imgur.com/mpiaKxG.jpg
http://i.imgur.com/MQiekCR.jpg
http://i.imgur.com/MUCTXvD.jpg
http://i.imgur.com/mUZ9FC0.jpg
http://i.imgur.com/MuZyRQ5.jpg
http://i.imgur.com/mVBKi4p.jpg
http://i.imgur.com/mYvI5U2.jpg
http://i.imgur.com/MZ0t30U.jpg
http://i.imgur.com/mzNMvH3.jpg
http://i.imgur.com/N52c5rx.jpg
http://i.imgur.com/NaVHYis.jpg
http://i.imgur.com/NcDlyAR.jpg
http://i.imgur.com/NCJXWsbl.jpg
http://i.imgur.com/Ncy3umL.jpg
http://i.imgur.com/NgAu4sM.jpg
http://i.imgur.com/nisGX6g.jpg
http://i.imgur.com/Np0N4tv.jpg
http://i.imgur.com/nQGrW7A.jpg
http://i.imgur.com/nQXZS9U.jpg
http://i.imgur.com/nRCbZio.jpg
http://i.imgur.com/NuQPrSt.jpg
http://i.imgur.com/Nx1jfLV.jpg
http://i.imgur.com/o54NLnI.jpg
http://i.imgur.com/O8v3Jnw.jpg
http://i.imgur.com/oFyCROe.jpg
http://i.imgur.com/ok2gqm8.jpg
http://i.imgur.com/OKlZwzb.jpg
http://i.imgur.com/oOMcEGj.jpg
http://i.imgur.com/osLdUS8.jpg
http://i.imgur.com/OsWaLpx.jpg
http://i.imgur.com/oV15QZA.jpg
http://i.imgur.com/OXqkWLU.jpg
http://i.imgur.com/pffxgGL.jpg
http://i.imgur.com/Pg9grWB.jpg
http://i.imgur.com/PiEMiKL.jpg
http://i.imgur.com/PIwRI1Z.jpg
http://i.imgur.com/pLBgjO3.jpg
http://i.imgur.com/pQx59n3.jpg
http://i.imgur.com/PR7Co9N.jpg
http://i.imgur.com/pSfC0b2.jpg
http://i.imgur.com/pT08Sr3.jpg
http://i.imgur.com/PVk4kbw.jpg
http://i.imgur.com/Px51YJ2.jpg
http://i.imgur.com/Pyh1CSB.jpg
http://i.imgur.com/PYqgQIW.jpg
http://i.imgur.com/pYXk5Da.jpg
http://i.imgur.com/pz1oRyp.jpg
http://i.imgur.com/PzzL4Xe.jpg
http://i.imgur.com/Q7G6oKa.jpg
http://i.imgur.com/q7VtlyF.jpg
http://i.imgur.com/qBzToGH.jpg
http://i.imgur.com/Qcg6DSW.jpg
http://i.imgur.com/qcr12dj.jpg
http://i.imgur.com/qepypXe.jpg
http://i.imgur.com/qf6e22D.jpg
http://i.imgur.com/QFrgVCT.jpg
http://i.imgur.com/QgJA1Fm.jpg
http://i.imgur.com/QhDMQl8.jpg
http://i.imgur.com/QkLYNso.jpg
http://i.imgur.com/ql79ynE.jpg
http://i.imgur.com/QmIKKPh.jpg
http://i.imgur.com/qO5hhro.jpg
http://i.imgur.com/qSw4JPv.jpg
http://i.imgur.com/Qv76Lan.jpg
http://i.imgur.com/qyDiUdA.jpg
http://i.imgur.com/QZyYX0i.jpg
http://i.imgur.com/R7eEyXS.jpg
http://i.imgur.com/R7p2dz5.jpg
http://i.imgur.com/r8efqfG.jpg
http://i.imgur.com/rBaAo3l.jpg
http://i.imgur.com/Rc2XUYK.jpg?1
http://i.imgur.com/rDKzUjM.jpg
http://i.imgur.com/RFhx2g7.jpg
http://i.imgur.com/rmybcx6.jpg
http://i.imgur.com/RRAh03r.jpg
http://i.imgur.com/RuQNwM0.jpg
http://i.imgur.com/rV2kehS.jpg
http://i.imgur.com/rwmvBPi.jpg
http://i.imgur.com/S1gkEro.jpg
http://i.imgur.com/s3wrEBF.jpg
http://i.imgur.com/S4fxfTc.jpg
http://i.imgur.com/s6GU72l.jpg
http://i.imgur.com/sfBb994.jpg
http://i.imgur.com/shDOeb5.jpg
http://i.imgur.com/sIcvljU.jpg
http://i.imgur.com/SkDRZmt.jpg
http://i.imgur.com/sKG3l1T.jpg
http://i.imgur.com/SKhTmwN.jpg
http://i.imgur.com/SLVs6Jp.jpg
http://i.imgur.com/SPmiLt2.jpg
http://i.imgur.com/sQeWMOO.jpg
http://i.imgur.com/Sty3o5P.jpg
http://i.imgur.com/SuZ7H96.jpg
http://i.imgur.com/sWPBXF5.jpg
http://i.imgur.com/sXLPMoj.jpg
http://i.imgur.com/sys1W8o.jpg
http://i.imgur.com/t0JSD59.jpg
http://i.imgur.com/T0WxDzL.jpg
http://i.imgur.com/TAQQVGL.jpg
http://i.imgur.com/Tb36dAY.jpg
http://i.imgur.com/tDsDD83.jpg
http://i.imgur.com/TF0f4Th.jpg
http://i.imgur.com/TfaDxmK.jpg
http://i.imgur.com/tGOss5R.jpg
http://i.imgur.com/tjhkEr1.jpg
http://i.imgur.com/tJHNpVX.jpg
http://i.imgur.com/TjMJZS2.jpg
http://i.imgur.com/tlqwCOi.jpg
http://i.imgur.com/tnJy1w7.jpg
http://i.imgur.com/tob21Hb.jpg
http://i.imgur.com/tp2oMmV.jpg
http://i.imgur.com/TsRFy1i.jpg
http://i.imgur.com/ttDS9kO.jpg
http://i.imgur.com/tyiOzVJ.jpg
http://i.imgur.com/U0yaAVU.jpg
http://i.imgur.com/U3kId86.jpg
http://i.imgur.com/u3RTmmb.jpg
http://i.imgur.com/U5ZfNF2.jpg
http://i.imgur.com/u90HAuz.jpg
http://i.imgur.com/uA4JUF4.jpg
http://i.imgur.com/UBnkDtU.jpg
http://i.imgur.com/ueOb1JP.jpg
http://i.imgur.com/uGcCUlF.jpg
http://i.imgur.com/UhhY70f.jpg
http://i.imgur.com/UIYMuXP.jpg
http://i.imgur.com/ujcxP8w.jpg
http://i.imgur.com/ULYNjZM.jpg
http://i.imgur.com/UoRY5bS.jpg
http://i.imgur.com/Ur8mfN3.jpg
http://i.imgur.com/UsgkiGS.jpg
http://i.imgur.com/usXQfoc.jpg
http://i.imgur.com/UUC6y8p.jpg
http://i.imgur.com/uWP9JZP.jpg
http://i.imgur.com/uY99VwS.jpg
http://i.imgur.com/v1dSaaw.jpg
http://i.imgur.com/V48CieV.jpg
http://i.imgur.com/v4CNunB.jpg
http://i.imgur.com/v6ozMQH.jpg
http://i.imgur.com/vbJepRK.jpg
http://i.imgur.com/VCjePQH.jpg
http://i.imgur.com/VcQ3OoQ.jpg
http://i.imgur.com/vIlL16U.jpg
http://i.imgur.com/vIyfelD.jpg
http://i.imgur.com/vJcEa2R.jpg
http://i.imgur.com/vjf1aBph.jpg
http://i.imgur.com/vJgd74s.jpg
http://i.imgur.com/vjSTmPS.jpg
http://i.imgur.com/vkmtqpg.jpg
http://i.imgur.com/vlWT6Ig.jpg
http://i.imgur.com/Vm29T7d.jpg
http://i.imgur.com/VrBB4cu.jpg
http://i.imgur.com/vrnWOl6.jpg
http://i.imgur.com/VU53g97.jpg
http://i.imgur.com/VxFWafc.jpg
http://i.imgur.com/Vz1ijny.jpg
http://i.imgur.com/VzDH7qu.jpg
http://i.imgur.com/W4ijSzN.jpg
http://i.imgur.com/W8dNfeF.jpg
http://i.imgur.com/WAPeulS.jpg
http://i.imgur.com/wawze22.jpg
http://i.imgur.com/wg1vORH.jpg
http://i.imgur.com/wkPUG2u.jpg
http://i.imgur.com/wNf1dGH.jpg
http://i.imgur.com/wwN5szh.jpg
http://i.imgur.com/X23jTdD.jpg
http://i.imgur.com/xaWK8eX.jpg
http://i.imgur.com/xB8gTrp.jpg
http://i.imgur.com/xE17I5i.jpg
http://i.imgur.com/xJMqwjk.jpg
http://i.imgur.com/XNsMhoc.jpg
http://i.imgur.com/XNUpFWN.jpg
http://i.imgur.com/XOJmzUf.jpg
http://i.imgur.com/xPv3lLm.jpg
http://i.imgur.com/XT5IU9q.jpg
http://i.imgur.com/xUSNHAn.jpg
http://i.imgur.com/XVC8yGI.jpg
http://i.imgur.com/xxJsNnL.jpg
http://i.imgur.com/xXkSOhy.jpg
http://i.imgur.com/XYTbIz5.jpg
http://i.imgur.com/Y6sHmwn.jpg
http://i.imgur.com/yc62Qro.jpg
http://i.imgur.com/YcWkhk2.jpg
http://i.imgur.com/yEJHO1Z.jpg
http://i.imgur.com/yglrEgH.jpg
http://i.imgur.com/yJkfsIV.jpg
http://i.imgur.com/ykFvZRw.jpg
http://i.imgur.com/Yl1EfKe.jpg
http://i.imgur.com/YnkcPPI.jpg
http://i.imgur.com/YOTznFc.jpg
http://i.imgur.com/ypHu0JX.jpg
http://i.imgur.com/yq894w9.jpg
http://i.imgur.com/yqZx3IT.jpg
http://i.imgur.com/yRmeH5w.jpg
http://i.imgur.com/YSMAASa.jpg
http://i.imgur.com/YueScwS.jpg
http://i.imgur.com/Yukj5Yl.jpg
http://i.imgur.com/YuvkvVu.jpg
http://i.imgur.com/yVykjC7.jpg
http://i.imgur.com/yxIWsQl.jpg
http://i.imgur.com/YzFxBsm.jpg
http://i.imgur.com/Z3ZY3Mr.jpg
http://i.imgur.com/Z5HSwrC.jpg
http://i.imgur.com/Z743HUf.jpg
http://i.imgur.com/zCNebrE.jpg
http://i.imgur.com/ZFriSPz.jpg
http://i.imgur.com/ZFVLT8r.jpg
http://i.imgur.com/ZgiPEL7.jpg
http://i.imgur.com/ZGUS7Bs.jpg
http://i.imgur.com/ZJeAFSz.jpg
http://i.imgur.com/ZKHTTyk.jpg
http://i.imgur.com/ZQ6Mxfj.jpg
http://i.imgur.com/ZR0pPo5.jpg
http://i.imgur.com/zsaETbF.jpg
http://i.imgur.com/Zsd4WVs.jpg
http://i.imgur.com/ZvXWqiu.jpg
http://i.imgur.com/zX9kFKv.jpg?1
http://i.imgur.com/Zy4kRFz.jpg
http://i.imgur.com/zY9f8QK.jpg
http://i.imgur.com/zYR2xFP.jpg
http://i.imgur.com/ZZjrlHd.jpg
http://img.imagefapusercontent.com/images/full/52/803/803473906.jpg
http://imgur.com/8TuGyCo.jpg
http://imgur.com/A831uia.jpg
http://imgur.com/aiz9x.jpg
http://imgur.com/ETuNIkh.jpg
http://imgur.com/F76i6jv.jpg
http://imgur.com/GNaUwLk.jpg
http://imgur.com/iMI7eaY.jpg
http://imgur.com/MyDvqoP.jpg
http://imgur.com/NMARwrY.jpg
http://imgur.com/NVCzXnk.jpg
http://imgur.com/RcmtGzU.jpg
http://imgur.com/uq9b8hP.jpg
http://imgur.com/WnykbGx.jpg
http://imgur.com/XEnYhTZ.jpg
http://imgur.com/Xgb0gK6.jpg
http://imgur.com/zUPP9ew.jpg
https://41.media.tumblr.com/69606c71ea2ba2fbbf15d188576a441d/tumblr_o4qk708QMr1qij4o1o1_1280.jpg
https://66.media.tumblr.com/c753fdc08cb597f077ee5d97a01ddca5/tumblr_oeu8ooKYzf1sjl3wio1_540.jpg
https://67.media.tumblr.com/56fbef43ccb9e419c81e77c96aedfac1/tumblr_oa0jn2kEiS1rb4iemo1_540.jpg
https://78.media.tumblr.com/097b4a77877de8a2ec82ccad78629a7d/tumblr_p1ajr8bw2h1uotrqno1_1280.jpg
https://78.media.tumblr.com/133f357f14a9a7c66b0ca18c24fd1e30/tumblr_p1rekwVhil1uotrqno1_1280.jpg
https://78.media.tumblr.com/35e1f6969e31e4255e5a3049455d197e/tumblr_p6y6wzb0PB1uotrqno1_1280.jpg
https://78.media.tumblr.com/3cc7f9e1e92700bb64c6ac24da09c3bb/tumblr_pa8rm6ot5V1uotrqno1_1280.jpg
https://78.media.tumblr.com/468e25efec019c84d63c3e39083b6819/tumblr_p9f1seEhO91uotrqno1_1280.jpg
https://78.media.tumblr.com/478b16d96eec6135fd7e0e7d75285618/tumblr_p5k6jg0bih1uotrqno1_1280.jpg
https://78.media.tumblr.com/53c2d7bd12a2f87ddffd5fd7cbd0d80e/tumblr_pcojsoOyef1vnc3k2o1_1280.jpg
https://78.media.tumblr.com/8b79ceaef5a420ff2aad6075a81248b9/tumblr_p6sna9iKsx1uotrqno1_1280.jpg
https://78.media.tumblr.com/8c1f88b4daa05539fed32b38fd507251/tumblr_p9vqk9x50e1uotrqno1_1280.jpg
https://78.media.tumblr.com/adb82fae4c977c49a744859d99a6bc10/tumblr_pc733wv8cq1uotrqno1_1280.jpg
https://78.media.tumblr.com/afa2c70dabf3d915c5718e51e0b217ea/tumblr_pceoezu1oF1uotrqno1_1280.jpg
https://78.media.tumblr.com/b064a42d939e585f1f6db4444b461b63/tumblr_p9bdaktbn71uotrqno1_1280.jpg
https://78.media.tumblr.com/b6ee80e45f29644b3af36fcc6a42e4ee/tumblr_p4u5gqqk3V1uotrqno1_1280.jpg
https://78.media.tumblr.com/bdd5b4fec1143a8f2d164dc82c3b2379/tumblr_p6spnvpMeV1uotrqno1_1280.jpg
https://78.media.tumblr.com/cf22a55a417d8addcd05b9aa83d0e503/tumblr_p0ogh6zD5V1uotrqno1_1280.jpg
https://78.media.tumblr.com/d68031c8d2bd7dc343042c90902f9c0e/tumblr_ootce7wewl1vs0o3bo1_1280.jpg
https://i.imgur.com/03mqRdB.jpg
https://i.imgur.com/046zdQr.jpg
https://i.imgur.com/05ePBsH.jpg
https://i.imgur.com/05WqeSN.jpg
https://i.imgur.com/0by2RDo.jpg
https://i.imgur.com/0hSjMOe.jpg
https://i.imgur.com/0Im6qVr.jpg
https://i.imgur.com/0nadZAa.jpg
https://i.imgur.com/0QjPBWV.jpg
https://i.imgur.com/0rzBUVd.jpg
https://i.imgur.com/0SdjPs7.jpg
https://i.imgur.com/0shQxGn.jpg
https://i.imgur.com/0U3TQtS.jpg
https://i.imgur.com/0xmxqk4.jpg
https://i.imgur.com/0YHq1Hu.jpg
https://i.imgur.com/0zjHI3W.jpg
https://i.imgur.com/10VNfzP.jpg
https://i.imgur.com/1BXx8uZ.jpg
https://i.imgur.com/1dX7KWi.jpg
https://i.imgur.com/1fjqsYf.jpg
https://i.imgur.com/1GiiC5v.jpg
https://i.imgur.com/1MYf3gQ.jpg
https://i.imgur.com/1nSHczI.jpg
https://i.imgur.com/1pwFgj2.jpg
https://i.imgur.com/1slspTs.jpg
https://i.imgur.com/25uT9FO.jpg
https://i.imgur.com/26ysP9v.jpg
https://i.imgur.com/28SSHm7.jpg
https://i.imgur.com/2DeeTcz.jpg
https://i.imgur.com/2O7YRHh.jpg
https://i.imgur.com/2sDbxnC.jpg
https://i.imgur.com/3BZzUdW.jpg
https://i.imgur.com/3HCNQJi.jpg
https://i.imgur.com/3itq05T.jpg
https://i.imgur.com/3lI6cvb.jpg
https://i.imgur.com/3LnZMgf.jpg
https://i.imgur.com/3SGFZu6.jpg
https://i.imgur.com/3vbCpKW.jpg
https://i.imgur.com/44hxnqX.jpg
https://i.imgur.com/46Jmmko.jpg
https://i.imgur.com/4AK9Cyn.jpg
https://i.imgur.com/4CUJ3zD.jpg
https://i.imgur.com/4e0kM6C.jpg
https://i.imgur.com/4Hymtpn.jpg
https://i.imgur.com/4iCLX3Q.jpg
https://i.imgur.com/4jorutp.jpg
https://i.imgur.com/4P0ONKF.jpg
https://i.imgur.com/4qks1Ws.jpg
https://i.imgur.com/4tb5IMs.jpg
https://i.imgur.com/4X3eGvi.jpg
https://i.imgur.com/5hMPv7A.jpg
https://i.imgur.com/5jS9AvU.jpg
https://i.imgur.com/5kiYRJe.jpg
https://i.imgur.com/5nmVfoe.jpg
https://i.imgur.com/5s8K7uK.jpg
https://i.imgur.com/5sDEUFB.jpg
https://i.imgur.com/5SnEe3x.jpg
https://i.imgur.com/5V0hZry.jpg
https://i.imgur.com/5vNIGw2.jpg
https://i.imgur.com/5W0vKq7.jpg
https://i.imgur.com/5WjndHJ.jpg
https://i.imgur.com/61qGUHA.jpg
https://i.imgur.com/64Eo1MC.jpg
https://i.imgur.com/6ADG2an.jpg
https://i.imgur.com/6JoxXkA.jpg
https://i.imgur.com/6jUCGhL.jpg
https://i.imgur.com/6Nf0TId.jpg
https://i.imgur.com/6o69dJ0.jpg
https://i.imgur.com/6TwV2xR.jpg
https://i.imgur.com/6VfiPvr.jpg
https://i.imgur.com/6vhBeQt.jpg
https://i.imgur.com/6YXqhlN.jpg
https://i.imgur.com/6ZggJ3U.jpg
https://i.imgur.com/6zOYrCf.jpg
https://i.imgur.com/74OTzlQ.jpg
https://i.imgur.com/77Li3i2.jpg
https://i.imgur.com/7DsAFXc.jpg
https://i.imgur.com/7eXHBba.jpg
https://i.imgur.com/7jLhyoX.jpg
https://i.imgur.com/7jWVoaW.jpg
https://i.imgur.com/7MFIqZ6.jpg
https://i.imgur.com/7MY4EVW.jpg
https://i.imgur.com/7PuSbkF.jpg
https://i.imgur.com/7SC91Fu.jpg
https://i.imgur.com/7u8avmQ.jpg
https://i.imgur.com/7v5qtHe.jpg
https://i.imgur.com/7vczJLi.jpg
https://i.imgur.com/7YCBmhl.jpg
https://i.imgur.com/7z0fo0R.jpg
https://i.imgur.com/80Vah2K.jpg
https://i.imgur.com/89CeT1t.jpg
https://i.imgur.com/8cUnFxQ.jpg
https://i.imgur.com/8fNSEQm.jpg
https://i.imgur.com/8Jt0tda.jpg
https://i.imgur.com/8kjS75R.jpg
https://i.imgur.com/8n5Apus.jpg
https://i.imgur.com/8OjQHs3.jpg
https://i.imgur.com/8PLH6rX.jpg
https://i.imgur.com/8ppnK3a.jpg
https://i.imgur.com/8TrG1ND.jpg
https://i.imgur.com/8u7MGlq.jpg
https://i.imgur.com/8x1Volo.jpg
https://i.imgur.com/8X8Wcei.jpg
https://i.imgur.com/97abbjN.jpg
https://i.imgur.com/9CpwXLg.jpg
https://i.imgur.com/9D7Qqhj.jpg
https://i.imgur.com/9DYN9Er.jpg
https://i.imgur.com/9IeUZfc.jpg
https://i.imgur.com/9MkTlnn.jpg
https://i.imgur.com/9muNmH3.jpg
https://i.imgur.com/9T5Avps.jpg
https://i.imgur.com/9TvWrhK.jpg
https://i.imgur.com/9vOHNzj.jpg
https://i.imgur.com/9wUob3H.jpg
https://i.imgur.com/a1C8HO9.jpg
https://i.imgur.com/A8YBjQ4.jpg
https://i.imgur.com/AawY4F8.jpg
https://i.imgur.com/ACiAeF8.jpg
https://i.imgur.com/AdYNcAH.jpg
https://i.imgur.com/afLKA6u.jpg
https://i.imgur.com/AKVSIQK.jpg
https://i.imgur.com/ApFAHAZ.jpg
https://i.imgur.com/aptmjEK.jpg
https://i.imgur.com/AVItfa4.jpg
https://i.imgur.com/aWTZ2hG.jpg
https://i.imgur.com/ayDtZkU.jpg
https://i.imgur.com/aYniQYo.jpg
https://i.imgur.com/b2qnR59.jpg
https://i.imgur.com/b6fhTvd.jpg
https://i.imgur.com/B8iEAJK.jpg
https://i.imgur.com/BEIukCO.jpg
https://i.imgur.com/bEMcTiR.jpg
https://i.imgur.com/BFe1FGm.jpg
https://i.imgur.com/BHs5jVg.jpg
https://i.imgur.com/BsHylTL.jpg
https://i.imgur.com/btxo8RE.jpg
https://i.imgur.com/Bu69KMr.jpg
https://i.imgur.com/bvMiApC.jpg
https://i.imgur.com/bxVVn2w.jpg
https://i.imgur.com/bzMK3RG.jpg
https://i.imgur.com/c3sOiw5.jpg
https://i.imgur.com/c6C2lxt.jpg
https://i.imgur.com/c78O6mR.jpg
https://i.imgur.com/c7E1AUb.jpg
https://i.imgur.com/C7hkBna.jpg
https://i.imgur.com/ceIwJVs.jpg
https://i.imgur.com/CEWepnX.jpg
https://i.imgur.com/CgQJzXO.jpg
https://i.imgur.com/CgZPuwt.jpg
https://i.imgur.com/ChhNJGd.jpg
https://i.imgur.com/CidCGIB.jpg
https://i.imgur.com/ciFBuTk.jpg
https://i.imgur.com/CiNc6dN.jpg
https://i.imgur.com/cJ0dsrr.jpg
https://i.imgur.com/CJalZNC.jpg
https://i.imgur.com/CjjXXzR.jpg
https://i.imgur.com/cK278TM.jpg
https://i.imgur.com/cKja3lE.jpg
https://i.imgur.com/clDOch1.jpg
https://i.imgur.com/coLJ40m.jpg
https://i.imgur.com/cPHiWxs.jpg
https://i.imgur.com/CPW2ltW.jpg
https://i.imgur.com/cQvmDJ6.jpg
https://i.imgur.com/credwzR.jpg
https://i.imgur.com/CWE2cLw.jpg
https://i.imgur.com/CWSi6NF.jpg
https://i.imgur.com/d01vdsP.jpg
https://i.imgur.com/d7TlEPa.jpg
https://i.imgur.com/DCsEBs8.jpg
https://i.imgur.com/dd8LgrJ.jpg
https://i.imgur.com/DEjeOkZ.jpg
https://i.imgur.com/dJI5hitg.jpg
https://i.imgur.com/dMavsC3.jpg
https://i.imgur.com/doPpQbs.jpg
https://i.imgur.com/DsRkNxw.jpg
https://i.imgur.com/dUg2o0E.jpg
https://i.imgur.com/DUWhuwQ.jpg
https://i.imgur.com/dXWtcUP.jpg
https://i.imgur.com/DY1r5Zp.jpg
https://i.imgur.com/E8DbAor.jpg
https://i.imgur.com/ea8bW7M.jpg
https://i.imgur.com/eaoTpWz.jpg
https://i.imgur.com/eAqcpcI.jpg
https://i.imgur.com/eBuwHIh.jpg
https://i.imgur.com/ebwHw6k.jpg
https://i.imgur.com/edaVIPF.jpg
https://i.imgur.com/EEnMpKl.jpg
https://i.imgur.com/EfJTAVL.jpg
https://i.imgur.com/eg9qAbp.jpg
https://i.imgur.com/EI2dMAS.jpg
https://i.imgur.com/EkU7gZt.jpg
https://i.imgur.com/eLnm9uD.jpg
https://i.imgur.com/ElxRH7i.jpg
https://i.imgur.com/eNByqjx.jpg
https://i.imgur.com/EpBLaU3.jpg
https://i.imgur.com/euLV3wA.jpg
https://i.imgur.com/EyxpeOT.jpg
https://i.imgur.com/eyywrsE.jpg
https://i.imgur.com/f1DGHlx.jpg
https://i.imgur.com/f2cRbPd.jpg
https://i.imgur.com/F3yFdoA.jpg
https://i.imgur.com/F64wN1J_d.jpg?maxwidth=640&shape=thumb&fidelity=medium
https://i.imgur.com/f8F7oX1.jpg
https://i.imgur.com/F9vHOYv.jpg
https://i.imgur.com/FAc8vpE.jpg
https://i.imgur.com/fdMPFnO.jpg
https://i.imgur.com/ffZupJn.jpg
https://i.imgur.com/fgpkCIJ.jpg
https://i.imgur.com/FiOzCQO.jpg
https://i.imgur.com/flFzSoG.jpg
https://i.imgur.com/FMAMWIC.jpg
https://i.imgur.com/fPI5X2Z.jpg
https://i.imgur.com/fqfk78O.jpg
https://i.imgur.com/FrKwmDz.jpg
https://i.imgur.com/FtvGxJF.jpg
https://i.imgur.com/FU4uCSL.jpg
https://i.imgur.com/FvLQhyD.jpg
https://i.imgur.com/FXnLd5Q.jpg
https://i.imgur.com/FyIf4Fl.jpg
https://i.imgur.com/fZOkObr.jpg
https://i.imgur.com/G9yqbvX.jpg
https://i.imgur.com/GCFFGyJ.jpg
https://i.imgur.com/gejswa8.jpg
https://i.imgur.com/gHQe5UL.jpg
https://i.imgur.com/GNaUwLk.jpg
https://i.imgur.com/gO4U49e.jpg
https://i.imgur.com/gpO6eh1.jpg
https://i.imgur.com/GQ6h0bC.jpg
https://i.imgur.com/gQhP8FQ.jpg
https://i.imgur.com/GsF4OuH.jpg
https://i.imgur.com/gtMmtTh.jpg
https://i.imgur.com/GtR2uRD.jpg
https://i.imgur.com/GWMwZlk.jpg
https://i.imgur.com/H1JHh8z.jpg
https://i.imgur.com/h3995PF.jpg
https://i.imgur.com/H3Dm9BS.jpg
https://i.imgur.com/h9FOEn9.jpg
https://i.imgur.com/haYl6gI.jpg
https://i.imgur.com/hb1IC.jpg
https://i.imgur.com/hDIM7Pe.jpg
https://i.imgur.com/hEeDTle.jpg
https://i.imgur.com/hGlNKUr.jpg
https://i.imgur.com/hH3Vm1A.jpg
https://i.imgur.com/HM0abfK.jpg
https://i.imgur.com/hp0LuOl.jpg
https://i.imgur.com/HSCfl00.jpg
https://i.imgur.com/hSNnLj3.jpg
https://i.imgur.com/HUtlUo2.jpg
https://i.imgur.com/hw9xaBn.jpg
https://i.imgur.com/HWHeTpP.jpg
https://i.imgur.com/HWjwKuw.jpg
https://i.imgur.com/i2ftqxo.jpg
https://i.imgur.com/i4BfLJa.jpg
https://i.imgur.com/i9pMbsq.jpg
https://i.imgur.com/i9RnzP7.jpg
https://i.imgur.com/I9YniEO.jpg
https://i.imgur.com/iBLKucn.jpg
https://i.imgur.com/IDS6dRB.jpg
https://i.imgur.com/IfvqdzN.jpg
https://i.imgur.com/IIzWqgu.jpg
https://i.imgur.com/IJCr96L.jpg
https://i.imgur.com/IkK6laR.jpg
https://i.imgur.com/iLQbh7t.jpg
https://i.imgur.com/IqlzNjk.jpg
https://i.imgur.com/IVta4Qy.jpg
https://i.imgur.com/iW9wdQQ.jpg
https://i.imgur.com/iwBY7rM.jpg
https://i.imgur.com/IX0aIdG.jpg
https://i.imgur.com/j516XNW.jpg
https://i.imgur.com/jcHBR7U.jpg
https://i.imgur.com/JcwyPTp.jpg
https://i.imgur.com/Jeyt6af.jpg
https://i.imgur.com/JIGfnxf.jpg
https://i.imgur.com/JJkUY2g.jpg
https://i.imgur.com/Jjvt2A4.jpg
https://i.imgur.com/Jkp0NhX.jpg
https://i.imgur.com/JlkcFXx.jpg
https://i.imgur.com/jlygoIq.jpg
https://i.imgur.com/jWQueHH.jpg
https://i.imgur.com/JxPQTaE.jpg
https://i.imgur.com/JXTR62v.jpg
https://i.imgur.com/K0xhERI.jpg
https://i.imgur.com/k2s936G.jpg
https://i.imgur.com/K3XM4hu.jpg
https://i.imgur.com/k6cAmyC.jpg
https://i.imgur.com/k6PnQyQ.jpg
https://i.imgur.com/KACaFcu.jpg
https://i.imgur.com/keENunD.jpg
https://i.imgur.com/kGuF4sE.jpg
https://i.imgur.com/kI21rlN.jpg
https://i.imgur.com/KKjBG95.jpg
https://i.imgur.com/KmNK6It.jpg
https://i.imgur.com/Kpp0Ylz.jpg
https://i.imgur.com/KQ94Ysy.jpg
https://i.imgur.com/KQICogk.jpg
https://i.imgur.com/KWsZS1d.jpg
https://i.imgur.com/Ky7SdtY.jpg
https://i.imgur.com/KYWoey2.jpg
https://i.imgur.com/kzkFQ60.jpg
https://i.imgur.com/l1gAUKs.jpg
https://i.imgur.com/L3KWEwj.jpg
https://i.imgur.com/l7ur6Ic.jpg
https://i.imgur.com/lbaDV4s.jpg
https://i.imgur.com/LchYpYC.jpg
https://i.imgur.com/lDA8CgD.jpg
https://i.imgur.com/leb3hyh.jpg
https://i.imgur.com/LEwC4fh.jpg
https://i.imgur.com/lgvcrHg.jpg
https://i.imgur.com/lo7zCZo.jpg
https://i.imgur.com/lPI09sl.jpg
https://i.imgur.com/LPUGs5K.jpg
https://i.imgur.com/LqpdDUT.jpg
https://i.imgur.com/lR4iqHK.jpg
https://i.imgur.com/LtooJWJ.jpg
https://i.imgur.com/LuFFhkz.jpg
https://i.imgur.com/lVF7S9C.jpg
https://i.imgur.com/lw2Kcmw.jpg
https://i.imgur.com/lWp9iOG.jpg
https://i.imgur.com/lxh54xM.jpg
https://i.imgur.com/LyII8hX.jpg
https://i.imgur.com/M23kgsB.jpg
https://i.imgur.com/M33kyqs.jpg
https://i.imgur.com/M5rHiAt.jpg
https://i.imgur.com/mEzdIr1.jpg
https://i.imgur.com/mFlGcbA.jpg
https://i.imgur.com/MHkZXcP.jpg
https://i.imgur.com/MIRyLYl.jpg
https://i.imgur.com/mkcVOGY.jpg
https://i.imgur.com/MkJdOAz.jpg
https://i.imgur.com/MlWulnI.jpg
https://i.imgur.com/mLxldKd.jpg
https://i.imgur.com/mmoAi3C.jpg
https://i.imgur.com/mopWznX.jpg
https://i.imgur.com/MpqmEnc.jpg
https://i.imgur.com/mRTNk1C.jpg
https://i.imgur.com/MVMj4fN.jpg
https://i.imgur.com/MY4NZhL.jpg
https://i.imgur.com/mZIZhhT.jpg
https://i.imgur.com/n11Z6P9.jpg
https://i.imgur.com/N4fc5o7.jpg
https://i.imgur.com/N4WWczw.jpg
https://i.imgur.com/N7ZEzhw.jpg
https://i.imgur.com/ncC0xWS.jpg
https://i.imgur.com/Nf3Nspy.jpg
https://i.imgur.com/nfFA63d.jpg
https://i.imgur.com/NHBhH8d.jpg
https://i.imgur.com/nja4RdC.jpg
https://i.imgur.com/nOIiNRM.jpg
https://i.imgur.com/NPGogtt.jpg
https://i.imgur.com/nPWBPXZ.jpg
https://i.imgur.com/NqGV3F3.jpg
https://i.imgur.com/nrltYsf.jpg
https://i.imgur.com/NS7XsQH.jpg
https://i.imgur.com/nWQTUF8.jpg
https://i.imgur.com/nxFMRhKh.jpg
https://i.imgur.com/o18n0BN.jpg
https://i.imgur.com/O1gpyNN.jpg
https://i.imgur.com/O1XiAFD.jpg
https://i.imgur.com/o8wpkCs.jpg
https://i.imgur.com/oCio46H.jpg
https://i.imgur.com/oCJ9aN4.jpg
https://i.imgur.com/OdSX7Y0.jpg
https://i.imgur.com/Oe4u0xP.jpg
https://i.imgur.com/OEVhNrx.jpg
https://i.imgur.com/oFEnNBM.jpg
https://i.imgur.com/OhQmYju.jpg
https://i.imgur.com/OiGGYmR.jpg
https://i.imgur.com/OMIUtPl.jpg
https://i.imgur.com/ONnnxXL.jpg
https://i.imgur.com/oohMttU.jpg
https://i.imgur.com/ooLJDNG.jpg
https://i.imgur.com/OPynfpy.jpg
https://i.imgur.com/OrVlS2g.jpg
https://i.imgur.com/osnEk1K.jpg
https://i.imgur.com/OSR1piY.jpg
https://i.imgur.com/oU6iVqb.jpg
https://i.imgur.com/oy0rtFn.jpg
https://i.imgur.com/oZae8vN.jpg
https://i.imgur.com/p01UAem.jpg
https://i.imgur.com/P047r9W.jpg
https://i.imgur.com/P8kEO6b.jpg
https://i.imgur.com/pbhZYZ0.jpg
https://i.imgur.com/pCuLUhm.jpg
https://i.imgur.com/PDb2RaD.jpg
https://i.imgur.com/pexoMkF.jpg
https://i.imgur.com/PF60ygx.jpg
https://i.imgur.com/PFjb9YA.jpg
https://i.imgur.com/pFzPaWA.jpg
https://i.imgur.com/PKGLBEA.jpg
https://i.imgur.com/PkZh2Eu.jpg
https://i.imgur.com/pL46ySP.jpg
https://i.imgur.com/plHeAhL.jpg
https://i.imgur.com/PMPHAWM.jpg
https://i.imgur.com/pmSu6Lp.jpg
https://i.imgur.com/pN2EGYe.jpg
https://i.imgur.com/PN2K3uG.jpg
https://i.imgur.com/pNEuauQ.jpg
https://i.imgur.com/pSJu0hu.jpg
https://i.imgur.com/pspBykd.jpg
https://i.imgur.com/PXXiOy1.jpg
https://i.imgur.com/pYXk5Da.jpg
https://i.imgur.com/PZJY6WW.jpg
https://i.imgur.com/qBf7AUy.jpg
https://i.imgur.com/QCEoVgU.jpg
https://i.imgur.com/QDeGDqM.jpg
https://i.imgur.com/qEXvkWV.jpg
https://i.imgur.com/qG0VFE2.jpg
https://i.imgur.com/QjZRCMM.jpg
https://i.imgur.com/qkzbwHg.jpg
https://i.imgur.com/Qmc6ipi.jpg
https://i.imgur.com/qSNJipZ.jpg
https://i.imgur.com/qtkF1hn.jpg
https://i.imgur.com/QTqiBdh.jpg
https://i.imgur.com/QX1jeLC.jpg
https://i.imgur.com/QyFh2re.jpg
https://i.imgur.com/Qzj3p03.jpg
https://i.imgur.com/r1jgPDF.jpg
https://i.imgur.com/R1KNrNI.jpg
https://i.imgur.com/rdlxiuI.jpg
https://i.imgur.com/RdV7l1q.jpg
https://i.imgur.com/rhjOGXy.jpg
https://i.imgur.com/rizNkr0.jpg
https://i.imgur.com/RoVckhH.jpg
https://i.imgur.com/rP7k9zi.jpg
https://i.imgur.com/RPy0AUT.jpg
https://i.imgur.com/RtXSoSb.jpg
https://i.imgur.com/RvXI8Wc.jpg
https://i.imgur.com/rVYbSuR.jpg
https://i.imgur.com/ry7HAzh.jpg
https://i.imgur.com/rYiKlpU.jpg
https://i.imgur.com/RyViHjn.jpg
https://i.imgur.com/s0YbebU.jpg
https://i.imgur.com/S1bxdB5.jpg
https://i.imgur.com/S2kttft.jpg
https://i.imgur.com/S3RhAjM.jpg
https://i.imgur.com/S92yVQw.jpg
https://i.imgur.com/S9ZeYnd.jpg
https://i.imgur.com/sC20iY2.jpg
https://i.imgur.com/SDKYndU.jpg
https://i.imgur.com/SDPRHEu.jpg
https://i.imgur.com/sEdyKUz.jpg
https://i.imgur.com/sevHRYc.jpg
https://i.imgur.com/sftkD7p.jpg
https://i.imgur.com/Sgt2W8H.jpg
https://i.imgur.com/sGykcLs.jpg
https://i.imgur.com/snGVsgM.jpg
https://i.imgur.com/sPFr1kw.jpg
https://i.imgur.com/sPtglio.jpg
https://i.imgur.com/sq52rQA.jpg
https://i.imgur.com/sRY96r7.jpg
https://i.imgur.com/STbxatZ.jpg
https://i.imgur.com/sv8TtX3.jpg
https://i.imgur.com/Swe929R.jpg
https://i.imgur.com/sXMS9SS.jpg
https://i.imgur.com/T1jdqYa.jpg
https://i.imgur.com/T1teWo9.jpg
https://i.imgur.com/t2drFI6.jpg
https://i.imgur.com/T2ngDy2.jpg
https://i.imgur.com/T8TBDwM.jpg
https://i.imgur.com/Tb36dAY.jpg
https://i.imgur.com/te6O03k.jpg
https://i.imgur.com/tH4EKWc.jpg
https://i.imgur.com/tiEBYsG.jpg
https://i.imgur.com/tiswmJq.jpg
https://i.imgur.com/TK1KjK9.jpg
https://i.imgur.com/TMbe5Wr.jpg
https://i.imgur.com/TnS1DQc.jpg
https://i.imgur.com/tRk3iNo.jpg
https://i.imgur.com/tTrFkNs.jpg
https://i.imgur.com/TX7UYHe.jpg
https://i.imgur.com/tx8dxvU.jpg
https://i.imgur.com/tXOeh8p.jpg
https://i.imgur.com/tz3Odcz.jpg
https://i.imgur.com/u0DfcJe.jpg
https://i.imgur.com/U0ZYeXD.jpg
https://i.imgur.com/u6dYkd5.jpg
https://i.imgur.com/UaeSE4B.jpg
https://i.imgur.com/UAVkxuF.jpg
https://i.imgur.com/ugSBtnh.jpg
https://i.imgur.com/UgUtIG1.jpg
https://i.imgur.com/uHacv48.jpg
https://i.imgur.com/UIIVN1W.jpg
https://i.imgur.com/uiZ2Ofv.jpg
https://i.imgur.com/UJLtEUO.jpg
https://i.imgur.com/uKrizKW.jpg
https://i.imgur.com/uo6qQ2U.jpg
https://i.imgur.com/uoHlYdm.jpg
https://i.imgur.com/UOrSzlK_d.jpg?maxwidth=640&shape=thumb&fidelity=medium
https://i.imgur.com/UQVsg6d.jpg
https://i.imgur.com/uRjVh9c.jpg
https://i.imgur.com/UU8rP8b.jpg
https://i.imgur.com/uvz9BYF.jpg
https://i.imgur.com/ux8YFfT.jpg
https://i.imgur.com/UXwEXPb.jpg
https://i.imgur.com/V7ee3k5.jpg
https://i.imgur.com/V7KduO8.jpg
https://i.imgur.com/v90Onhx.jpg
https://i.imgur.com/VAn6Lo5.jpg
https://i.imgur.com/vaxQQSR.jpg
https://i.imgur.com/VbRCBvC.jpg
https://i.imgur.com/vCYRRP2.jpg
https://i.imgur.com/vDW46mh.jpg
https://i.imgur.com/VGjCliQ.jpg
https://i.imgur.com/vgZuXGT.jpg
https://i.imgur.com/VhsHGvn.jpg
https://i.imgur.com/VIvPIBF.jpg
https://i.imgur.com/VlScR4H.jpg
https://i.imgur.com/vlZrJuG.jpg
https://i.imgur.com/VnCNKd2.jpg
https://i.imgur.com/vogeUK3.jpg
https://i.imgur.com/vop3A1q.jpg
https://i.imgur.com/vtIgOJB.jpg
https://i.imgur.com/VTwBOIJ.jpg
https://i.imgur.com/VVBRMeu.jpg
https://i.imgur.com/VYKTI19.jpg
https://i.imgur.com/vzlYIfm.jpg
https://i.imgur.com/wasg0Y4.jpg
https://i.imgur.com/weffGEb.jpg
https://i.imgur.com/WfT6SfH.jpg
https://i.imgur.com/WG2HR3X.jpg
https://i.imgur.com/wGOwD1Y.jpg
https://i.imgur.com/wgPRBOA.jpg
https://i.imgur.com/wRvi7WW.jpg
https://i.imgur.com/wtdT6N3.jpg
https://i.imgur.com/WtOQ7cK.jpg
https://i.imgur.com/WV1YIDz.jpg
https://i.imgur.com/WWyg1h3.jpg
https://i.imgur.com/wYQpN2C.jpg
https://i.imgur.com/X4RwPqr.jpg.jpg
https://i.imgur.com/x5ndsOr.jpg
https://i.imgur.com/x8VwM4y.jpg
https://i.imgur.com/xAXoPba.jpg
https://i.imgur.com/xCHb8hP.jpg
https://i.imgur.com/XCvjyLh.jpg
https://i.imgur.com/XGsdJk5.jpg
https://i.imgur.com/XhZWlBW.jpg
https://i.imgur.com/XIPAhKC.jpg
https://i.imgur.com/xleQzow.jpg
https://i.imgur.com/xlFXmFM.jpg
https://i.imgur.com/Xm2R7EB.jpg
https://i.imgur.com/XPoHcg1.jpg
https://i.imgur.com/XQGl2Oy.jpg
https://i.imgur.com/xrLvvSH.jpg
https://i.imgur.com/xSt5Ujk.jpg
https://i.imgur.com/xVuGV8E.jpg
https://i.imgur.com/XWrq5WV.jpg
https://i.imgur.com/Xy3jTti.jpg
https://i.imgur.com/Y0asudG.jpg
https://i.imgur.com/y2YFYXd.jpg
https://i.imgur.com/Y7KksMW.jpg
https://i.imgur.com/Y8SY3Am.jpg
https://i.imgur.com/YCFzQOj.jpg
https://i.imgur.com/YiK8iC5.jpg
https://i.imgur.com/yM1OtSG.jpg
https://i.imgur.com/ymMlpJN.jpg
https://i.imgur.com/yoAb8tI.jpg
https://i.imgur.com/yoOGf0i.jpg
https://i.imgur.com/ysu2MGF.jpg
https://i.imgur.com/Yu5vLWT.jpg
https://i.imgur.com/yvMv7v1.jpg
https://i.imgur.com/z2Lt5Hw.jpg
https://i.imgur.com/Z3VZwWy.jpg
https://i.imgur.com/z67u2Ps.jpg
https://i.imgur.com/Z6DtbMV.jpg
https://i.imgur.com/Z7AZ6oK.jpg
https://i.imgur.com/z7Owk7Y.jpg
https://i.imgur.com/ZBwdoGT.jpg
https://i.imgur.com/zC3yBXJ.jpg
https://i.imgur.com/zE22zt2.jpg
https://i.imgur.com/zE40plT.jpg
https://i.imgur.com/zGRIaqs.jpg
https://i.imgur.com/ZgS4C2z.jpg
https://i.imgur.com/Zh0kJYn.jpg
https://i.imgur.com/zi6nzWn.jpg
https://i.imgur.com/ZiDDUC0.jpg
https://i.imgur.com/ZIexPLm.jpg
https://i.imgur.com/zM5ob8r.jpg
https://i.imgur.com/ZNWiitc.jpg
https://i.imgur.com/Zo7LxvA.jpg
https://i.imgur.com/zP87qyl.jpg
https://i.imgur.com/zUHS0PB.jpg
https://i.imgur.com/ZUsyV10.jpg
https://i.imgur.com/zvEQgHg.jpg
https://i.imgur.com/ZWeIhGy.jpg
https://i.imgur.com/Zwoqdp6.jpg
https://i.imgur.com/zZ8JzV4.jpg
https://imgur.com/1LLBf9M.jpg
https://imgur.com/1N2ojlu.jpg
https://imgur.com/3oSKe80.jpg
https://imgur.com/6QecYOf.jpg
https://imgur.com/b7hb2iZ.jpg
https://imgur.com/D2NmCfK.jpg
https://imgur.com/EFV3uxM.jpg
https://imgur.com/ei0fMJ5.jpg
https://imgur.com/EWn53FD.jpg
https://imgur.com/ImLhS0Z.jpg
https://imgur.com/Imn6xqP.jpg
https://imgur.com/NoqpbL3.jpg
https://imgur.com/NXJHpGs.jpg
https://imgur.com/oYme0oW.jpg
https://imgur.com/rDKzUjM.jpg
https://imgur.com/TjMJZS2.jpg
https://imgur.com/ud5QvLO.jpg
https://imgur.com/VBw7kIQ.jpg
https://imgur.com/Xgb0gK6.jpg
https://imgur.com/XGsdJk5.jpg
https://imgur.com/ZE6FtTI.jpg
https://imgur.com/zTj0zFV.jpg
https://i.redd.it/00qucz5b5vq01.jpg
https://i.redd.it/2ap26wiltav11.jpg
https://i.redd.it/2aru6s799tr11.jpg
https://i.redd.it/2js2dqvd4u121.jpg
https://i.redd.it/35qp43e5tun11.jpg
https://i.redd.it/3uphgqjrao221.jpg
https://i.redd.it/5ektnrxy13011.jpg
https://i.redd.it/5kp3k4w5tu221.jpg
https://i.redd.it/5t17q21timm11.jpg
https://i.redd.it/64h5jjseacn11.jpg
https://i.redd.it/6pk4cz118so11.jpg
https://i.redd.it/6uktb9a34zz11.jpg
https://i.redd.it/6uyv8iikus7z.jpg
https://i.redd.it/71948wzdtkt01.jpg
https://i.redd.it/7ait8dujwqq11.jpg
https://i.redd.it/7ic82bscca921.jpg
https://i.redd.it/7yvhds9eky011.jpg
https://i.redd.it/86y0vmcfoz321.jpg
https://i.redd.it/8hjnj4mf7ey01.jpg
https://i.redd.it/8i2zgqjmckb11.jpg
https://i.redd.it/8rb6w7tytm7z.jpg
https://i.redd.it/8xwnm6a5bn521.jpg
https://i.redd.it/9auli8z9s0m01.jpg
https://i.redd.it/9mhz6veu6h921.jpg
https://i.redd.it/a0nwrw19zlb21.jpg
https://i.redd.it/a6myelpge1b21.jpg
https://i.redd.it/aih95b8ziv921.jpg
https://i.redd.it/alzqgrt3jwz11.jpg
https://i.redd.it/ap0cnf0wcp521.jpg
https://i.redd.it/bn5mkgyyvk811.jpg
https://i.redd.it/cqu1dwjzn9021.jpg
https://i.redd.it/cr6qtgltfqe11.jpg
https://i.redd.it/ctmh1phjw5z11.jpg
https://i.redd.it/cu22shjpue821.jpg
https://i.redd.it/cuhmr70vc7l11.jpg
https://i.redd.it/dk748oe12o021.jpg
https://i.redd.it/dtqvahx3bfn11.jpg
https://i.redd.it/e9eyda6sexk01.jpg
https://i.redd.it/ed4y8m4k1tp11.jpg
https://i.redd.it/eh7n1wmjssw01.jpg
https://i.redd.it/fao1bcd3gx121.jpg
https://i.redd.it/fpwpniqsce121.jpg
https://i.redd.it/gz5y6uwzzwv01.jpg
https://i.redd.it/hry6s4wewwi11.jpg
https://i.redd.it/i3uhcc7tngwz.jpg
https://i.redd.it/ismvhv42poz11.jpg
https://i.redd.it/j1d2sq7swve11.jpg
https://i.redd.it/j8nb2miuoo601.jpg
https://i.redd.it/jazfnym803g11.jpg
https://i.redd.it/jtw716tav6911.jpg
https://i.redd.it/kkag7x9ceyyy.jpg
https://i.redd.it/kkwo6p3zbg811.jpg
https://i.redd.it/l1avt8sut0d21.jpg
https://i.redd.it/l6pkj6cvkx621.jpg
https://i.redd.it/lpirnf6k9rv11.jpg
https://i.redd.it/n2zkbwoxmt111.jpg
https://i.redd.it/ngkwjf2heb221.jpg
https://i.redd.it/ny7klssc01521.jpg
https://i.redd.it/o8t9xc3o3r021.jpg
https://i.redd.it/p0ldgejtmsc11.jpg
https://i.redd.it/pnckbulhh3l11.jpg
https://i.redd.it/qja6u0fwaop11.jpg
https://i.redd.it/qycqek7zhrv01.jpg
https://i.redd.it/r6do1z9vkl021.jpg
https://i.redd.it/r8yght8fud121.jpg
https://i.redd.it/s781stiqxru11.jpg
https://i.redd.it/sy6fuoeu62721.jpg
https://i.redd.it/t6phcnekhk321.jpg
https://i.redd.it/tkui114bdm621.jpg
https://i.redd.it/u12605c7tq121.jpg
https://i.redd.it/unog0fopp3m01.jpg
https://i.redd.it/v353kw34ig811.jpg
https://i.redd.it/vhwp4maiz4921.jpg
https://i.redd.it/vskgzsn5hv521.jpg
https://i.redd.it/wqchiijlp0s11.jpg
https://i.redd.it/wzgmio575q621.jpg
https://i.redd.it/x1h4jbs59u811.jpg
https://i.redd.it/xnxkhxv9c6y11.jpg
https://i.redd.it/xwelolykdar11.jpg
https://i.redd.it/y3emx7d9y7921.jpg
https://i.redd.it/ymeenpmjc2421.jpg
https://i.redd.it/yoc0wcm3tc011.jpg
https://i.redd.it/yxh40xbi32821.jpg
https://i.redd.it/zyx15vdv0m021.jpg
https://pbs.twimg.com/media/Az_3mC9CIAA1tTP.jpg
https://s101.erome.com/22/BQLq4D8Y/0SU2IdH5.jpg
|
{
"pile_set_name": "Github"
}
|
import urlparse
from urllib import urlencode
import requests
import sqlalchemy
from flask import current_app
from forex_python.converter import CurrencyRates
import stripe
from app.api.helpers.cache import cache
from app.api.helpers.db import safe_query, save_to_db
from app.api.helpers.files import make_frontend_url
from app.api.helpers.utilities import represents_int
from app.models.stripe_authorization import StripeAuthorization
from app.models.ticket_fee import TicketFees
from app.models.order import Order
from app.settings import get_settings
from app.models import db
from app.models.event import Event
DEFAULT_FEE = 0.0
@cache.memoize(5)
def forex(from_currency, to_currency, amount):
try:
currency_rates = CurrencyRates()
return currency_rates.convert(from_currency, to_currency, amount)
except:
return amount
@cache.memoize(5)
def get_fee(currency):
fee = TicketFees.query.filter_by(currency=currency).order_by(sqlalchemy.desc(TicketFees.id)).first()
if fee:
return fee.service_fee
else:
return DEFAULT_FEE
class StripePaymentsManager(object):
@staticmethod
def get_credentials(event=None):
if not event:
settings = get_settings()
if settings['stripe_secret_key'] and settings["stripe_publishable_key"] and settings[
'stripe_secret_key'] != "" and \
settings["stripe_publishable_key"] != "":
return {
'SECRET_KEY': settings['stripe_secret_key'],
'PUBLISHABLE_KEY': settings["stripe_publishable_key"]
}
else:
return None
else:
if represents_int(event):
authorization = StripeAuthorization.query.filter_by(event_id=event).first()
else:
authorization = event.stripe
if authorization:
return {
'SECRET_KEY': authorization.stripe_secret_key,
'PUBLISHABLE_KEY': authorization.stripe_publishable_key
}
else:
return None
@staticmethod
def capture_payment(order_invoice, currency=None, credentials=None):
if not credentials:
credentials = StripePaymentsManager.get_credentials(order_invoice.event)
if not credentials:
raise Exception('Stripe is incorrectly configured')
stripe.api_key = credentials['SECRET_KEY']
if not currency:
currency = order_invoice.event.payment_currency
if not currency or currency == "":
currency = "USD"
try:
customer = stripe.Customer.create(
email=order_invoice.user.email,
source=order_invoice.stripe_token
)
charge = stripe.Charge.create(
customer=customer.id,
amount=int(order_invoice.amount * 100),
currency=currency.lower(),
metadata={
'order_id': order_invoice.id,
'event': order_invoice.event.name,
'user_id': order_invoice.user_id,
'event_id': order_invoice.event_id
},
description=order_invoice.event.name
)
return charge
except:
return None
class PayPalPaymentsManager(object):
api_version = 93
@staticmethod
def get_credentials(event=None, override_mode=False, is_testing=False):
if event and represents_int(event):
event = safe_query(db, Event, 'id', event, 'event_id')
settings = get_settings()
if not override_mode:
if settings['paypal_mode'] and settings['paypal_mode'] != "":
if settings['paypal_mode'] == 'live':
is_testing = False
else:
is_testing = True
else:
return None
if is_testing:
credentials = {
'USER': settings['paypal_sandbox_username'],
'PWD': settings['paypal_sandbox_password'],
'SIGNATURE': settings['paypal_sandbox_signature'],
'SERVER': 'https://api-3t.sandbox.paypal.com/nvp',
'CHECKOUT_URL': 'https://www.sandbox.paypal.com/cgi-bin/webscr',
'EMAIL': '' if not event or not event.paypal_email or event.paypal_email == "" else event.paypal_email
}
else:
credentials = {
'USER': settings['paypal_live_username'],
'PWD': settings['paypal_live_password'],
'SIGNATURE': settings['paypal_live_signature'],
'SERVER': 'https://api-3t.paypal.com/nvp',
'CHECKOUT_URL': 'https://www.paypal.com/cgi-bin/webscr',
'EMAIL': '' if not event or not event.paypal_email or event.paypal_email == "" else event.paypal_email
}
if credentials['USER'] and credentials['PWD'] and credentials['SIGNATURE'] and credentials['USER'] != "" and \
credentials['PWD'] != "" and credentials['SIGNATURE'] != "":
return credentials
else:
return None
@staticmethod
def get_checkout_url(order, currency=None, credentials=None):
if not credentials:
credentials = PayPalPaymentsManager.get_credentials(order.event)
if not credentials:
raise Exception('PayPal credentials have not be set correctly')
if current_app.config['TESTING']:
return credentials['CHECKOUT_URL']
currency = order.event.payment_currency if not currency and order.event.payment_currency != "" else "USD"
data = {
'USER': credentials['USER'],
'PWD': credentials['PWD'],
'SIGNATURE': credentials['SIGNATURE'],
'SUBJECT': credentials['EMAIL'],
'METHOD': 'SetExpressCheckout',
'VERSION': PayPalPaymentsManager.api_version,
'PAYMENTREQUEST_0_PAYMENTACTION': 'SALE',
'PAYMENTREQUEST_0_AMT': order.amount,
'PAYMENTREQUEST_0_CURRENCYCODE': currency,
'RETURNURL': make_frontend_url(path='/orders/{identifier}/payment/success'.
format(identifier=order.identifier)),
'CANCELURL': make_frontend_url(path='/orders/{identifier}/payment/cancelled'.
format(identifier=order.identifier))
}
count = 1
if type(order) is Order:
for ticket_order in order.order_tickets:
data['L_PAYMENTREQUEST_' + str(count) + '_NAMEm'] = ticket_order.ticket.name
data['L_PAYMENTREQUEST_' + str(count) + '_QTYm'] = ticket_order.quantity
data['L_PAYMENTREQUEST_' + str(count) + '_AMTm'] = ticket_order.ticket.price
count += 1
response = requests.post(credentials['SERVER'], data=data)
if 'TOKEN' not in dict(urlparse.parse_qsl(response.text)):
raise Exception('PayPal Token could not be retrieved')
token = dict(urlparse.parse_qsl(response.text))['TOKEN']
order.paypal_token = token
save_to_db(order)
return credentials['CHECKOUT_URL'] + "?" + urlencode({
'cmd': '_express-checkout',
'token': token
})
@staticmethod
def get_approved_payment_details(order, credentials=None):
if not credentials:
credentials = PayPalPaymentsManager.get_credentials(order.event)
if not credentials:
raise Exception('PayPal credentials have not be set correctly')
data = {
'USER': credentials['USER'],
'PWD': credentials['PWD'],
'SIGNATURE': credentials['SIGNATURE'],
'SUBJECT': credentials['EMAIL'],
'METHOD': 'GetExpressCheckoutDetails',
'VERSION': PayPalPaymentsManager.api_version,
'TOKEN': order.paypal_token
}
if current_app.config['TESTING']:
return data
response = requests.post(credentials['SERVER'], data=data)
return dict(urlparse.parse_qsl(response.text))
@staticmethod
def capture_payment(order, payer_id, currency=None, credentials=None):
if not credentials:
credentials = PayPalPaymentsManager.get_credentials(order.event)
if not credentials:
raise Exception('PayPal credentials have not be set correctly')
if not currency:
currency = order.event.payment_currency
if not currency or currency == "":
currency = "USD"
data = {
'USER': credentials['USER'],
'PWD': credentials['PWD'],
'SIGNATURE': credentials['SIGNATURE'],
'SUBJECT': credentials['EMAIL'],
'METHOD': 'DoExpressCheckoutPayment',
'VERSION': PayPalPaymentsManager.api_version,
'TOKEN': order.paypal_token,
'PAYERID': payer_id,
'PAYMENTREQUEST_0_PAYMENTACTION': 'SALE',
'PAYMENTREQUEST_0_AMT': order.amount,
'PAYMENTREQUEST_0_CURRENCYCODE': currency,
}
response = requests.post(credentials['SERVER'], data=data)
return dict(urlparse.parse_qsl(response.text))
|
{
"pile_set_name": "Github"
}
|
(function( window, undefined ) {
kendo.cultures["fo-FO"] = {
name: "fo-FO",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Danish Krone",
abbr: "DKK",
pattern: ["-n $","n $"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "kr"
}
},
calendars: {
standard: {
days: {
names: ["sunnudagur","mánadagur","týsdagur","mikudagur","hósdagur","fríggjadagur","leygardagur"],
namesAbbr: ["sun.","mán.","týs.","mik.","hós.","frí.","ley."],
namesShort: ["su.","má.","tý.","mi.","hó.","fr.","le."]
},
months: {
names: ["januar","februar","mars","apríl","mai","juni","juli","august","september","oktober","november","desember"],
namesAbbr: ["jan","feb","mar","apr","mai","jun","jul","aug","sep","okt","nov","des"]
},
AM: ["um fyr.","um fyr.","UM FYR."],
PM: ["um sein.","um sein.","UM SEIN."],
patterns: {
d: "dd.MM.yyyy",
D: "dddd, d. MMMM yyyy",
F: "dddd, d. MMMM yyyy HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "d. MMMM",
M: "d. MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
import re
import datatest
class TestExample(datatest.DataTestCase):
def test_membership_in_set(self):
data = ['x', 'x', 'y', 'y', 'z', 'z']
requirement = {'x', 'y', 'z'} # <- set
self.assertValid(data, requirement)
def test_function_returns_true(self):
data = ['X', 'X', 'Y', 'Y']
def requirement(x): # <- callable (helper function)
return x.isupper()
self.assertValid(data, requirement)
def test_regex_matches(self):
data = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar']
requirement = re.compile('^\w\w\w$') # <- regex object
self.assertValid(data, requirement)
def test_equality(self):
data = ['x', 'x', 'x']
requirement = 'x' # <- other (not container, callable, or regex)
self.assertValid(data, requirement)
def test_order(self):
data = ['x', 'x', 'y', 'y', 'z', 'z']
requirement = ['x', 'x', 'y', 'y', 'z', 'z'] # <- sequence
self.assertValid(data, requirement)
def test_mapping(self):
data = {'x': 'foo', 'y': 'bar'}
requirement = {'x': 'foo', 'y': 'bar'} # <- mapping
self.assertValid(data, requirement)
if __name__ == '__main__':
datatest.main()
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License").
See License in the project root for license information.
*/
package com.linkedin.kafka.clients.auditing;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* The default no-op auditor class.
*/
public class NoOpAuditor<K, V> implements Auditor<K, V> {
@Override
public void configure(Map<String, ?> configs) {
}
@Override
public void start() {
}
@Override
public Object auditToken(K key, V value) {
return null;
}
@Override
public void record(Object auditToken,
String topic,
Long timestamp,
Long messageCount,
Long bytesCount,
AuditType auditType) {
}
@Override
public void close(long timeout, TimeUnit unit) {
}
@Override
public void close() {
}
}
|
{
"pile_set_name": "Github"
}
|
config DRM_PANEL
bool
depends on DRM
help
Panel registration and lookup framework.
menu "Display Panels"
depends on DRM && DRM_PANEL
config DRM_PANEL_SIMPLE
tristate "support for simple panels"
depends on OF
depends on BACKLIGHT_CLASS_DEVICE
select VIDEOMODE_HELPERS
help
DRM panel driver for dumb panels that need at most a regulator and
a GPIO to be powered up. Optionally a backlight can be attached so
that it can be automatically turned off when the panel goes into a
low power state.
config DRM_PANEL_JDI_LT070ME05000
tristate "JDI LT070ME05000 WUXGA DSI panel"
depends on OF
depends on DRM_MIPI_DSI
depends on BACKLIGHT_CLASS_DEVICE
help
Say Y here if you want to enable support for JDI DSI video mode
panel as found in Google Nexus 7 (2013) devices.
The panel has a 1200(RGB)×1920 (WUXGA) resolution and uses
24 bit per pixel.
config DRM_PANEL_SAMSUNG_LD9040
tristate "Samsung LD9040 RGB/SPI panel"
depends on OF && SPI
select VIDEOMODE_HELPERS
config DRM_PANEL_LG_LG4573
tristate "LG4573 RGB/SPI panel"
depends on OF && SPI
select VIDEOMODE_HELPERS
help
Say Y here if you want to enable support for LG4573 RGB panel.
To compile this driver as a module, choose M here.
config DRM_PANEL_PANASONIC_VVX10F034N00
tristate "Panasonic VVX10F034N00 1920x1200 video mode panel"
depends on OF
depends on DRM_MIPI_DSI
depends on BACKLIGHT_CLASS_DEVICE
help
Say Y here if you want to enable support for Panasonic VVX10F034N00
WUXGA (1920x1200) Novatek NT1397-based DSI panel as found in some
Xperia Z2 tablets
config DRM_PANEL_SAMSUNG_S6E8AA0
tristate "Samsung S6E8AA0 DSI video mode panel"
depends on OF
select DRM_MIPI_DSI
select VIDEOMODE_HELPERS
config DRM_PANEL_SHARP_LQ101R1SX01
tristate "Sharp LQ101R1SX01 panel"
depends on OF
depends on DRM_MIPI_DSI
depends on BACKLIGHT_CLASS_DEVICE
help
Say Y here if you want to enable support for Sharp LQ101R1SX01
TFT-LCD modules. The panel has a 2560x1600 resolution and uses
24 bit RGB per pixel. It provides a dual MIPI DSI interface to
the host and has a built-in LED backlight.
To compile this driver as a module, choose M here: the module
will be called panel-sharp-lq101r1sx01.
config DRM_PANEL_SHARP_LS043T1LE01
tristate "Sharp LS043T1LE01 qHD video mode panel"
depends on OF
depends on DRM_MIPI_DSI
depends on BACKLIGHT_CLASS_DEVICE
help
Say Y here if you want to enable support for Sharp LS043T1LE01 qHD
(540x960) DSI panel as found on the Qualcomm APQ8074 Dragonboard
endmenu
|
{
"pile_set_name": "Github"
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.eagle.storage.hbase.query.coprocessor;
import org.apache.eagle.log.base.taggedlog.TaggedLogAPIEntity;
import org.apache.eagle.log.entity.*;
import org.apache.eagle.log.entity.meta.EntityDefinition;
import org.apache.eagle.log.entity.meta.Qualifier;
import org.apache.eagle.query.aggregate.AggregateFunctionType;
import org.apache.eagle.query.aggregate.raw.GroupbyKeyValue;
import org.apache.eagle.query.aggregate.raw.RawAggregator;
import org.apache.eagle.query.aggregate.timeseries.TimeSeriesAggregator;
import org.apache.eagle.storage.hbase.query.coprocessor.generated.AggregateProtos;
import org.apache.eagle.common.DateTimeUtil;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import com.google.protobuf.Service;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.Coprocessor;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.protobuf.ResponseConverter;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.InternalScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//public abstract class AbstractAggregateEndPoint extends BaseEndpointCoprocessor{
public class AggregateProtocolEndPoint extends AggregateProtos.AggregateProtocol implements AggregateProtocol, Coprocessor, CoprocessorService {
private RegionCoprocessorEnvironment env;
@Override
public Service getService() {
return this;
}
public AggregateProtocolEndPoint() {}
protected void checkNotNull(Object obj,String name) {
if(obj==null) throw new NullPointerException(name+" is null");
}
@Override
public void start(CoprocessorEnvironment env) throws IOException {
if (env instanceof RegionCoprocessorEnvironment) {
this.env = (RegionCoprocessorEnvironment)env;
} else {
throw new CoprocessorException("Must be loaded on a table region!");
}
}
@Override
public void stop(CoprocessorEnvironment env) throws IOException {
// do nothing
}
// @Override
// public ProtocolSignature getProtocolSignature(String protocol, long version, int clientMethodsHashCode) throws IOException {
// if (AggregateProtocol.class.getName().equals(protocol)) {
//// return new ProtocolSignature(AggregateProtocol.VERSION, null);
// return new ProtocolSignature(98l, null);
// }
// throw new IOException("Unknown protocol: " + protocol);
// }
protected HRegion getCurrentRegion(){
return this.env.getRegion();
}
/**
* <pre>
* Region-unittest,\x82\xB4\x85\xC2\x7F\xFF\xFE\xB6\xC9jNG\xEE!\x5C3\xBB\xAE\xA1:\x05\xA5\xA9x\xB0\xA1"8\x05\xFB(\xD2VY\xDB\x9A\x06\x09\xA9\x98\xC2\xE3\x8D=,1413960230654.aaf2a6c9f2c87c196f43497243bb2424.
* RegionID-unittest,1413960230654
* </pre>
*/
protected String getLogHeader(){
HRegion region = this.getCurrentRegion();
return LOG.isDebugEnabled() ? String.format("Region-%s",region.getRegionNameAsString()):
String.format("Region-%s,%d",region.getTableDesc().getNameAsString(),region.getRegionId());
}
protected class InternalReadReport {
public InternalReadReport(long counter,long startTimestamp,long stopTimestamp){
this.counter = counter;
this.startTimestamp = startTimestamp;
this.stopTimestamp = stopTimestamp;
}
public long getCounter() {
return counter;
}
public void setCounter(long counter) {
this.counter = counter;
}
public long getStartTimestamp() {
return startTimestamp;
}
public void setStartTimestamp(long startTimestamp) {
this.startTimestamp = startTimestamp;
}
public long getStopTimestamp() {
return stopTimestamp;
}
public void setStopTimestamp(long stopTimestamp) {
this.stopTimestamp = stopTimestamp;
}
private long counter;
private long startTimestamp;
private long stopTimestamp;
}
/**
* Asynchronous HBase scan read as entity
*
* @param scan
* @throws java.io.IOException
*/
protected InternalReadReport asyncStreamRead(EntityDefinition ed, Scan scan, EntityCreationListener listener) throws IOException {
// _init();
long counter = 0;
long startTimestamp = 0;
long stopTimestamp = 0;
InternalScanner scanner = this.getCurrentRegion().getScanner(scan);
List<Cell> results = new ArrayList<Cell>();
try{
boolean hasMoreRows;
GenericMetricShadowEntity singleMetricEntity = null;
do{
hasMoreRows = scanner.next(results);
Map<String, byte[]> kvMap = new HashMap<String, byte[]>();
if(!results.isEmpty()){
counter ++;
byte[] row = results.get(0).getRow();
long timestamp = RowkeyBuilder.getTimestamp(row, ed);
// Min
if(startTimestamp == 0 || startTimestamp > timestamp ){
startTimestamp = timestamp;
}
// Max
if(stopTimestamp == 0 || stopTimestamp < timestamp ){
stopTimestamp = timestamp;
}
for(Cell kv:results){
String qualifierName = Bytes.toString(kv.getQualifier());
// Qualifier qualifier = null;
// if(!ed.isTag(qualifierName)){
// qualifier = ed.getQualifierNameMap().get(qualifierName);
// if(qualifier == null){
// LOG.error("qualifier for " + qualifierName + " not exist");
// throw new NullPointerException("qualifier for field "+qualifierName+" not exist");
// }
// }
if(kv.getValue()!=null) kvMap.put(qualifierName ,kv.getValue());
}
// LOG.info("DEBUG: timestamp="+timestamp+", keys=["+StringUtils.join(kvMap.keySet(),",")+"]");
InternalLog internalLog = HBaseInternalLogHelper.buildObject(ed, row, timestamp, kvMap);
if(internalLog!=null){
TaggedLogAPIEntity logAPIEntity = null;
try {
logAPIEntity = HBaseInternalLogHelper.buildEntity(internalLog, ed);
if(logAPIEntity instanceof GenericMetricEntity){
if(singleMetricEntity == null) singleMetricEntity = new GenericMetricShadowEntity();
GenericMetricEntity e = (GenericMetricEntity)logAPIEntity;
if(e.getValue()!=null) {
int count = e.getValue().length;
@SuppressWarnings("unused")
Class<?> cls = ed.getMetricDefinition().getSingleTimestampEntityClass();
for (int i = 0; i < count; i++) {
long ts = logAPIEntity.getTimestamp() + i * ed.getMetricDefinition().getInterval();
// exclude those entity which is not within the time range in search condition. [start, end)
singleMetricEntity.setTimestamp(ts);
singleMetricEntity.setTags(e.getTags());
singleMetricEntity.setValue(e.getValue()[i]);
// Min
if (startTimestamp == 0 || startTimestamp > ts) startTimestamp = ts;
// Max
if (stopTimestamp == 0 || stopTimestamp < ts) stopTimestamp = ts;
listener.entityCreated(singleMetricEntity);
}
}
}else {
// LOG.info("DEBUG: rowKey="+logAPIEntity.getEncodedRowkey());
listener.entityCreated(logAPIEntity);
}
} catch (Exception e) {
if(internalLog!=null) {
LOG.error("Got exception to handle " + internalLog.toString() + ": " + e.getMessage(), e);
}
throw new IOException(e);
}
}else{
LOG.error("Got null to parse internal log for row: " + row.length + " with fields: " + kvMap);
}
results.clear();
}else{
if(LOG.isDebugEnabled()) LOG.warn("Empty batch of KeyValue");
}
} while(hasMoreRows);
}catch(IOException ex){
LOG.error(ex.getMessage(),ex);
throw ex;
} finally {
if(scanner != null) {
scanner.close();
}
}
return new InternalReadReport(counter,startTimestamp,stopTimestamp);
}
/**
* Asynchronous HBase scan read as RAW qualifier
*
* @param scan
* @param listener
* @throws Exception
*/
protected InternalReadReport asyncStreamRead(EntityDefinition ed, Scan scan, QualifierCreationListener listener) throws IOException {
// _init();
long counter = 0;
long startTimestamp = 0;
long stopTimestamp = 0;
InternalScanner scanner = this.getCurrentRegion().getScanner(scan);
List<Cell> results = new ArrayList<Cell>();
try{
boolean hasMoreRows;//false by default
do{
hasMoreRows = scanner.next(results);
Map<String, byte[]> kvMap = new HashMap<String, byte[]>();
if(!results.isEmpty()){
counter ++;
byte[] row = results.get(0).getRow();
// if(ed.isTimeSeries()){
long timestamp = RowkeyBuilder.getTimestamp(row,ed);
// Min
if(startTimestamp == 0 || startTimestamp > timestamp ){
startTimestamp = timestamp;
}
// Max
if(stopTimestamp == 0 || stopTimestamp < timestamp ){
stopTimestamp = timestamp;
}
// }
for(Cell kv:results){
String qualifierName = Bytes.toString(kv.getQualifier());
Qualifier qualifier = null;
if(!ed.isTag(qualifierName)){
qualifier = ed.getQualifierNameMap().get(qualifierName);
if(qualifier == null){
LOG.error("qualifier for field " + qualifierName + " not exist");
throw new IOException(new NullPointerException("qualifier for field "+qualifierName+" is null"));
}
qualifierName = qualifier.getDisplayName();
}
if(kv.getValue()!=null) kvMap.put(qualifierName,kv.getValue());
}
// LOG.info("DEBUG: timestamp="+timestamp+", keys=["+StringUtils.join(kvMap.keySet(),",")+"]");
if(!kvMap.isEmpty()) listener.qualifierCreated(kvMap);
results.clear();
}else{
if(LOG.isDebugEnabled()) LOG.warn("Empty batch of KeyValue");
}
} while(hasMoreRows);
} catch(IOException ex){
LOG.error(ex.getMessage(),ex);
throw ex;
} finally {
if(scanner != null) {
scanner.close();
}
}
return new InternalReadReport(counter,startTimestamp,stopTimestamp);
}
@Override
public void aggregate(RpcController controller, AggregateProtos.AggregateRequest request, RpcCallback<AggregateProtos.AggregateResult> done) {
AggregateResult result = null;
try {
result = this.aggregate(ProtoBufConverter.fromPBEntityDefinition(request.getEntityDefinition()),
ProtoBufConverter.fromPBScan(request.getScan()),
ProtoBufConverter.fromPBStringList(request.getGroupbyFieldsList()),
ProtoBufConverter.fromPBByteArrayList(request.getAggregateFuncTypesList()),
ProtoBufConverter.fromPBStringList(request.getAggregatedFieldsList())
);
} catch (IOException e) {
ResponseConverter.setControllerException(controller, e);
}
try {
done.run(ProtoBufConverter.toPBAggregateResult(result));
} catch (IOException e) {
throw new RuntimeException("Failed to convert result to PB-based message",e);
}
}
@Override
public void timeseriesAggregate(RpcController controller, AggregateProtos.TimeSeriesAggregateRequest request, RpcCallback<AggregateProtos.AggregateResult> done) {
AggregateResult result = null;
try {
result = this.aggregate(ProtoBufConverter.fromPBEntityDefinition(request.getEntityDefinition()),
ProtoBufConverter.fromPBScan(request.getScan()),
ProtoBufConverter.fromPBStringList(request.getGroupbyFieldsList()),
ProtoBufConverter.fromPBByteArrayList(request.getAggregateFuncTypesList()),
ProtoBufConverter.fromPBStringList(request.getAggregatedFieldsList()),
request.getStartTime(),
request.getEndTime(),
request.getIntervalMin()
);
} catch (IOException e) {
LOG.error("Failed to convert result to PB-based message",e);
ResponseConverter.setControllerException(controller, e);
}
try {
done.run(ProtoBufConverter.toPBAggregateResult(result));
} catch (IOException e) {
LOG.error("Failed to convert result to PB-based message",e);
ResponseConverter.setControllerException(controller, e);
}
}
private final static Logger LOG = LoggerFactory.getLogger(AggregateProtocolEndPoint.class);
/**
*
* @param entityDefinition
* @param scan
* @param groupbyFields
* @param aggregateFuncTypes
* @param aggregatedFields
* @return
* @throws Exception
*/
@Override
public AggregateResult aggregate(EntityDefinition entityDefinition, Scan scan, List<String> groupbyFields, List<byte[]> aggregateFuncTypes, List<String> aggregatedFields) throws IOException {
// LOG.info("Using coprocessor instance: "+this);
checkNotNull(entityDefinition, "entityDefinition");
String serviceName = entityDefinition.getService();
LOG.info(this.getLogHeader() +" raw group aggregate on service: " + serviceName + " by: " + groupbyFields + " func: " + AggregateFunctionType.fromBytesList(aggregateFuncTypes) + " fields: " + aggregatedFields);
if(LOG.isDebugEnabled()) LOG.debug("SCAN: "+scan.toJSON());
long _start = System.currentTimeMillis();
final RawAggregator aggregator = new RawAggregator(groupbyFields,AggregateFunctionType.fromBytesList(aggregateFuncTypes),aggregatedFields,entityDefinition);
InternalReadReport report = this.asyncStreamRead(entityDefinition, scan, aggregator);
List<GroupbyKeyValue> keyValues = aggregator.getGroupbyKeyValues();
AggregateResult result = new AggregateResult();
result.setKeyValues(keyValues);
result.setStartTimestamp(report.getStartTimestamp());
result.setStopTimestamp(report.getStopTimestamp());
long _stop = System.currentTimeMillis();
LOG.info(String.format("%s: scan = %d rows, group = %d keys, startTime = %d, endTime = %d, spend = %d ms", this.getLogHeader(),report.getCounter(),keyValues.size(),report.getStartTimestamp(),report.getStopTimestamp(),(_stop - _start)));
return result;
}
/**
* TODO: refactor time series aggregator to remove dependency of business logic entity class
*
* @param entityDefinition
* @param scan
* @param groupbyFields
* @param aggregateFuncTypes
* @param aggregatedFields
* @param intervalMin
* @return
* @throws Exception
*/
@Override
public AggregateResult aggregate(EntityDefinition entityDefinition, Scan scan, List<String> groupbyFields, List<byte[]> aggregateFuncTypes, List<String> aggregatedFields, long startTime,long endTime,long intervalMin) throws IOException {
// LOG.info("Using coprocessor instance: "+this);
checkNotNull(entityDefinition, "entityDefinition");
String serviceName = entityDefinition.getService();
LOG.info(this.getLogHeader() + " time series group aggregate on service: " + serviceName + " by: " + groupbyFields + " func: " + AggregateFunctionType.fromBytesList(aggregateFuncTypes) + " fields: " + aggregatedFields + " intervalMin: " + intervalMin +
" from: " + DateTimeUtil.millisecondsToHumanDateWithMilliseconds(startTime) + " to: " + DateTimeUtil.millisecondsToHumanDateWithMilliseconds(endTime));
if(LOG.isDebugEnabled()) LOG.debug("SCAN: "+scan.toJSON());
long _start = System.currentTimeMillis();
final TimeSeriesAggregator aggregator = new TimeSeriesAggregator(groupbyFields,AggregateFunctionType.fromBytesList(aggregateFuncTypes),aggregatedFields,startTime,endTime,intervalMin);
InternalReadReport report = this.asyncStreamRead(entityDefinition, scan,aggregator);
List<GroupbyKeyValue> keyValues = aggregator.getGroupbyKeyValues();
AggregateResult result = new AggregateResult();
result.setKeyValues(keyValues);
result.setStartTimestamp(report.getStartTimestamp());
result.setStopTimestamp(report.getStopTimestamp());
long _stop = System.currentTimeMillis();
LOG.info(String.format("%s: scan = %d rows, group = %d keys, startTime = %d, endTime = %d, spend = %d ms", this.getLogHeader(),report.getCounter(),keyValues.size(),report.getStartTimestamp(),report.getStopTimestamp(),(_stop - _start)));
return result;
}
// /**
// * Initialization per aggregate RPC call
// */
// private void _init(){
// this.startTimestamp = 0;
// this.stopTimestamp = 0;
// }
//
// // Min
// private long startTimestamp;
// // Max
// private long stopTimestamp;
//
// public long getStartTimestamp() {
// return startTimestamp;
// }
// public long getStopTimestamp() {
// return stopTimestamp;
// }
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright(c) 2007 Atheros Corporation. All rights reserved.
*
* Derived from Intel e1000 driver
* Copyright(c) 1999 - 2005 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include "atl1c.h"
/*
* check_eeprom_exist
* return 1 if eeprom exist
*/
int atl1c_check_eeprom_exist(struct atl1c_hw *hw)
{
u32 data;
AT_READ_REG(hw, REG_TWSI_DEBUG, &data);
if (data & TWSI_DEBUG_DEV_EXIST)
return 1;
return 0;
}
void atl1c_hw_set_mac_addr(struct atl1c_hw *hw)
{
u32 value;
/*
* 00-0B-6A-F6-00-DC
* 0: 6AF600DC 1: 000B
* low dword
*/
value = (((u32)hw->mac_addr[2]) << 24) |
(((u32)hw->mac_addr[3]) << 16) |
(((u32)hw->mac_addr[4]) << 8) |
(((u32)hw->mac_addr[5])) ;
AT_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 0, value);
/* hight dword */
value = (((u32)hw->mac_addr[0]) << 8) |
(((u32)hw->mac_addr[1])) ;
AT_WRITE_REG_ARRAY(hw, REG_MAC_STA_ADDR, 1, value);
}
/*
* atl1c_get_permanent_address
* return 0 if get valid mac address,
*/
static int atl1c_get_permanent_address(struct atl1c_hw *hw)
{
u32 addr[2];
u32 i;
u32 otp_ctrl_data;
u32 twsi_ctrl_data;
u8 eth_addr[ETH_ALEN];
/* init */
addr[0] = addr[1] = 0;
AT_READ_REG(hw, REG_OTP_CTRL, &otp_ctrl_data);
if (atl1c_check_eeprom_exist(hw)) {
/* Enable OTP CLK */
if (!(otp_ctrl_data & OTP_CTRL_CLK_EN)) {
otp_ctrl_data |= OTP_CTRL_CLK_EN;
AT_WRITE_REG(hw, REG_OTP_CTRL, otp_ctrl_data);
AT_WRITE_FLUSH(hw);
msleep(1);
}
AT_READ_REG(hw, REG_TWSI_CTRL, &twsi_ctrl_data);
twsi_ctrl_data |= TWSI_CTRL_SW_LDSTART;
AT_WRITE_REG(hw, REG_TWSI_CTRL, twsi_ctrl_data);
for (i = 0; i < AT_TWSI_EEPROM_TIMEOUT; i++) {
msleep(10);
AT_READ_REG(hw, REG_TWSI_CTRL, &twsi_ctrl_data);
if ((twsi_ctrl_data & TWSI_CTRL_SW_LDSTART) == 0)
break;
}
if (i >= AT_TWSI_EEPROM_TIMEOUT)
return -1;
}
/* Disable OTP_CLK */
if (otp_ctrl_data & OTP_CTRL_CLK_EN) {
otp_ctrl_data &= ~OTP_CTRL_CLK_EN;
AT_WRITE_REG(hw, REG_OTP_CTRL, otp_ctrl_data);
AT_WRITE_FLUSH(hw);
msleep(1);
}
/* maybe MAC-address is from BIOS */
AT_READ_REG(hw, REG_MAC_STA_ADDR, &addr[0]);
AT_READ_REG(hw, REG_MAC_STA_ADDR + 4, &addr[1]);
*(u32 *) ð_addr[2] = swab32(addr[0]);
*(u16 *) ð_addr[0] = swab16(*(u16 *)&addr[1]);
if (is_valid_ether_addr(eth_addr)) {
memcpy(hw->perm_mac_addr, eth_addr, ETH_ALEN);
return 0;
}
return -1;
}
bool atl1c_read_eeprom(struct atl1c_hw *hw, u32 offset, u32 *p_value)
{
int i;
int ret = false;
u32 otp_ctrl_data;
u32 control;
u32 data;
if (offset & 3)
return ret; /* address do not align */
AT_READ_REG(hw, REG_OTP_CTRL, &otp_ctrl_data);
if (!(otp_ctrl_data & OTP_CTRL_CLK_EN))
AT_WRITE_REG(hw, REG_OTP_CTRL,
(otp_ctrl_data | OTP_CTRL_CLK_EN));
AT_WRITE_REG(hw, REG_EEPROM_DATA_LO, 0);
control = (offset & EEPROM_CTRL_ADDR_MASK) << EEPROM_CTRL_ADDR_SHIFT;
AT_WRITE_REG(hw, REG_EEPROM_CTRL, control);
for (i = 0; i < 10; i++) {
udelay(100);
AT_READ_REG(hw, REG_EEPROM_CTRL, &control);
if (control & EEPROM_CTRL_RW)
break;
}
if (control & EEPROM_CTRL_RW) {
AT_READ_REG(hw, REG_EEPROM_CTRL, &data);
AT_READ_REG(hw, REG_EEPROM_DATA_LO, p_value);
data = data & 0xFFFF;
*p_value = swab32((data << 16) | (*p_value >> 16));
ret = true;
}
if (!(otp_ctrl_data & OTP_CTRL_CLK_EN))
AT_WRITE_REG(hw, REG_OTP_CTRL, otp_ctrl_data);
return ret;
}
/*
* Reads the adapter's MAC address from the EEPROM
*
* hw - Struct containing variables accessed by shared code
*/
int atl1c_read_mac_addr(struct atl1c_hw *hw)
{
int err = 0;
err = atl1c_get_permanent_address(hw);
if (err)
random_ether_addr(hw->perm_mac_addr);
memcpy(hw->mac_addr, hw->perm_mac_addr, sizeof(hw->perm_mac_addr));
return 0;
}
/*
* atl1c_hash_mc_addr
* purpose
* set hash value for a multicast address
* hash calcu processing :
* 1. calcu 32bit CRC for multicast address
* 2. reverse crc with MSB to LSB
*/
u32 atl1c_hash_mc_addr(struct atl1c_hw *hw, u8 *mc_addr)
{
u32 crc32;
u32 value = 0;
int i;
crc32 = ether_crc_le(6, mc_addr);
for (i = 0; i < 32; i++)
value |= (((crc32 >> i) & 1) << (31 - i));
return value;
}
/*
* Sets the bit in the multicast table corresponding to the hash value.
* hw - Struct containing variables accessed by shared code
* hash_value - Multicast address hash value
*/
void atl1c_hash_set(struct atl1c_hw *hw, u32 hash_value)
{
u32 hash_bit, hash_reg;
u32 mta;
/*
* The HASH Table is a register array of 2 32-bit registers.
* It is treated like an array of 64 bits. We want to set
* bit BitArray[hash_value]. So we figure out what register
* the bit is in, read it, OR in the new bit, then write
* back the new value. The register is determined by the
* upper bit of the hash value and the bit within that
* register are determined by the lower 5 bits of the value.
*/
hash_reg = (hash_value >> 31) & 0x1;
hash_bit = (hash_value >> 26) & 0x1F;
mta = AT_READ_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg);
mta |= (1 << hash_bit);
AT_WRITE_REG_ARRAY(hw, REG_RX_HASH_TABLE, hash_reg, mta);
}
/*
* Reads the value from a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to read
*/
int atl1c_read_phy_reg(struct atl1c_hw *hw, u16 reg_addr, u16 *phy_data)
{
u32 val;
int i;
val = ((u32)(reg_addr & MDIO_REG_ADDR_MASK)) << MDIO_REG_ADDR_SHIFT |
MDIO_START | MDIO_SUP_PREAMBLE | MDIO_RW |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
AT_WRITE_REG(hw, REG_MDIO_CTRL, val);
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
AT_READ_REG(hw, REG_MDIO_CTRL, &val);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
}
if (!(val & (MDIO_START | MDIO_BUSY))) {
*phy_data = (u16)val;
return 0;
}
return -1;
}
/*
* Writes a value to a PHY register
* hw - Struct containing variables accessed by shared code
* reg_addr - address of the PHY register to write
* data - data to write to the PHY
*/
int atl1c_write_phy_reg(struct atl1c_hw *hw, u32 reg_addr, u16 phy_data)
{
int i;
u32 val;
val = ((u32)(phy_data & MDIO_DATA_MASK)) << MDIO_DATA_SHIFT |
(reg_addr & MDIO_REG_ADDR_MASK) << MDIO_REG_ADDR_SHIFT |
MDIO_SUP_PREAMBLE | MDIO_START |
MDIO_CLK_25_4 << MDIO_CLK_SEL_SHIFT;
AT_WRITE_REG(hw, REG_MDIO_CTRL, val);
for (i = 0; i < MDIO_WAIT_TIMES; i++) {
udelay(2);
AT_READ_REG(hw, REG_MDIO_CTRL, &val);
if (!(val & (MDIO_START | MDIO_BUSY)))
break;
}
if (!(val & (MDIO_START | MDIO_BUSY)))
return 0;
return -1;
}
/*
* Configures PHY autoneg and flow control advertisement settings
*
* hw - Struct containing variables accessed by shared code
*/
static int atl1c_phy_setup_adv(struct atl1c_hw *hw)
{
u16 mii_adv_data = ADVERTISE_DEFAULT_CAP & ~ADVERTISE_SPEED_MASK;
u16 mii_giga_ctrl_data = GIGA_CR_1000T_DEFAULT_CAP &
~GIGA_CR_1000T_SPEED_MASK;
if (hw->autoneg_advertised & ADVERTISED_10baseT_Half)
mii_adv_data |= ADVERTISE_10HALF;
if (hw->autoneg_advertised & ADVERTISED_10baseT_Full)
mii_adv_data |= ADVERTISE_10FULL;
if (hw->autoneg_advertised & ADVERTISED_100baseT_Half)
mii_adv_data |= ADVERTISE_100HALF;
if (hw->autoneg_advertised & ADVERTISED_100baseT_Full)
mii_adv_data |= ADVERTISE_100FULL;
if (hw->autoneg_advertised & ADVERTISED_Autoneg)
mii_adv_data |= ADVERTISE_10HALF | ADVERTISE_10FULL |
ADVERTISE_100HALF | ADVERTISE_100FULL;
if (hw->ctrl_flags & ATL1C_LINK_CAP_1000M) {
if (hw->autoneg_advertised & ADVERTISED_1000baseT_Half)
mii_giga_ctrl_data |= ADVERTISE_1000HALF;
if (hw->autoneg_advertised & ADVERTISED_1000baseT_Full)
mii_giga_ctrl_data |= ADVERTISE_1000FULL;
if (hw->autoneg_advertised & ADVERTISED_Autoneg)
mii_giga_ctrl_data |= ADVERTISE_1000HALF |
ADVERTISE_1000FULL;
}
if (atl1c_write_phy_reg(hw, MII_ADVERTISE, mii_adv_data) != 0 ||
atl1c_write_phy_reg(hw, MII_GIGA_CR, mii_giga_ctrl_data) != 0)
return -1;
return 0;
}
void atl1c_phy_disable(struct atl1c_hw *hw)
{
AT_WRITE_REGW(hw, REG_GPHY_CTRL,
GPHY_CTRL_PW_WOL_DIS | GPHY_CTRL_EXT_RESET);
}
static void atl1c_phy_magic_data(struct atl1c_hw *hw)
{
u16 data;
data = ANA_LOOP_SEL_10BT | ANA_EN_MASK_TB | ANA_EN_10BT_IDLE |
((1 & ANA_INTERVAL_SEL_TIMER_MASK) <<
ANA_INTERVAL_SEL_TIMER_SHIFT);
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_18);
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
data = (2 & ANA_SERDES_CDR_BW_MASK) | ANA_MS_PAD_DBG |
ANA_SERDES_EN_DEEM | ANA_SERDES_SEL_HSP | ANA_SERDES_EN_PLL |
ANA_SERDES_EN_LCKDT;
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_5);
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
data = (44 & ANA_LONG_CABLE_TH_100_MASK) |
((33 & ANA_SHORT_CABLE_TH_100_MASK) <<
ANA_SHORT_CABLE_TH_100_SHIFT) | ANA_BP_BAD_LINK_ACCUM |
ANA_BP_SMALL_BW;
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_54);
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
data = (11 & ANA_IECHO_ADJ_MASK) | ((11 & ANA_IECHO_ADJ_MASK) <<
ANA_IECHO_ADJ_2_SHIFT) | ((8 & ANA_IECHO_ADJ_MASK) <<
ANA_IECHO_ADJ_1_SHIFT) | ((8 & ANA_IECHO_ADJ_MASK) <<
ANA_IECHO_ADJ_0_SHIFT);
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_4);
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
data = ANA_RESTART_CAL | ((7 & ANA_MANUL_SWICH_ON_MASK) <<
ANA_MANUL_SWICH_ON_SHIFT) | ANA_MAN_ENABLE |
ANA_SEL_HSP | ANA_EN_HB | ANA_OEN_125M;
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_0);
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
if (hw->ctrl_flags & ATL1C_HIB_DISABLE) {
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_41);
if (atl1c_read_phy_reg(hw, MII_DBG_DATA, &data) != 0)
return;
data &= ~ANA_TOP_PS_EN;
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
atl1c_write_phy_reg(hw, MII_DBG_ADDR, MII_ANA_CTRL_11);
if (atl1c_read_phy_reg(hw, MII_DBG_DATA, &data) != 0)
return;
data &= ~ANA_PS_HIB_EN;
atl1c_write_phy_reg(hw, MII_DBG_DATA, data);
}
}
int atl1c_phy_reset(struct atl1c_hw *hw)
{
struct atl1c_adapter *adapter = hw->adapter;
struct pci_dev *pdev = adapter->pdev;
u32 phy_ctrl_data = GPHY_CTRL_DEFAULT;
u32 mii_ier_data = IER_LINK_UP | IER_LINK_DOWN;
int err;
if (hw->ctrl_flags & ATL1C_HIB_DISABLE)
phy_ctrl_data &= ~GPHY_CTRL_HIB_EN;
AT_WRITE_REG(hw, REG_GPHY_CTRL, phy_ctrl_data);
AT_WRITE_FLUSH(hw);
msleep(40);
phy_ctrl_data |= GPHY_CTRL_EXT_RESET;
AT_WRITE_REG(hw, REG_GPHY_CTRL, phy_ctrl_data);
AT_WRITE_FLUSH(hw);
msleep(10);
/*Enable PHY LinkChange Interrupt */
err = atl1c_write_phy_reg(hw, MII_IER, mii_ier_data);
if (err) {
if (netif_msg_hw(adapter))
dev_err(&pdev->dev,
"Error enable PHY linkChange Interrupt\n");
return err;
}
if (!(hw->ctrl_flags & ATL1C_FPGA_VERSION))
atl1c_phy_magic_data(hw);
return 0;
}
int atl1c_phy_init(struct atl1c_hw *hw)
{
struct atl1c_adapter *adapter = (struct atl1c_adapter *)hw->adapter;
struct pci_dev *pdev = adapter->pdev;
int ret_val;
u16 mii_bmcr_data = BMCR_RESET;
u16 phy_id1, phy_id2;
if ((atl1c_read_phy_reg(hw, MII_PHYSID1, &phy_id1) != 0) ||
(atl1c_read_phy_reg(hw, MII_PHYSID2, &phy_id2) != 0)) {
if (netif_msg_link(adapter))
dev_err(&pdev->dev, "Error get phy ID\n");
return -1;
}
switch (hw->media_type) {
case MEDIA_TYPE_AUTO_SENSOR:
ret_val = atl1c_phy_setup_adv(hw);
if (ret_val) {
if (netif_msg_link(adapter))
dev_err(&pdev->dev,
"Error Setting up Auto-Negotiation\n");
return ret_val;
}
mii_bmcr_data |= BMCR_AUTO_NEG_EN | BMCR_RESTART_AUTO_NEG;
break;
case MEDIA_TYPE_100M_FULL:
mii_bmcr_data |= BMCR_SPEED_100 | BMCR_FULL_DUPLEX;
break;
case MEDIA_TYPE_100M_HALF:
mii_bmcr_data |= BMCR_SPEED_100;
break;
case MEDIA_TYPE_10M_FULL:
mii_bmcr_data |= BMCR_SPEED_10 | BMCR_FULL_DUPLEX;
break;
case MEDIA_TYPE_10M_HALF:
mii_bmcr_data |= BMCR_SPEED_10;
break;
default:
if (netif_msg_link(adapter))
dev_err(&pdev->dev, "Wrong Media type %d\n",
hw->media_type);
return -1;
break;
}
ret_val = atl1c_write_phy_reg(hw, MII_BMCR, mii_bmcr_data);
if (ret_val)
return ret_val;
hw->phy_configured = true;
return 0;
}
/*
* Detects the current speed and duplex settings of the hardware.
*
* hw - Struct containing variables accessed by shared code
* speed - Speed of the connection
* duplex - Duplex setting of the connection
*/
int atl1c_get_speed_and_duplex(struct atl1c_hw *hw, u16 *speed, u16 *duplex)
{
int err;
u16 phy_data;
/* Read PHY Specific Status Register (17) */
err = atl1c_read_phy_reg(hw, MII_GIGA_PSSR, &phy_data);
if (err)
return err;
if (!(phy_data & GIGA_PSSR_SPD_DPLX_RESOLVED))
return -1;
switch (phy_data & GIGA_PSSR_SPEED) {
case GIGA_PSSR_1000MBS:
*speed = SPEED_1000;
break;
case GIGA_PSSR_100MBS:
*speed = SPEED_100;
break;
case GIGA_PSSR_10MBS:
*speed = SPEED_10;
break;
default:
return -1;
break;
}
if (phy_data & GIGA_PSSR_DPLX)
*duplex = FULL_DUPLEX;
else
*duplex = HALF_DUPLEX;
return 0;
}
int atl1c_restart_autoneg(struct atl1c_hw *hw)
{
int err = 0;
u16 mii_bmcr_data = BMCR_RESET;
err = atl1c_phy_setup_adv(hw);
if (err)
return err;
mii_bmcr_data |= BMCR_AUTO_NEG_EN | BMCR_RESTART_AUTO_NEG;
return atl1c_write_phy_reg(hw, MII_BMCR, mii_bmcr_data);
}
|
{
"pile_set_name": "Github"
}
|
/* SPDX-License-Identifier: MIT */
#ifndef __NVKM_IBUS_H__
#define __NVKM_IBUS_H__
#include <core/subdev.h>
int gf100_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
int gf117_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
int gk104_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
int gk20a_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
int gm200_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
int gp10b_ibus_new(struct nvkm_device *, int, struct nvkm_subdev **);
#endif
|
{
"pile_set_name": "Github"
}
|
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Components : Common: Container renders correctly 1`] = `
<div
className="container container"
>
<div
className="full"
>
<p>
Sample child
</p>
</div>
</div>
`;
exports[`Components : Common: Container: Centered renders correctly 1`] = `
<div
className="container container"
>
<div
className="centered narrow"
>
<p>
Sample child
</p>
</div>
</div>
`;
exports[`Components : Common: Container: Narrow renders correctly 1`] = `
<div
className="container container"
>
<div
className="narrow"
>
<p>
Sample child
</p>
</div>
</div>
`;
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.