text
stringlengths
2
99.9k
meta
dict
# This schema creates tables without columns for the translated fields ActiveRecord::Schema.define do create_table :blogs, :force => true do |t| t.string :description end create_table :posts, :force => true do |t| t.references :blog end create_table :sections, :force => true do |t| end create_table :contents, :force => true do |t| t.string :type end end
{ "pile_set_name": "Github" }
# Changelog All notable changes to this project will be documented in this file, in reverse chronological order by release. ## 1.0.1 - 2016-08-06 ### Added - Nothing. ### Deprecated - Nothing. ### Removed - Nothing. ### Fixed - Updated all `@return self` annotation references in interfaces to use `@return static`, which more closelly follows the semantics of the specification. - Updated the `MessageInterface::getHeaders()` return annotation to use the value `string[][]`, indicating the format is a nested array of strings. - Updated the `@link` annotation for `RequestInterface::withRequestTarget()` to point to the correct section of RFC 7230. - Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation to add the parameter name (`$uploadedFiles`). - Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` method to correctly reference the method parameter (it was referencing an incorrect parameter name previously). ## 1.0.0 - 2016-05-18 Initial stable release; reflects accepted PSR-7 specification.
{ "pile_set_name": "Github" }
#ifndef JSON_SPIRIT_READER_TEMPLATE #define JSON_SPIRIT_READER_TEMPLATE // Copyright John W. Wilkinson 2007 - 2009. // Distributed under the MIT License, see accompanying file LICENSE.txt // json spirit version 4.03 #include "json_spirit_value.h" #include "json_spirit_error_position.h" //#define BOOST_SPIRIT_THREADSAFE // uncomment for multithreaded use, requires linking to boost.thread #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/version.hpp> #if BOOST_VERSION >= 103800 #include <boost/spirit/include/classic_core.hpp> #include <boost/spirit/include/classic_confix.hpp> #include <boost/spirit/include/classic_escape_char.hpp> #include <boost/spirit/include/classic_multi_pass.hpp> #include <boost/spirit/include/classic_position_iterator.hpp> #define spirit_namespace boost::spirit::classic #else #include <boost/spirit/core.hpp> #include <boost/spirit/utility/confix.hpp> #include <boost/spirit/utility/escape_char.hpp> #include <boost/spirit/iterator/multi_pass.hpp> #include <boost/spirit/iterator/position_iterator.hpp> #define spirit_namespace boost::spirit #endif namespace json_spirit { const spirit_namespace::int_parser < boost::int64_t > int64_p = spirit_namespace::int_parser < boost::int64_t >(); const spirit_namespace::uint_parser< boost::uint64_t > uint64_p = spirit_namespace::uint_parser< boost::uint64_t >(); template< class Iter_type > bool is_eq( Iter_type first, Iter_type last, const char* c_str ) { for( Iter_type i = first; i != last; ++i, ++c_str ) { if( *c_str == 0 ) return false; if( *i != *c_str ) return false; } return true; } template< class Char_type > Char_type hex_to_num( const Char_type c ) { if( ( c >= '0' ) && ( c <= '9' ) ) return c - '0'; if( ( c >= 'a' ) && ( c <= 'f' ) ) return c - 'a' + 10; if( ( c >= 'A' ) && ( c <= 'F' ) ) return c - 'A' + 10; return 0; } template< class Char_type, class Iter_type > Char_type hex_str_to_char( Iter_type& begin ) { const Char_type c1( *( ++begin ) ); const Char_type c2( *( ++begin ) ); return ( hex_to_num( c1 ) << 4 ) + hex_to_num( c2 ); } template< class Char_type, class Iter_type > Char_type unicode_str_to_char( Iter_type& begin ) { const Char_type c1( *( ++begin ) ); const Char_type c2( *( ++begin ) ); const Char_type c3( *( ++begin ) ); const Char_type c4( *( ++begin ) ); return ( hex_to_num( c1 ) << 12 ) + ( hex_to_num( c2 ) << 8 ) + ( hex_to_num( c3 ) << 4 ) + hex_to_num( c4 ); } template< class String_type > void append_esc_char_and_incr_iter( String_type& s, typename String_type::const_iterator& begin, typename String_type::const_iterator end ) { typedef typename String_type::value_type Char_type; const Char_type c2( *begin ); switch( c2 ) { case 't': s += '\t'; break; case 'b': s += '\b'; break; case 'f': s += '\f'; break; case 'n': s += '\n'; break; case 'r': s += '\r'; break; case '\\': s += '\\'; break; case '/': s += '/'; break; case '"': s += '"'; break; case 'x': { if( end - begin >= 3 ) // expecting "xHH..." { s += hex_str_to_char< Char_type >( begin ); } break; } case 'u': { if( end - begin >= 5 ) // expecting "uHHHH..." { s += unicode_str_to_char< Char_type >( begin ); } break; } } } template< class String_type > String_type substitute_esc_chars( typename String_type::const_iterator begin, typename String_type::const_iterator end ) { typedef typename String_type::const_iterator Iter_type; if( end - begin < 2 ) return String_type( begin, end ); String_type result; result.reserve( end - begin ); const Iter_type end_minus_1( end - 1 ); Iter_type substr_start = begin; Iter_type i = begin; for( ; i < end_minus_1; ++i ) { if( *i == '\\' ) { result.append( substr_start, i ); ++i; // skip the '\' append_esc_char_and_incr_iter( result, i, end ); substr_start = i + 1; } } result.append( substr_start, end ); return result; } template< class String_type > String_type get_str_( typename String_type::const_iterator begin, typename String_type::const_iterator end ) { assert( end - begin >= 2 ); typedef typename String_type::const_iterator Iter_type; Iter_type str_without_quotes( ++begin ); Iter_type end_without_quotes( --end ); return substitute_esc_chars< String_type >( str_without_quotes, end_without_quotes ); } inline std::string get_str( std::string::const_iterator begin, std::string::const_iterator end ) { return get_str_< std::string >( begin, end ); } inline std::wstring get_str( std::wstring::const_iterator begin, std::wstring::const_iterator end ) { return get_str_< std::wstring >( begin, end ); } template< class String_type, class Iter_type > String_type get_str( Iter_type begin, Iter_type end ) { const String_type tmp( begin, end ); // convert multipass iterators to string iterators return get_str( tmp.begin(), tmp.end() ); } // this class's methods get called by the spirit parse resulting // in the creation of a JSON object or array // // NB Iter_type could be a std::string iterator, wstring iterator, a position iterator or a multipass iterator // template< class Value_type, class Iter_type > class Semantic_actions { public: typedef typename Value_type::Config_type Config_type; typedef typename Config_type::String_type String_type; typedef typename Config_type::Object_type Object_type; typedef typename Config_type::Array_type Array_type; typedef typename String_type::value_type Char_type; Semantic_actions( Value_type& value ) : value_( value ) , current_p_( 0 ) { } void begin_obj( Char_type c ) { assert( c == '{' ); begin_compound< Object_type >(); } void end_obj( Char_type c ) { assert( c == '}' ); end_compound(); } void begin_array( Char_type c ) { assert( c == '[' ); begin_compound< Array_type >(); } void end_array( Char_type c ) { assert( c == ']' ); end_compound(); } void new_name( Iter_type begin, Iter_type end ) { assert( current_p_->type() == obj_type ); name_ = get_str< String_type >( begin, end ); } void new_str( Iter_type begin, Iter_type end ) { add_to_current( get_str< String_type >( begin, end ) ); } void new_true( Iter_type begin, Iter_type end ) { assert( is_eq( begin, end, "true" ) ); add_to_current( true ); } void new_false( Iter_type begin, Iter_type end ) { assert( is_eq( begin, end, "false" ) ); add_to_current( false ); } void new_null( Iter_type begin, Iter_type end ) { assert( is_eq( begin, end, "null" ) ); add_to_current( Value_type() ); } void new_int( boost::int64_t i ) { add_to_current( i ); } void new_uint64( boost::uint64_t ui ) { add_to_current( ui ); } void new_real( double d ) { add_to_current( d ); } private: Semantic_actions& operator=( const Semantic_actions& ); // to prevent "assignment operator could not be generated" warning Value_type* add_first( const Value_type& value ) { assert( current_p_ == 0 ); value_ = value; current_p_ = &value_; return current_p_; } template< class Array_or_obj > void begin_compound() { if( current_p_ == 0 ) { add_first( Array_or_obj() ); } else { stack_.push_back( current_p_ ); Array_or_obj new_array_or_obj; // avoid copy by building new array or object in place current_p_ = add_to_current( new_array_or_obj ); } } void end_compound() { if( current_p_ != &value_ ) { current_p_ = stack_.back(); stack_.pop_back(); } } Value_type* add_to_current( const Value_type& value ) { if( current_p_ == 0 ) { return add_first( value ); } else if( current_p_->type() == array_type ) { current_p_->get_array().push_back( value ); return &current_p_->get_array().back(); } assert( current_p_->type() == obj_type ); return &Config_type::add( current_p_->get_obj(), name_, value ); } Value_type& value_; // this is the object or array that is being created Value_type* current_p_; // the child object or array that is currently being constructed std::vector< Value_type* > stack_; // previous child objects and arrays String_type name_; // of current name/value pair }; template< typename Iter_type > void throw_error( spirit_namespace::position_iterator< Iter_type > i, const std::string& reason ) { throw Error_position( i.get_position().line, i.get_position().column, reason ); } template< typename Iter_type > void throw_error( Iter_type i, const std::string& reason ) { throw reason; } // the spirit grammer // template< class Value_type, class Iter_type > class Json_grammer : public spirit_namespace::grammar< Json_grammer< Value_type, Iter_type > > { public: typedef Semantic_actions< Value_type, Iter_type > Semantic_actions_t; Json_grammer( Semantic_actions_t& semantic_actions ) : actions_( semantic_actions ) { } static void throw_not_value( Iter_type begin, Iter_type end ) { throw_error( begin, "not a value" ); } static void throw_not_array( Iter_type begin, Iter_type end ) { throw_error( begin, "not an array" ); } static void throw_not_object( Iter_type begin, Iter_type end ) { throw_error( begin, "not an object" ); } static void throw_not_pair( Iter_type begin, Iter_type end ) { throw_error( begin, "not a pair" ); } static void throw_not_colon( Iter_type begin, Iter_type end ) { throw_error( begin, "no colon in pair" ); } static void throw_not_string( Iter_type begin, Iter_type end ) { throw_error( begin, "not a string" ); } template< typename ScannerT > class definition { public: definition( const Json_grammer& self ) { using namespace spirit_namespace; typedef typename Value_type::String_type::value_type Char_type; // first we convert the semantic action class methods to functors with the // parameter signature expected by spirit typedef boost::function< void( Char_type ) > Char_action; typedef boost::function< void( Iter_type, Iter_type ) > Str_action; typedef boost::function< void( double ) > Real_action; typedef boost::function< void( boost::int64_t ) > Int_action; typedef boost::function< void( boost::uint64_t ) > Uint64_action; Char_action begin_obj ( boost::bind( &Semantic_actions_t::begin_obj, &self.actions_, _1 ) ); Char_action end_obj ( boost::bind( &Semantic_actions_t::end_obj, &self.actions_, _1 ) ); Char_action begin_array( boost::bind( &Semantic_actions_t::begin_array, &self.actions_, _1 ) ); Char_action end_array ( boost::bind( &Semantic_actions_t::end_array, &self.actions_, _1 ) ); Str_action new_name ( boost::bind( &Semantic_actions_t::new_name, &self.actions_, _1, _2 ) ); Str_action new_str ( boost::bind( &Semantic_actions_t::new_str, &self.actions_, _1, _2 ) ); Str_action new_true ( boost::bind( &Semantic_actions_t::new_true, &self.actions_, _1, _2 ) ); Str_action new_false ( boost::bind( &Semantic_actions_t::new_false, &self.actions_, _1, _2 ) ); Str_action new_null ( boost::bind( &Semantic_actions_t::new_null, &self.actions_, _1, _2 ) ); Real_action new_real ( boost::bind( &Semantic_actions_t::new_real, &self.actions_, _1 ) ); Int_action new_int ( boost::bind( &Semantic_actions_t::new_int, &self.actions_, _1 ) ); Uint64_action new_uint64 ( boost::bind( &Semantic_actions_t::new_uint64, &self.actions_, _1 ) ); // actual grammer json_ = value_ | eps_p[ &throw_not_value ] ; value_ = string_[ new_str ] | number_ | object_ | array_ | str_p( "true" ) [ new_true ] | str_p( "false" )[ new_false ] | str_p( "null" ) [ new_null ] ; object_ = ch_p('{')[ begin_obj ] >> !members_ >> ( ch_p('}')[ end_obj ] | eps_p[ &throw_not_object ] ) ; members_ = pair_ >> *( ',' >> pair_ ) ; pair_ = string_[ new_name ] >> ( ':' | eps_p[ &throw_not_colon ] ) >> ( value_ | eps_p[ &throw_not_value ] ) ; array_ = ch_p('[')[ begin_array ] >> !elements_ >> ( ch_p(']')[ end_array ] | eps_p[ &throw_not_array ] ) ; elements_ = value_ >> *( ',' >> value_ ) ; string_ = lexeme_d // this causes white space inside a string to be retained [ confix_p ( '"', *lex_escape_ch_p, '"' ) ] ; number_ = strict_real_p[ new_real ] | int64_p [ new_int ] | uint64_p [ new_uint64 ] ; } spirit_namespace::rule< ScannerT > json_, object_, members_, pair_, array_, elements_, value_, string_, number_; const spirit_namespace::rule< ScannerT >& start() const { return json_; } }; private: Json_grammer& operator=( const Json_grammer& ); // to prevent "assignment operator could not be generated" warning Semantic_actions_t& actions_; }; template< class Iter_type, class Value_type > Iter_type read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value ) { Semantic_actions< Value_type, Iter_type > semantic_actions( value ); const spirit_namespace::parse_info< Iter_type > info = spirit_namespace::parse( begin, end, Json_grammer< Value_type, Iter_type >( semantic_actions ), spirit_namespace::space_p ); if( !info.hit ) { assert( false ); // in theory exception should already have been thrown throw_error( info.stop, "error" ); } return info.stop; } template< class Iter_type, class Value_type > void add_posn_iter_and_read_range_or_throw( Iter_type begin, Iter_type end, Value_type& value ) { typedef spirit_namespace::position_iterator< Iter_type > Posn_iter_t; const Posn_iter_t posn_begin( begin, end ); const Posn_iter_t posn_end( end, end ); read_range_or_throw( posn_begin, posn_end, value ); } template< class Iter_type, class Value_type > bool read_range( Iter_type& begin, Iter_type end, Value_type& value ) { try { begin = read_range_or_throw( begin, end, value ); return true; } catch( ... ) { return false; } } template< class String_type, class Value_type > void read_string_or_throw( const String_type& s, Value_type& value ) { add_posn_iter_and_read_range_or_throw( s.begin(), s.end(), value ); } template< class String_type, class Value_type > bool read_string( const String_type& s, Value_type& value ) { typename String_type::const_iterator begin = s.begin(); return read_range( begin, s.end(), value ); } template< class Istream_type > struct Multi_pass_iters { typedef typename Istream_type::char_type Char_type; typedef std::istream_iterator< Char_type, Char_type > istream_iter; typedef spirit_namespace::multi_pass< istream_iter > Mp_iter; Multi_pass_iters( Istream_type& is ) { is.unsetf( std::ios::skipws ); begin_ = spirit_namespace::make_multi_pass( istream_iter( is ) ); end_ = spirit_namespace::make_multi_pass( istream_iter() ); } Mp_iter begin_; Mp_iter end_; }; template< class Istream_type, class Value_type > bool read_stream( Istream_type& is, Value_type& value ) { Multi_pass_iters< Istream_type > mp_iters( is ); return read_range( mp_iters.begin_, mp_iters.end_, value ); } template< class Istream_type, class Value_type > void read_stream_or_throw( Istream_type& is, Value_type& value ) { const Multi_pass_iters< Istream_type > mp_iters( is ); add_posn_iter_and_read_range_or_throw( mp_iters.begin_, mp_iters.end_, value ); } } #endif
{ "pile_set_name": "Github" }
/*container*/ #ym-window{ background:#fff;overflow:hidden; font-size:12px;font-family:'宋体' } .ym-tl{padding-left:3px;background:#333 url(images/title_bg_left.gif) no-repeat 0 0} .ym-tr{padding-right:3px;background:#333 url(images/title_bg_right.gif) no-repeat right 0;} .ym-tc{background:#333 url(images/title_bg_center.gif) repeat-x 0 0;overflow:hidden;height:25px;line-height:25px;} .ym-ttc{height:3px} .ym-header-text{font-size:12px;font-weight:bold;color:#fff;margin-left:5px;float:left} .ym-header-tools{float:right;margin-top:5px} /*body*/ .ym-ml{background:#5F5F68;padding-left:2px} .ym-mr{background:#5F5F68;padding-right:2px} .ym-mc{background:#fff;padding:0} .ym-body{overflow:auto;padding:0;font-size:12px;} .ym-header-tools strong{display:none} /*button*/ .ym-btn{text-align:center;background:#fff;} /*footer*/ .ym-bl{background:#5F5F68;padding-left:2px} .ym-br{background:#5F5F68;padding-right:2px} .ym-bc{background:#5F5F68;height:2px;font-size:2px} .ymPrompt_alert{ padding-left:90px; background:url(images/info.gif) no-repeat 20px 50% } .ymPrompt_succeed{ padding-left:90px; background:url(images/right.gif) no-repeat 20px 50% } .ymPrompt_error{ padding-left:90px; background:url(images/err.gif) no-repeat 20px 50% } .ymPrompt_confirm{ padding-left:90px; background:url(images/ask.gif) no-repeat 20px 50% } .ymPrompt_alert .ym-content,.ymPrompt_succeed .ym-content,.ymPrompt_error .ym-content,.ymPrompt_confirm .ym-content{padding:50px 3px 0} /*图标公共定义*/ .ym-header-tools div{ cursor:pointer; width:15px;height:15px;float:left;margin:0 1px; background:url(images/ico.gif) no-repeat 0 0; } .ymPrompt_close{ background-position:-45px 0 !important; } .ymPrompt_max{ background-position:0 0 !important; } .ymPrompt_min{ background-position:-30px 0 !important; } .ymPrompt_normal{ background-position:-15px 0 !important; } /*取消确认按钮样式*/ input.btnStyle{ background:url(images/btn_bg.gif) no-repeat; width:80px;height:21px;line-height:21px; font-size:12px;color:#fff;border:0;margin:10px 0 }
{ "pile_set_name": "Github" }
package com.planet_ink.coffee_mud.WebMacros; import com.planet_ink.coffee_web.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2006-2020 Bo Zimmerman 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. */ public class FactionID extends StdWebMacro { @Override public String name() { return "FactionID"; } @Override public String runMacro(final HTTPRequest httpReq, final String parm, final HTTPResponse httpResp) { final java.util.Map<String,String> parms=parseParms(parm); String last=httpReq.getUrlParameter("FACTION"); if(last==null) { if(parms.containsKey("FACTION")) last=parms.get("FACTION"); if(last == null) return " @break@"; } if(last.length()>0) return clearWebMacros(last); return ""; } }
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * Driver for TI TPS6598x USB Power Delivery controller family * * Copyright (C) 2017, Intel Corporation * Author: Heikki Krogerus <[email protected]> */ #include <linux/i2c.h> #include <linux/acpi.h> #include <linux/module.h> #include <linux/regmap.h> #include <linux/interrupt.h> #include <linux/usb/typec.h> /* Register offsets */ #define TPS_REG_VID 0x00 #define TPS_REG_MODE 0x03 #define TPS_REG_CMD1 0x08 #define TPS_REG_DATA1 0x09 #define TPS_REG_INT_EVENT1 0x14 #define TPS_REG_INT_EVENT2 0x15 #define TPS_REG_INT_MASK1 0x16 #define TPS_REG_INT_MASK2 0x17 #define TPS_REG_INT_CLEAR1 0x18 #define TPS_REG_INT_CLEAR2 0x19 #define TPS_REG_STATUS 0x1a #define TPS_REG_SYSTEM_CONF 0x28 #define TPS_REG_CTRL_CONF 0x29 #define TPS_REG_POWER_STATUS 0x3f #define TPS_REG_RX_IDENTITY_SOP 0x48 /* TPS_REG_INT_* bits */ #define TPS_REG_INT_PLUG_EVENT BIT(3) /* TPS_REG_STATUS bits */ #define TPS_STATUS_PLUG_PRESENT BIT(0) #define TPS_STATUS_ORIENTATION BIT(4) #define TPS_STATUS_PORTROLE(s) (!!((s) & BIT(5))) #define TPS_STATUS_DATAROLE(s) (!!((s) & BIT(6))) #define TPS_STATUS_VCONN(s) (!!((s) & BIT(7))) /* TPS_REG_SYSTEM_CONF bits */ #define TPS_SYSCONF_PORTINFO(c) ((c) & 7) enum { TPS_PORTINFO_SINK, TPS_PORTINFO_SINK_ACCESSORY, TPS_PORTINFO_DRP_UFP, TPS_PORTINFO_DRP_UFP_DRD, TPS_PORTINFO_DRP_DFP, TPS_PORTINFO_DRP_DFP_DRD, TPS_PORTINFO_SOURCE, }; /* TPS_REG_POWER_STATUS bits */ #define TPS_POWER_STATUS_SOURCESINK BIT(1) #define TPS_POWER_STATUS_PWROPMODE(p) (((p) & GENMASK(3, 2)) >> 2) /* TPS_REG_RX_IDENTITY_SOP */ struct tps6598x_rx_identity_reg { u8 status; struct usb_pd_identity identity; u32 vdo[3]; } __packed; /* Standard Task return codes */ #define TPS_TASK_TIMEOUT 1 #define TPS_TASK_REJECTED 3 enum { TPS_MODE_APP, TPS_MODE_BOOT, TPS_MODE_BIST, TPS_MODE_DISC, }; static const char *const modes[] = { [TPS_MODE_APP] = "APP ", [TPS_MODE_BOOT] = "BOOT", [TPS_MODE_BIST] = "BIST", [TPS_MODE_DISC] = "DISC", }; /* Unrecognized commands will be replaced with "!CMD" */ #define INVALID_CMD(_cmd_) (_cmd_ == 0x444d4321) struct tps6598x { struct device *dev; struct regmap *regmap; struct mutex lock; /* device lock */ u8 i2c_protocol:1; struct typec_port *port; struct typec_partner *partner; struct usb_pd_identity partner_identity; }; /* * Max data bytes for Data1, Data2, and other registers. See ch 1.3.2: * http://www.ti.com/lit/ug/slvuan1a/slvuan1a.pdf */ #define TPS_MAX_LEN 64 static int tps6598x_block_read(struct tps6598x *tps, u8 reg, void *val, size_t len) { u8 data[TPS_MAX_LEN + 1]; int ret; if (WARN_ON(len + 1 > sizeof(data))) return -EINVAL; if (!tps->i2c_protocol) return regmap_raw_read(tps->regmap, reg, val, len); ret = regmap_raw_read(tps->regmap, reg, data, sizeof(data)); if (ret) return ret; if (data[0] < len) return -EIO; memcpy(val, &data[1], len); return 0; } static int tps6598x_block_write(struct tps6598x *tps, u8 reg, const void *val, size_t len) { u8 data[TPS_MAX_LEN + 1]; if (!tps->i2c_protocol) return regmap_raw_write(tps->regmap, reg, val, len); data[0] = len; memcpy(&data[1], val, len); return regmap_raw_write(tps->regmap, reg, data, sizeof(data)); } static inline int tps6598x_read16(struct tps6598x *tps, u8 reg, u16 *val) { return tps6598x_block_read(tps, reg, val, sizeof(u16)); } static inline int tps6598x_read32(struct tps6598x *tps, u8 reg, u32 *val) { return tps6598x_block_read(tps, reg, val, sizeof(u32)); } static inline int tps6598x_read64(struct tps6598x *tps, u8 reg, u64 *val) { return tps6598x_block_read(tps, reg, val, sizeof(u64)); } static inline int tps6598x_write16(struct tps6598x *tps, u8 reg, u16 val) { return tps6598x_block_write(tps, reg, &val, sizeof(u16)); } static inline int tps6598x_write32(struct tps6598x *tps, u8 reg, u32 val) { return tps6598x_block_write(tps, reg, &val, sizeof(u32)); } static inline int tps6598x_write64(struct tps6598x *tps, u8 reg, u64 val) { return tps6598x_block_write(tps, reg, &val, sizeof(u64)); } static inline int tps6598x_write_4cc(struct tps6598x *tps, u8 reg, const char *val) { return tps6598x_block_write(tps, reg, val, 4); } static int tps6598x_read_partner_identity(struct tps6598x *tps) { struct tps6598x_rx_identity_reg id; int ret; ret = tps6598x_block_read(tps, TPS_REG_RX_IDENTITY_SOP, &id, sizeof(id)); if (ret) return ret; tps->partner_identity = id.identity; return 0; } static int tps6598x_connect(struct tps6598x *tps, u32 status) { struct typec_partner_desc desc; enum typec_pwr_opmode mode; u16 pwr_status; int ret; if (tps->partner) return 0; ret = tps6598x_read16(tps, TPS_REG_POWER_STATUS, &pwr_status); if (ret < 0) return ret; mode = TPS_POWER_STATUS_PWROPMODE(pwr_status); desc.usb_pd = mode == TYPEC_PWR_MODE_PD; desc.accessory = TYPEC_ACCESSORY_NONE; /* XXX: handle accessories */ desc.identity = NULL; if (desc.usb_pd) { ret = tps6598x_read_partner_identity(tps); if (ret) return ret; desc.identity = &tps->partner_identity; } typec_set_pwr_opmode(tps->port, mode); typec_set_pwr_role(tps->port, TPS_STATUS_PORTROLE(status)); typec_set_vconn_role(tps->port, TPS_STATUS_VCONN(status)); typec_set_data_role(tps->port, TPS_STATUS_DATAROLE(status)); tps->partner = typec_register_partner(tps->port, &desc); if (IS_ERR(tps->partner)) return PTR_ERR(tps->partner); if (desc.identity) typec_partner_set_identity(tps->partner); return 0; } static void tps6598x_disconnect(struct tps6598x *tps, u32 status) { if (!IS_ERR(tps->partner)) typec_unregister_partner(tps->partner); tps->partner = NULL; typec_set_pwr_opmode(tps->port, TYPEC_PWR_MODE_USB); typec_set_pwr_role(tps->port, TPS_STATUS_PORTROLE(status)); typec_set_vconn_role(tps->port, TPS_STATUS_VCONN(status)); typec_set_data_role(tps->port, TPS_STATUS_DATAROLE(status)); } static int tps6598x_exec_cmd(struct tps6598x *tps, const char *cmd, size_t in_len, u8 *in_data, size_t out_len, u8 *out_data) { unsigned long timeout; u32 val; int ret; ret = tps6598x_read32(tps, TPS_REG_CMD1, &val); if (ret) return ret; if (val && !INVALID_CMD(val)) return -EBUSY; if (in_len) { ret = tps6598x_block_write(tps, TPS_REG_DATA1, in_data, in_len); if (ret) return ret; } ret = tps6598x_write_4cc(tps, TPS_REG_CMD1, cmd); if (ret < 0) return ret; /* XXX: Using 1s for now, but it may not be enough for every command. */ timeout = jiffies + msecs_to_jiffies(1000); do { ret = tps6598x_read32(tps, TPS_REG_CMD1, &val); if (ret) return ret; if (INVALID_CMD(val)) return -EINVAL; if (time_is_before_jiffies(timeout)) return -ETIMEDOUT; } while (val); if (out_len) { ret = tps6598x_block_read(tps, TPS_REG_DATA1, out_data, out_len); if (ret) return ret; val = out_data[0]; } else { ret = tps6598x_block_read(tps, TPS_REG_DATA1, &val, sizeof(u8)); if (ret) return ret; } switch (val) { case TPS_TASK_TIMEOUT: return -ETIMEDOUT; case TPS_TASK_REJECTED: return -EPERM; default: break; } return 0; } static int tps6598x_dr_set(struct typec_port *port, enum typec_data_role role) { const char *cmd = (role == TYPEC_DEVICE) ? "SWUF" : "SWDF"; struct tps6598x *tps = typec_get_drvdata(port); u32 status; int ret; mutex_lock(&tps->lock); ret = tps6598x_exec_cmd(tps, cmd, 0, NULL, 0, NULL); if (ret) goto out_unlock; ret = tps6598x_read32(tps, TPS_REG_STATUS, &status); if (ret) goto out_unlock; if (role != TPS_STATUS_DATAROLE(status)) { ret = -EPROTO; goto out_unlock; } typec_set_data_role(tps->port, role); out_unlock: mutex_unlock(&tps->lock); return ret; } static int tps6598x_pr_set(struct typec_port *port, enum typec_role role) { const char *cmd = (role == TYPEC_SINK) ? "SWSk" : "SWSr"; struct tps6598x *tps = typec_get_drvdata(port); u32 status; int ret; mutex_lock(&tps->lock); ret = tps6598x_exec_cmd(tps, cmd, 0, NULL, 0, NULL); if (ret) goto out_unlock; ret = tps6598x_read32(tps, TPS_REG_STATUS, &status); if (ret) goto out_unlock; if (role != TPS_STATUS_PORTROLE(status)) { ret = -EPROTO; goto out_unlock; } typec_set_pwr_role(tps->port, role); out_unlock: mutex_unlock(&tps->lock); return ret; } static const struct typec_operations tps6598x_ops = { .dr_set = tps6598x_dr_set, .pr_set = tps6598x_pr_set, }; static irqreturn_t tps6598x_interrupt(int irq, void *data) { struct tps6598x *tps = data; u64 event1; u64 event2; u32 status; int ret; mutex_lock(&tps->lock); ret = tps6598x_read64(tps, TPS_REG_INT_EVENT1, &event1); ret |= tps6598x_read64(tps, TPS_REG_INT_EVENT2, &event2); if (ret) { dev_err(tps->dev, "%s: failed to read events\n", __func__); goto err_unlock; } ret = tps6598x_read32(tps, TPS_REG_STATUS, &status); if (ret) { dev_err(tps->dev, "%s: failed to read status\n", __func__); goto err_clear_ints; } /* Handle plug insert or removal */ if ((event1 | event2) & TPS_REG_INT_PLUG_EVENT) { if (status & TPS_STATUS_PLUG_PRESENT) { ret = tps6598x_connect(tps, status); if (ret) dev_err(tps->dev, "failed to register partner\n"); } else { tps6598x_disconnect(tps, status); } } err_clear_ints: tps6598x_write64(tps, TPS_REG_INT_CLEAR1, event1); tps6598x_write64(tps, TPS_REG_INT_CLEAR2, event2); err_unlock: mutex_unlock(&tps->lock); return IRQ_HANDLED; } static int tps6598x_check_mode(struct tps6598x *tps) { char mode[5] = { }; int ret; ret = tps6598x_read32(tps, TPS_REG_MODE, (void *)mode); if (ret) return ret; switch (match_string(modes, ARRAY_SIZE(modes), mode)) { case TPS_MODE_APP: return 0; case TPS_MODE_BOOT: dev_warn(tps->dev, "dead-battery condition\n"); return 0; case TPS_MODE_BIST: case TPS_MODE_DISC: default: dev_err(tps->dev, "controller in unsupported mode \"%s\"\n", mode); break; } return -ENODEV; } static const struct regmap_config tps6598x_regmap_config = { .reg_bits = 8, .val_bits = 8, .max_register = 0x7F, }; static int tps6598x_probe(struct i2c_client *client) { struct typec_capability typec_cap = { }; struct tps6598x *tps; u32 status; u32 conf; u32 vid; int ret; tps = devm_kzalloc(&client->dev, sizeof(*tps), GFP_KERNEL); if (!tps) return -ENOMEM; mutex_init(&tps->lock); tps->dev = &client->dev; tps->regmap = devm_regmap_init_i2c(client, &tps6598x_regmap_config); if (IS_ERR(tps->regmap)) return PTR_ERR(tps->regmap); ret = tps6598x_read32(tps, TPS_REG_VID, &vid); if (ret < 0 || !vid) return -ENODEV; /* * Checking can the adapter handle SMBus protocol. If it can not, the * driver needs to take care of block reads separately. * * FIXME: Testing with I2C_FUNC_I2C. regmap-i2c uses I2C protocol * unconditionally if the adapter has I2C_FUNC_I2C set. */ if (i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) tps->i2c_protocol = true; /* Make sure the controller has application firmware running */ ret = tps6598x_check_mode(tps); if (ret) return ret; ret = tps6598x_read32(tps, TPS_REG_STATUS, &status); if (ret < 0) return ret; ret = tps6598x_read32(tps, TPS_REG_SYSTEM_CONF, &conf); if (ret < 0) return ret; typec_cap.revision = USB_TYPEC_REV_1_2; typec_cap.pd_revision = 0x200; typec_cap.prefer_role = TYPEC_NO_PREFERRED_ROLE; typec_cap.driver_data = tps; typec_cap.ops = &tps6598x_ops; switch (TPS_SYSCONF_PORTINFO(conf)) { case TPS_PORTINFO_SINK_ACCESSORY: case TPS_PORTINFO_SINK: typec_cap.type = TYPEC_PORT_SNK; typec_cap.data = TYPEC_PORT_UFP; break; case TPS_PORTINFO_DRP_UFP_DRD: case TPS_PORTINFO_DRP_DFP_DRD: typec_cap.type = TYPEC_PORT_DRP; typec_cap.data = TYPEC_PORT_DRD; break; case TPS_PORTINFO_DRP_UFP: typec_cap.type = TYPEC_PORT_DRP; typec_cap.data = TYPEC_PORT_UFP; break; case TPS_PORTINFO_DRP_DFP: typec_cap.type = TYPEC_PORT_DRP; typec_cap.data = TYPEC_PORT_DFP; break; case TPS_PORTINFO_SOURCE: typec_cap.type = TYPEC_PORT_SRC; typec_cap.data = TYPEC_PORT_DFP; break; default: return -ENODEV; } tps->port = typec_register_port(&client->dev, &typec_cap); if (IS_ERR(tps->port)) return PTR_ERR(tps->port); if (status & TPS_STATUS_PLUG_PRESENT) { ret = tps6598x_connect(tps, status); if (ret) dev_err(&client->dev, "failed to register partner\n"); } ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, tps6598x_interrupt, IRQF_SHARED | IRQF_ONESHOT, dev_name(&client->dev), tps); if (ret) { tps6598x_disconnect(tps, 0); typec_unregister_port(tps->port); return ret; } i2c_set_clientdata(client, tps); return 0; } static int tps6598x_remove(struct i2c_client *client) { struct tps6598x *tps = i2c_get_clientdata(client); tps6598x_disconnect(tps, 0); typec_unregister_port(tps->port); return 0; } static const struct i2c_device_id tps6598x_id[] = { { "tps6598x" }, { } }; MODULE_DEVICE_TABLE(i2c, tps6598x_id); static struct i2c_driver tps6598x_i2c_driver = { .driver = { .name = "tps6598x", }, .probe_new = tps6598x_probe, .remove = tps6598x_remove, .id_table = tps6598x_id, }; module_i2c_driver(tps6598x_i2c_driver); MODULE_AUTHOR("Heikki Krogerus <[email protected]>"); MODULE_LICENSE("GPL v2"); MODULE_DESCRIPTION("TI TPS6598x USB Power Delivery Controller Driver");
{ "pile_set_name": "Github" }
#!/bin/bash set -e check_mandatory_flags() { if [ -z "$EXTERNAL_IP" ]; then echo "external ip not set, use the -e flag." >&2 usage exit 1 fi } setup_database() { set +e TIMEOUT=90 COUNT=0 RETRY=1 while [ $RETRY -ne 0 ]; do if [ "$COUNT" -ge "$TIMEOUT" ]; then printf " [FAIL]\n" echo "Timeout reached, exiting with error" exit 1 fi echo "Waiting for mariadb to be ready in 5 seconds" sleep 5 COUNT=$((COUNT+5)) printf "Portus: configuring database..." docker-compose run --rm web rake db:migrate:reset > /dev/null docker-compose run --rm web rake db:seed > /dev/null RETRY=$? if [ $RETRY -ne 0 ]; then printf " failed, will retry\n" fi done printf " [SUCCESS]\n" set -e } clean() { echo "The setup will destroy the containers used by Portus, removing also their volumes." if [ $FORCE -ne 1 ]; then while true; do read -p "Are you sure to delete all the data? (Y/N) [Y] " yn case $yn in [Yy]* ) break;; [Nn]* ) exit 1;; "" ) break;; * ) echo "Please answer yes or no.";; esac done fi docker-compose kill docker-compose rm -fv } usage() { echo "Usage: $0 [-fo] -e EXTERNAL_IP [-c REGISTRY_PORT]" echo " -f force removal of data" echo " -e EXTERNAL_IP - the IP or FQDN used to publish Portus and the Docker registry" echo " -c REGISTRY_PORT - the registry port. By default 5000" } # Force the current directory to be named "portus". It's known that other # setups will make docker-compose fail. # # See: https://github.com/docker/compose/issues/2092 if [ "${PWD##*/}" != "portus" ] && [ "${PWD##*/}" != "Portus" ]; then cat <<HERE ERROR: docker-compose is not able to tag built images. Since our compose setup expects the built image be named "portus_web", the current directory has to be named "portus" in order to work. HERE exit 1 fi FORCE=0 export REGISTRY_PORT=5000 while getopts "foe:hc:" opt; do case "${opt}" in f) FORCE=1 ;; e) export EXTERNAL_IP=$OPTARG ;; c) export REGISTRY_PORT=$OPTARG ;; h) usage exit 0 ;; *) echo "Invalid option: -$OPTARG" >&2 usage exit 1 ;; esac done cat <<EOM ########### # WARNING # ########### This deployment method is intended for testing/development purposes. To deploy Portus on production please take a look at: http://port.us.org/documentation.html EOM sleep 2 check_mandatory_flags clean docker-compose build docker-compose up -d setup_database cat <<EOM ################### # SUCCESS # ################### EOM echo "Make sure port 3000 and ${REGISTRY_PORT} are open on host ${EXTERNAL_IP}" printf "\n" echo "Open http://${EXTERNAL_IP}:3000 with your browser and perform the following steps:" printf "\n" echo " 1. Create an admin account" echo " 2. You will be redirected to a page where you have to register the registry. In this form:" echo " - Choose a custom name for the registry." echo " - Enter ${EXTERNAL_IP}:${REGISTRY_PORT} as the hostname." echo " - Do *not* check the \"Use SSL\" checkbox, since this setup is not using SSL." printf "\n" echo "Perform the following actions on the docker hosts that need to interact with your registry:" printf "\n" echo " - Ensure the docker daemon is started with the '--insecure-registry ${EXTERNAL_IP}:${REGISTRY_PORT}'" echo " - Perform the docker login." printf "\n" echo "To authenticate against your registry using the docker cli do:" printf "\n" echo " $ docker login -u <portus username> -p <password> -e <email> ${EXTERNAL_IP}:${REGISTRY_PORT}" printf "\n" echo "To push an image to the private registry:" printf "\n" echo " $ docker pull busybox" echo " $ docker tag busybox ${EXTERNAL_IP}:${REGISTRY_PORT}/<username>/busybox" echo " $ docker push ${EXTERNAL_IP}:${REGISTRY_PORT}/<username>/busybox"
{ "pile_set_name": "Github" }
# coding: utf-8 from __future__ import unicode_literals from fireworks.utilities.fw_serializers import FWSerializable, recursive_serialize, serialize_fw, \ recursive_deserialize __author__ = 'Anubhav Jain' __copyright__ = 'Copyright 2014, The Materials Project' __version__ = '0.1' __maintainer__ = 'Anubhav Jain' __email__ = '[email protected]' __date__ = 'Feb 10, 2014' class BackgroundTask(FWSerializable, object): _fw_name = 'BackgroundTask' def __init__(self, tasks, num_launches=0, sleep_time=60, run_on_finish=False): """ Args: tasks [Firetask]: a list of Firetasks to perform num_launches (int): the total number of times to run the process (0=infinite) sleep_time (int): sleep time in seconds between background runs run_on_finish (bool): always run this task upon completion of Firework """ self.tasks = tasks if isinstance(tasks, (list, tuple)) else [tasks] self.num_launches = num_launches self.sleep_time = sleep_time self.run_on_finish = run_on_finish @recursive_serialize @serialize_fw def to_dict(self): return {'tasks': self.tasks, 'num_launches': self.num_launches, 'sleep_time': self.sleep_time, 'run_on_finish': self.run_on_finish} @classmethod @recursive_deserialize def from_dict(cls, m_dict): return BackgroundTask(m_dict['tasks'], m_dict['num_launches'], m_dict['sleep_time'], m_dict['run_on_finish'])
{ "pile_set_name": "Github" }
fixes: - | Use SHA256 for comparing file contents instead of MD5. This improves FIPS compatibility.
{ "pile_set_name": "Github" }
/** * err.c * * Contains a formal API to create, initialize, get, reset, and free errors * among different backends. */ #include "err.h" #include "assert.h" #include "redismodule.h" #include "stdlib.h" #include "string.h" char *RAI_Chomp(const char *src) { char *str = RedisModule_Strdup(src); size_t len = strlen(src); for (size_t i = 0; i < len; i++) { if (str[i] == '\n' || str[i] == '\r') { str[i] = ' '; } } return str; } const char* RAI_GetError(RAI_Error *err) { return err->detail; } const char* RAI_GetErrorOneLine(RAI_Error *err) { return err->detail_oneline; } RAI_ErrorCode RAI_GetErrorCode(RAI_Error *err) { return err->code; } void RAI_SetError(RAI_Error *err, RAI_ErrorCode code, const char *detail) { if(!err){ return; } if (err->code != RAI_OK) { return; } assert(!err->detail); err->code = code; if (detail) { err->detail = RedisModule_Strdup(detail); } else { err->detail = RedisModule_Strdup("ERR Generic error"); } err->detail_oneline = RAI_Chomp(err->detail); } /** * Allocate the memory and initialise the RAI_Error. * @param result Output parameter to capture allocated RAI_Error. * @return 0 on success, or 1 if the allocation * failed. */ int RAI_InitError(RAI_Error **result) { RAI_Error *err; err = (RAI_Error *)RedisModule_Calloc(1, sizeof(RAI_Error)); if (!err) { return 1; } err->code = 0; err->detail = NULL; err->detail_oneline = NULL; *result = err; return 0; } void RAI_ClearError(RAI_Error *err) { if (err) { if (err->detail) { RedisModule_Free(err->detail); err->detail = NULL; } if (err->detail_oneline) { RedisModule_Free(err->detail_oneline); err->detail_oneline = NULL; } err->code = RAI_OK; } } void RAI_FreeError(RAI_Error *err) { if (err) { RAI_ClearError(err); RedisModule_Free(err); } }
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Version: 2.1.0\n", "Eager mode: True\n", "Hub version: 0.7.0\n", "GPU is NOT AVAILABLE\n" ] } ], "source": [ "import numpy as np\n", "import tensorflow as tf\n", "import tensorflow_hub as hub\n", "import tensorflow_datasets as tfds\n", "\n", "print(\"Version: \", tf.__version__)\n", "print(\"Eager mode: \", tf.executing_eagerly())\n", "print(\"Hub version: \", hub.__version__)\n", "print(\"GPU is\", \"available\" if tf.config.experimental.list_physical_devices(\"GPU\") else \"NOT AVAILABLE\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# 将训练集按照 6:4 的比例进行切割,从而最终我们将得到 15,000\n", "# 个训练样本, 10,000 个验证样本以及 25,000 个测试样本\n", "(train_data, validation_data, test_data) = tfds.load(\n", " name=\"imdb_reviews\",\n", " split=('train[:60%]', 'train[60%:]', 'test'),\n", " as_supervised=True)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<tf.Tensor: shape=(10,), dtype=string, numpy=\n", "array([b'This is a big step down after the surprisingly enjoyable original. This sequel isn\\'t nearly as fun as part one, and it instead spends too much time on plot development. Tim Thomerson is still the best thing about this series, but his wisecracking is toned down in this entry. The performances are all adequate, but this time the script lets us down. The action is merely routine and the plot is only mildly interesting, so I need lots of silly laughs in order to stay entertained during a \"Trancers\" movie. Unfortunately, the laughs are few and far between, and so, this film is watchable at best.',\n", " b\"Perhaps because I was so young, innocent and BRAINWASHED when I saw it, this movie was the cause of many sleepless nights for me. I haven't seen it since I was in seventh grade at a Presbyterian school, so I am not sure what effect it would have on me now. However, I will say that it left an impression on me... and most of my friends. It did serve its purpose, at least until we were old enough and knowledgeable enough to analyze and create our own opinions. I was particularly terrified of what the newly-converted post-rapture Christians had to endure when not receiving the mark of the beast. I don't want to spoil the movie for those who haven't seen it so I will not mention details of the scenes, but I can still picture them in my head... and it's been 19 years.\",\n", " b'Hood of the Living Dead had a lot to live up to even before the opening credits began. First, any play on \"...of the living dead\" invokes His Holiness Mr. Romero and instantly sets up a high standard to which many movies cannot afford to aspire. And second, my movie-watching companion professed doubt that any urban horror film would surpass the seminal Leprechaun In the Hood. Skeptical, we settled in to watch. <br /><br />We were rewarded with a surprisingly sincere and good-hearted zombie film. Oh, certainly the budget is low, and of course the directors\\' amateurs friends populate the cast, but Hood of the Living Dead loves zombie cinema. Cheap? Yeah. But when it\\'s this cheap, you can clearly see where LOVE holds it together. <br /><br />Ricky works in a lab during the day and as a surrogate parent to his younger brother at night. He dreams of moving out of Oakland. Before this planned escape, however, his brother is shot to death in a drive-by. Ricky\\'s keen scientific mind presents an option superior to CPR or 911: injections of his lab\\'s experimental regenerative formula. Sadly, little bro wakes up in an ambulance as a bloodthirsty Oakland zombie! Chaos and mayhem! I think it\\'s more economical to eat your enemies than take vengeance in a drive-by, but then again, I\\'m a poor judge of the complexities of urban life. (How poor a judge? In response to a gory scene involving four men, I opined \"Ah-ha! White t-shirts on everyone so the blood shows up. Economical! I used the same technique in my own low-budget horror film.\" Jordan replied, \"No, that\\'s gang dress. White t-shirts were banned from New Orleans bars for a time as a result.\" Oh.)<br /><br />A lot of the movie is set in someone\\'s living room, so there\\'s a great deal of hanging out and waiting for the zombies. But the characters are sympathetic and the movie is sincere-- it surpasses its budget in spirit. <br /><br />Zombie explanation: When man plays God, zombies arise! Or, perhaps: Follow FDA-approved testing rules before human experimentation! <br /><br />Contribution to the zombie canon: This is the first zombie movie I\\'ve seen with a drive-by shooting. As far as the actual zombies go, infection is spread with a bite as usual, but quite unusually head shots don\\'t work-- it\\'s heart shots that kill. Zombies have pulses, the absence of which proves true death. And these zombies make pretty cool jaguar-growl noises. <br /><br />Gratuitous zombie movie in-joke: A mercenary named Romero. Groan. <br /><br />Favorite zombie: Jaguar-noise little brother zombie, of course!',\n", " b\"For me this is a story that starts with some funny jokes regarding Franks fanatasies when he is travelling with a staircase and when he is sitting in business meetings... The problem is that when you have been watching this movie for an hour you will see the same fantasies/funny situations again and again and again. It is to predictable. It is more done as a TV story where you can go away and come back without missing anything.<br /><br />I like Felix Herngren as Frank but that is not enough even when it is a comedy it has to have more variations and some kind of message to it's audience....<br /><br />\",\n", " b'This is not a bad movie. It follows the new conventions of modern horror, that is the movie within a movie, the well known actress running for her life in the first scene. This movie takes the old convention of a psycho killer on he loose, and manage to do something new, and interesting with it. It is also always nice to see Molly Ringwald back for the attack.<br /><br />So this might be an example of what the genre has become. Cut hits all the marks, and is actually scary in some parts. I liked it I gave it an eight.',\n", " b\"I just finished a marathon of this series, and it became agonising to watch as it progressed. From the fictionalising of the historical elements, to O'Herlihy's awful accent in later episodes, the show just slumps the further it goes. If you are looking for some low quality production generalised WW2 fluff, then I could recommend season 1, but avoid anything after that, it degenerates into being one step from a soap opera, with increasingly worse story lines and sensibility.<br /><br />The old B&W film is by far the best of any form of entertainment with the Colditz name attached to it, and even that is not what one could hope for.\",\n", " b'I am very sorry that this charming and whimsical film (which I first saw soon after it was first released in the early fifties) has had such a poor reception more recently. In my opinion it has been greatly underrated - but perhaps it appeals more to the European sense of humour than to (for example) the American: maybe we in Europe can understand and appreciate its subtleties and situations more, since we are closer to some of them in real life! Particular mention should be made of the limited but good music - especially the catchy and memorable song \"It\\'s a fine, fine night\", which was issued separately on an HMV 78rpm record (10 inch plum label, I think!) in the fifties. I would urge anyone interested to give it a try if you get the chance: you may have a pleasant surprise.',\n", " b\"Well i am going to go against the grain on this film so it seems. Being a self confessed horror fan I sat down to this not quite knowing what to expect. After 2 or 3 mins i actually found myself scared (quite rare). The film obviously has a small budget and is set around charing cross station but the films lack of money does not distract from the story. Yes the story is a bit far fetched and doesn't explain itself very well but THE CREEP is a class act and proceeds to slash and dismember anything that comes its way. MESSAGE FOR LADIES !!! THERE ARE CERTAIN PARTS OF THE FILM YOU SHOULD CLOSE YOUR EYES AT OR AT LEAST CROSS YOUR LEGS !! you will understand when you see it.<br /><br />All in all a good film and it makes a change to see a good slasher movie that actually scares\",\n", " b'Even 15 years after the end of the Vietnam war \"Jacknife\" came not too late or was even superfluous. It\\'s one of the few that try to deal with the second sad side of the war: The time after. Different from movies like \"Taxi driver\" or \"Rambo\" which use to present their main characters as broken heroes in a bad after war environment this movie allows the audience to face a different view on the Vietnam vets. Their development is shown very precisely before and especially after the war. The problems are obvious but in all this tragic there is always the feeling of some hope on the basis of love and friendship. \"Jacknife\" might be the quietest Vietnam movie ever but after almost 15 years this is really plausible and therefor justified. Moreover, it can make us believe that the war has not finished, yet; at least for some of us.<br /><br />The three main characters are amazing. De Niro has done one of his best jobs but Ed Harris is the star of this movie. Possibly,this was his best performance ever.',\n", " b'Before I explain the \"Alias\" comment let me say that \"The Desert Trail\" is bad even by the standards of westerns staring The Three Stooges. In fact it features Carmen Laroux as semi- bad girl Juanita, when you hear her Mexican accent you will immediately recognize her as Senorita Rita from the classic Stooge short \"Saved by the Belle\". <br /><br />In \"The Desert Trail\" John Wayne gets to play the Moe Howard character and Eddy Chandler gets to play Curly Howard. Like their Stooge counterparts a running gag throughout the 53- minute movie is Moe hitting Curly. Wayne\\'s character, a skirt chasing bully, is not very endearing, but is supposed to be the good guy. <br /><br />Playing a traveling rodeo cowboy Wayne holds up the rodeo box office at gunpoint and takes the prize money he would have won if the attendance proceeds had been good-the other riders have to settle for 25 cents on the dollar (actually even less after Wayne robs the box office). No explanation is given for Wayne\\'s ripping off the riders and still being considered the hero who gets the girl. <br /><br />Things get complicated at this point because the villain (Al Ferguson) and his sidekick Larry Fine (played by Paul Fix-who would go on to play Sheriff Micah on television\\'s \"The Rifleman\") see Wayne rob the box office and then steal the remainder of the money and kill the rodeo manager. Moe and Curly get blamed. <br /><br />So Moe and Curly move to another town to get away from the law and they change their names to Smith and Jones. Who do they meet first but their old friend Larry, whose sister becomes the 2nd half love interest (Senorita Rita is left behind it the old town and makes no further appearances in the movie). <br /><br />Larry\\'s sister is nicely played by a radiantly beautiful Mary Kornman (now grown up but in her younger days she was one of the original cast members of Hal Roach\\'s \"Our Gang\" shorts). Kornman is the main reason to watch the mega-lame western and her scenes with Moe and Curly are much better than any others in the production, as if they used an entirely different crew to film them. <br /><br />Even for 1935 the action sequences in this thing are extremely weak and the technical film- making is staggeringly bad. The two main chase scenes end with stock footage wide shots of a rider falling from a horse. Both times the editor cuts to a shot of one of the characters rolling on the ground, but there is no horse in the frame, the film stock is completely different, and the character has on different clothes than the stunt rider. There is liberal use of stock footage in other places, none of it even remotely convincing. <br /><br />One thing to watch for is a scene midway into the movie where Moe and Curly get on their horses and ride away (to screen right) from a cabin as the posse is galloping toward the cabin from the left. The cameraman follows the two stooges with a slow pan right and then does a whip pan to the left to reveal the approaching posse. Outside of home movies I have never seen anything like this, not because it is looks stupid (which it does) but because a competent director would never stage a scene in this manner. They would film the two riders leaving and then reposition the camera and film the posse approaching as a separate action. Or if they were feeling creative they would stage the sequence so the camera shows the riders in the foreground and the posse approaching in the background. <br /><br />Then again, what do I know? I\\'m only a child.'],\n", " dtype=object)>" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_examples_batch,train_labels_batch = next(iter(train_data.batch(10)))\n", "train_examples_batch" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<tf.Tensor: shape=(10,), dtype=int64, numpy=array([0, 0, 1, 0, 1, 0, 1, 1, 1, 0], dtype=int64)>" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_labels_batch" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<tf.Tensor: shape=(3, 20), dtype=float32, numpy=\n", "array([[ 2.209591 , -2.7093675 , 3.6802928 , -1.0291991 , -4.1671185 ,\n", " -2.4566064 , -2.2519937 , -0.36589956, 1.9485804 , -3.1104462 ,\n", " -2.4610963 , 1.3139242 , -0.9161584 , -0.16625322, -3.723651 ,\n", " 1.8498232 , 3.499562 , -1.2373022 , -2.8403084 , -1.213074 ],\n", " [ 1.9055302 , -4.11395 , 3.6038654 , 0.28555924, -4.658998 ,\n", " -5.5433393 , -3.2735848 , 1.9235417 , 3.8461034 , 1.5882455 ,\n", " -2.64167 , 0.76057523, -0.14820506, 0.9115291 , -6.45758 ,\n", " 2.3990374 , 5.0985413 , -3.2776263 , -3.2652326 , -1.2345369 ],\n", " [ 3.6510668 , -4.7066135 , 4.71003 , -1.7002777 , -3.7708545 ,\n", " -3.709126 , -4.222776 , 1.946586 , 6.1182513 , -2.7392752 ,\n", " -5.4384456 , 2.7078724 , -2.1263676 , -0.7084146 , -5.893995 ,\n", " 3.1602864 , 3.8389287 , -3.318196 , -5.1542974 , -2.4051712 ]],\n", " dtype=float32)>" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "embedding = \"https://hub.tensorflow.google.cn/google/tf2-preview/gnews-swivel-20dim/1\"\n", "hub_layer = hub.KerasLayer(embedding,input_shape=[],\n", " dtype=tf.string,trainable=True)\n", "hub_layer(train_examples_batch[:3])" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<tf.Tensor: shape=(), dtype=string, numpy=b'This is a big step down after the surprisingly enjoyable original. This sequel isn\\'t nearly as fun as part one, and it instead spends too much time on plot development. Tim Thomerson is still the best thing about this series, but his wisecracking is toned down in this entry. The performances are all adequate, but this time the script lets us down. The action is merely routine and the plot is only mildly interesting, so I need lots of silly laughs in order to stay entertained during a \"Trancers\" movie. Unfortunately, the laughs are few and far between, and so, this film is watchable at best.'>" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train_examples_batch[0]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"sequential\"\n", "_________________________________________________________________\n", "Layer (type) Output Shape Param # \n", "=================================================================\n", "keras_layer (KerasLayer) (None, 20) 400020 \n", "_________________________________________________________________\n", "dense (Dense) (None, 16) 336 \n", "_________________________________________________________________\n", "dense_1 (Dense) (None, 1) 17 \n", "=================================================================\n", "Total params: 400,373\n", "Trainable params: 400,373\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model = tf.keras.Sequential()\n", "model.add(hub_layer)\n", "model.add(tf.keras.layers.Dense(16,activation='relu'))\n", "model.add(tf.keras.layers.Dense(1,activation='sigmoid'))\n", "model.summary()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "model.compile(optimizer='adam',\n", " loss='binary_crossentropy',\n", " metrics=['accuracy'])" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/10\n", "30/30 [==============================].9851 - accuracy: 0.43 - 2s 769ms/step - loss: 0.9482 - accuracy: 0.452 - 2s 544ms/step - loss: 0.9236 - accuracy: 0.455 - 2s 429ms/step - loss: 0.9043 - accuracy: 0.466 - 2s 358ms/step - loss: 0.8790 - accuracy: 0.481 - 2s 313ms/step - loss: 0.8589 - accuracy: 0.488 - 2s 279ms/step - loss: 0.8437 - accuracy: 0.497 - 2s 257ms/step - loss: 0.8408 - accuracy: 0.497 - 2s 238ms/step - loss: 0.8337 - accuracy: 0.503 - 2s 222ms/step - loss: 0.8320 - accuracy: 0.502 - 2s 210ms/step - loss: 0.8285 - accuracy: 0.503 - 2s 200ms/step - loss: 0.8224 - accuracy: 0.510 - 2s 192ms/step - loss: 0.8172 - accuracy: 0.514 - 3s 184ms/step - loss: 0.8148 - accuracy: 0.517 - 3s 178ms/step - loss: 0.8104 - accuracy: 0.521 - 3s 172ms/step - loss: 0.8051 - accuracy: 0.524 - 3s 167ms/step - loss: 0.8016 - accuracy: 0.527 - 3s 162ms/step - loss: 0.7989 - accuracy: 0.528 - 3s 158ms/step - loss: 0.7974 - accuracy: 0.530 - 3s 154ms/step - loss: 0.7942 - accuracy: 0.531 - 3s 151ms/step - loss: 0.7912 - accuracy: 0.534 - 3s 148ms/step - loss: 0.7900 - accuracy: 0.536 - 3s 145ms/step - loss: 0.7874 - accuracy: 0.537 - 3s 143ms/step - loss: 0.7834 - accuracy: 0.540 - 4s 141ms/step - loss: 0.7815 - accuracy: 0.541 - 4s 139ms/step - loss: 0.7800 - accuracy: 0.541 - 4s 137ms/step - loss: 0.7770 - accuracy: 0.543 - 4s 135ms/step - loss: 0.7731 - accuracy: 0.546 - 4s 134ms/step - loss: 0.7719 - accuracy: 0.546 - 4s 131ms/step - loss: 0.7687 - accuracy: 0.546 - 6s 189ms/step - loss: 0.7687 - accuracy: 0.5469 - val_loss: 0.7085 - val_accuracy: 0.5714\n", "Epoch 2/10\n", "30/30 [==============================] - ETA: 14s - loss: 0.6609 - accuracy: 0.619 - ETA: 8s - loss: 0.6714 - accuracy: 0.616 - ETA: 6s - loss: 0.6718 - accuracy: 0.61 - ETA: 5s - loss: 0.6749 - accuracy: 0.61 - ETA: 4s - loss: 0.6796 - accuracy: 0.60 - ETA: 4s - loss: 0.6769 - accuracy: 0.60 - ETA: 3s - loss: 0.6783 - accuracy: 0.60 - ETA: 3s - loss: 0.6757 - accuracy: 0.60 - ETA: 3s - loss: 0.6755 - accuracy: 0.60 - ETA: 2s - loss: 0.6777 - accuracy: 0.60 - ETA: 2s - loss: 0.6778 - accuracy: 0.60 - ETA: 2s - loss: 0.6749 - accuracy: 0.60 - ETA: 2s - loss: 0.6738 - accuracy: 0.60 - ETA: 2s - loss: 0.6733 - accuracy: 0.60 - ETA: 1s - loss: 0.6716 - accuracy: 0.60 - ETA: 1s - loss: 0.6711 - accuracy: 0.60 - ETA: 1s - loss: 0.6687 - accuracy: 0.61 - ETA: 1s - loss: 0.6678 - accuracy: 0.61 - ETA: 1s - loss: 0.6688 - accuracy: 0.61 - ETA: 1s - loss: 0.6674 - accuracy: 0.61 - ETA: 1s - loss: 0.6669 - accuracy: 0.61 - ETA: 0s - loss: 0.6649 - accuracy: 0.61 - ETA: 0s - loss: 0.6644 - accuracy: 0.61 - ETA: 0s - loss: 0.6623 - accuracy: 0.61 - ETA: 0s - loss: 0.6623 - accuracy: 0.61 - ETA: 0s - loss: 0.6600 - accuracy: 0.61 - ETA: 0s - loss: 0.6588 - accuracy: 0.61 - ETA: 0s - loss: 0.6586 - accuracy: 0.62 - ETA: 0s - loss: 0.6572 - accuracy: 0.62 - 5s 158ms/step - loss: 0.6541 - accuracy: 0.6230 - val_loss: 0.6232 - val_accuracy: 0.6574\n", "Epoch 3/10\n", "30/30 [==============================] - ETA: 12s - loss: 0.6115 - accuracy: 0.656 - ETA: 7s - loss: 0.5992 - accuracy: 0.672 - ETA: 5s - loss: 0.6035 - accuracy: 0.67 - ETA: 4s - loss: 0.6043 - accuracy: 0.68 - ETA: 3s - loss: 0.6078 - accuracy: 0.67 - ETA: 3s - loss: 0.6055 - accuracy: 0.67 - ETA: 3s - loss: 0.6061 - accuracy: 0.67 - ETA: 2s - loss: 0.6089 - accuracy: 0.67 - ETA: 2s - loss: 0.6058 - accuracy: 0.68 - ETA: 2s - loss: 0.6049 - accuracy: 0.68 - ETA: 2s - loss: 0.6073 - accuracy: 0.68 - ETA: 2s - loss: 0.6072 - accuracy: 0.67 - ETA: 1s - loss: 0.6060 - accuracy: 0.67 - ETA: 1s - loss: 0.6032 - accuracy: 0.68 - ETA: 1s - loss: 0.6021 - accuracy: 0.68 - ETA: 1s - loss: 0.6000 - accuracy: 0.68 - ETA: 1s - loss: 0.5994 - accuracy: 0.68 - ETA: 1s - loss: 0.5967 - accuracy: 0.68 - ETA: 1s - loss: 0.5960 - accuracy: 0.68 - ETA: 1s - loss: 0.5974 - accuracy: 0.68 - ETA: 0s - loss: 0.5976 - accuracy: 0.68 - ETA: 0s - loss: 0.5979 - accuracy: 0.68 - ETA: 0s - loss: 0.5972 - accuracy: 0.68 - ETA: 0s - loss: 0.5961 - accuracy: 0.68 - ETA: 0s - loss: 0.5946 - accuracy: 0.68 - ETA: 0s - loss: 0.5939 - accuracy: 0.68 - ETA: 0s - loss: 0.5930 - accuracy: 0.68 - ETA: 0s - loss: 0.5920 - accuracy: 0.68 - ETA: 0s - loss: 0.5926 - accuracy: 0.68 - 4s 146ms/step - loss: 0.5934 - accuracy: 0.6870 - val_loss: 0.5732 - val_accuracy: 0.7055\n", "Epoch 4/10\n", "30/30 [==============================] - ETA: 13s - loss: 0.5350 - accuracy: 0.728 - ETA: 7s - loss: 0.5587 - accuracy: 0.702 - ETA: 5s - loss: 0.5628 - accuracy: 0.69 - ETA: 4s - loss: 0.5551 - accuracy: 0.70 - ETA: 4s - loss: 0.5595 - accuracy: 0.70 - ETA: 3s - loss: 0.5625 - accuracy: 0.70 - ETA: 3s - loss: 0.5610 - accuracy: 0.70 - ETA: 2s - loss: 0.5599 - accuracy: 0.71 - ETA: 2s - loss: 0.5549 - accuracy: 0.71 - ETA: 2s - loss: 0.5530 - accuracy: 0.71 - ETA: 2s - loss: 0.5535 - accuracy: 0.71 - ETA: 2s - loss: 0.5550 - accuracy: 0.71 - ETA: 1s - loss: 0.5570 - accuracy: 0.71 - ETA: 1s - loss: 0.5585 - accuracy: 0.71 - ETA: 1s - loss: 0.5573 - accuracy: 0.71 - ETA: 1s - loss: 0.5581 - accuracy: 0.71 - ETA: 1s - loss: 0.5575 - accuracy: 0.71 - ETA: 1s - loss: 0.5565 - accuracy: 0.71 - ETA: 1s - loss: 0.5570 - accuracy: 0.71 - ETA: 1s - loss: 0.5549 - accuracy: 0.71 - ETA: 0s - loss: 0.5542 - accuracy: 0.71 - ETA: 0s - loss: 0.5539 - accuracy: 0.71 - ETA: 0s - loss: 0.5527 - accuracy: 0.71 - ETA: 0s - loss: 0.5513 - accuracy: 0.71 - ETA: 0s - loss: 0.5512 - accuracy: 0.72 - ETA: 0s - loss: 0.5504 - accuracy: 0.72 - ETA: 0s - loss: 0.5493 - accuracy: 0.72 - ETA: 0s - loss: 0.5486 - accuracy: 0.72 - ETA: 0s - loss: 0.5482 - accuracy: 0.72 - 4s 146ms/step - loss: 0.5488 - accuracy: 0.7229 - val_loss: 0.5380 - val_accuracy: 0.7342\n", "Epoch 5/10\n", "30/30 [==============================] - ETA: 14s - loss: 0.5364 - accuracy: 0.726 - ETA: 8s - loss: 0.5486 - accuracy: 0.714 - ETA: 6s - loss: 0.5288 - accuracy: 0.73 - ETA: 5s - loss: 0.5266 - accuracy: 0.73 - ETA: 4s - loss: 0.5232 - accuracy: 0.73 - ETA: 3s - loss: 0.5210 - accuracy: 0.74 - ETA: 3s - loss: 0.5210 - accuracy: 0.74 - ETA: 3s - loss: 0.5172 - accuracy: 0.74 - ETA: 2s - loss: 0.5185 - accuracy: 0.74 - ETA: 2s - loss: 0.5176 - accuracy: 0.74 - ETA: 2s - loss: 0.5192 - accuracy: 0.74 - ETA: 2s - loss: 0.5162 - accuracy: 0.74 - ETA: 2s - loss: 0.5181 - accuracy: 0.74 - ETA: 1s - loss: 0.5167 - accuracy: 0.74 - ETA: 1s - loss: 0.5152 - accuracy: 0.74 - ETA: 1s - loss: 0.5144 - accuracy: 0.74 - ETA: 1s - loss: 0.5157 - accuracy: 0.74 - ETA: 1s - loss: 0.5142 - accuracy: 0.74 - ETA: 1s - loss: 0.5144 - accuracy: 0.74 - ETA: 1s - loss: 0.5137 - accuracy: 0.74 - ETA: 1s - loss: 0.5113 - accuracy: 0.75 - ETA: 0s - loss: 0.5118 - accuracy: 0.75 - ETA: 0s - loss: 0.5112 - accuracy: 0.75 - ETA: 0s - loss: 0.5107 - accuracy: 0.75 - ETA: 0s - loss: 0.5097 - accuracy: 0.75 - ETA: 0s - loss: 0.5093 - accuracy: 0.75 - ETA: 0s - loss: 0.5098 - accuracy: 0.75 - ETA: 0s - loss: 0.5101 - accuracy: 0.75 - ETA: 0s - loss: 0.5111 - accuracy: 0.75 - 5s 153ms/step - loss: 0.5093 - accuracy: 0.7531 - val_loss: 0.5084 - val_accuracy: 0.7525\n", "Epoch 6/10\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "30/30 [==============================] - ETA: 12s - loss: 0.5077 - accuracy: 0.757 - ETA: 7s - loss: 0.5012 - accuracy: 0.749 - ETA: 5s - loss: 0.4929 - accuracy: 0.76 - ETA: 4s - loss: 0.4887 - accuracy: 0.76 - ETA: 3s - loss: 0.4889 - accuracy: 0.76 - ETA: 3s - loss: 0.4858 - accuracy: 0.76 - ETA: 3s - loss: 0.4857 - accuracy: 0.76 - ETA: 2s - loss: 0.4867 - accuracy: 0.76 - ETA: 2s - loss: 0.4828 - accuracy: 0.77 - ETA: 2s - loss: 0.4838 - accuracy: 0.77 - ETA: 2s - loss: 0.4843 - accuracy: 0.76 - ETA: 2s - loss: 0.4855 - accuracy: 0.76 - ETA: 1s - loss: 0.4864 - accuracy: 0.76 - ETA: 1s - loss: 0.4855 - accuracy: 0.76 - ETA: 1s - loss: 0.4846 - accuracy: 0.76 - ETA: 1s - loss: 0.4825 - accuracy: 0.77 - ETA: 1s - loss: 0.4805 - accuracy: 0.77 - ETA: 1s - loss: 0.4812 - accuracy: 0.77 - ETA: 1s - loss: 0.4821 - accuracy: 0.77 - ETA: 1s - loss: 0.4822 - accuracy: 0.77 - ETA: 0s - loss: 0.4819 - accuracy: 0.77 - ETA: 0s - loss: 0.4811 - accuracy: 0.77 - ETA: 0s - loss: 0.4819 - accuracy: 0.77 - ETA: 0s - loss: 0.4817 - accuracy: 0.77 - ETA: 0s - loss: 0.4812 - accuracy: 0.77 - ETA: 0s - loss: 0.4801 - accuracy: 0.77 - ETA: 0s - loss: 0.4796 - accuracy: 0.77 - ETA: 0s - loss: 0.4789 - accuracy: 0.77 - ETA: 0s - loss: 0.4780 - accuracy: 0.77 - 4s 147ms/step - loss: 0.4759 - accuracy: 0.7775 - val_loss: 0.4823 - val_accuracy: 0.7705\n", "Epoch 7/10\n", "30/30 [==============================] - ETA: 13s - loss: 0.4508 - accuracy: 0.783 - ETA: 7s - loss: 0.4503 - accuracy: 0.790 - ETA: 5s - loss: 0.4502 - accuracy: 0.79 - ETA: 4s - loss: 0.4543 - accuracy: 0.78 - ETA: 3s - loss: 0.4502 - accuracy: 0.79 - ETA: 3s - loss: 0.4559 - accuracy: 0.78 - ETA: 3s - loss: 0.4555 - accuracy: 0.78 - ETA: 2s - loss: 0.4506 - accuracy: 0.79 - ETA: 2s - loss: 0.4545 - accuracy: 0.79 - ETA: 2s - loss: 0.4545 - accuracy: 0.79 - ETA: 2s - loss: 0.4552 - accuracy: 0.79 - ETA: 2s - loss: 0.4536 - accuracy: 0.79 - ETA: 1s - loss: 0.4545 - accuracy: 0.79 - ETA: 1s - loss: 0.4534 - accuracy: 0.79 - ETA: 1s - loss: 0.4544 - accuracy: 0.79 - ETA: 1s - loss: 0.4521 - accuracy: 0.79 - ETA: 1s - loss: 0.4517 - accuracy: 0.79 - ETA: 1s - loss: 0.4503 - accuracy: 0.79 - ETA: 1s - loss: 0.4502 - accuracy: 0.79 - ETA: 1s - loss: 0.4490 - accuracy: 0.79 - ETA: 0s - loss: 0.4480 - accuracy: 0.79 - ETA: 0s - loss: 0.4485 - accuracy: 0.79 - ETA: 0s - loss: 0.4483 - accuracy: 0.79 - ETA: 0s - loss: 0.4484 - accuracy: 0.79 - ETA: 0s - loss: 0.4484 - accuracy: 0.79 - ETA: 0s - loss: 0.4482 - accuracy: 0.79 - ETA: 0s - loss: 0.4474 - accuracy: 0.79 - ETA: 0s - loss: 0.4461 - accuracy: 0.80 - ETA: 0s - loss: 0.4468 - accuracy: 0.79 - 5s 151ms/step - loss: 0.4447 - accuracy: 0.8000 - val_loss: 0.4579 - val_accuracy: 0.7873\n", "Epoch 8/10\n", "30/30 [==============================] - ETA: 12s - loss: 0.4196 - accuracy: 0.812 - ETA: 7s - loss: 0.4302 - accuracy: 0.813 - ETA: 5s - loss: 0.4400 - accuracy: 0.80 - ETA: 4s - loss: 0.4384 - accuracy: 0.79 - ETA: 4s - loss: 0.4387 - accuracy: 0.79 - ETA: 3s - loss: 0.4339 - accuracy: 0.80 - ETA: 3s - loss: 0.4343 - accuracy: 0.80 - ETA: 3s - loss: 0.4296 - accuracy: 0.80 - ETA: 2s - loss: 0.4287 - accuracy: 0.80 - ETA: 2s - loss: 0.4279 - accuracy: 0.80 - ETA: 2s - loss: 0.4244 - accuracy: 0.81 - ETA: 2s - loss: 0.4235 - accuracy: 0.81 - ETA: 2s - loss: 0.4220 - accuracy: 0.81 - ETA: 1s - loss: 0.4225 - accuracy: 0.81 - ETA: 1s - loss: 0.4224 - accuracy: 0.81 - ETA: 1s - loss: 0.4227 - accuracy: 0.81 - ETA: 1s - loss: 0.4232 - accuracy: 0.81 - ETA: 1s - loss: 0.4224 - accuracy: 0.81 - ETA: 1s - loss: 0.4208 - accuracy: 0.81 - ETA: 1s - loss: 0.4214 - accuracy: 0.81 - ETA: 0s - loss: 0.4203 - accuracy: 0.81 - ETA: 0s - loss: 0.4195 - accuracy: 0.81 - ETA: 0s - loss: 0.4192 - accuracy: 0.81 - ETA: 0s - loss: 0.4197 - accuracy: 0.81 - ETA: 0s - loss: 0.4175 - accuracy: 0.81 - ETA: 0s - loss: 0.4178 - accuracy: 0.81 - ETA: 0s - loss: 0.4172 - accuracy: 0.81 - ETA: 0s - loss: 0.4175 - accuracy: 0.81 - ETA: 0s - loss: 0.4171 - accuracy: 0.81 - 5s 151ms/step - loss: 0.4157 - accuracy: 0.8177 - val_loss: 0.4345 - val_accuracy: 0.8008\n", "Epoch 9/10\n", "30/30 [==============================] - ETA: 12s - loss: 0.3931 - accuracy: 0.830 - ETA: 7s - loss: 0.3916 - accuracy: 0.835 - ETA: 5s - loss: 0.3920 - accuracy: 0.84 - ETA: 4s - loss: 0.3946 - accuracy: 0.83 - ETA: 3s - loss: 0.3942 - accuracy: 0.83 - ETA: 3s - loss: 0.3961 - accuracy: 0.83 - ETA: 3s - loss: 0.3935 - accuracy: 0.83 - ETA: 2s - loss: 0.3953 - accuracy: 0.83 - ETA: 2s - loss: 0.3997 - accuracy: 0.82 - ETA: 2s - loss: 0.3989 - accuracy: 0.83 - ETA: 2s - loss: 0.3979 - accuracy: 0.83 - ETA: 2s - loss: 0.3988 - accuracy: 0.83 - ETA: 1s - loss: 0.3992 - accuracy: 0.83 - ETA: 1s - loss: 0.3998 - accuracy: 0.83 - ETA: 1s - loss: 0.3978 - accuracy: 0.83 - ETA: 1s - loss: 0.3980 - accuracy: 0.82 - ETA: 1s - loss: 0.3969 - accuracy: 0.82 - ETA: 1s - loss: 0.3972 - accuracy: 0.82 - ETA: 1s - loss: 0.3968 - accuracy: 0.82 - ETA: 1s - loss: 0.3960 - accuracy: 0.83 - ETA: 0s - loss: 0.3937 - accuracy: 0.83 - ETA: 0s - loss: 0.3927 - accuracy: 0.83 - ETA: 0s - loss: 0.3921 - accuracy: 0.83 - ETA: 0s - loss: 0.3920 - accuracy: 0.83 - ETA: 0s - loss: 0.3908 - accuracy: 0.83 - ETA: 0s - loss: 0.3891 - accuracy: 0.83 - ETA: 0s - loss: 0.3891 - accuracy: 0.83 - ETA: 0s - loss: 0.3894 - accuracy: 0.83 - ETA: 0s - loss: 0.3887 - accuracy: 0.83 - 5s 152ms/step - loss: 0.3864 - accuracy: 0.8353 - val_loss: 0.4149 - val_accuracy: 0.8125\n", "Epoch 10/10\n", "30/30 [==============================] - ETA: 11s - loss: 0.3769 - accuracy: 0.837 - ETA: 6s - loss: 0.3819 - accuracy: 0.828 - ETA: 5s - loss: 0.3811 - accuracy: 0.83 - ETA: 4s - loss: 0.3919 - accuracy: 0.82 - ETA: 3s - loss: 0.3864 - accuracy: 0.83 - ETA: 3s - loss: 0.3844 - accuracy: 0.83 - ETA: 2s - loss: 0.3823 - accuracy: 0.83 - ETA: 2s - loss: 0.3781 - accuracy: 0.83 - ETA: 2s - loss: 0.3778 - accuracy: 0.83 - ETA: 2s - loss: 0.3778 - accuracy: 0.83 - ETA: 2s - loss: 0.3802 - accuracy: 0.83 - ETA: 2s - loss: 0.3784 - accuracy: 0.83 - ETA: 1s - loss: 0.3789 - accuracy: 0.83 - ETA: 1s - loss: 0.3790 - accuracy: 0.83 - ETA: 1s - loss: 0.3775 - accuracy: 0.83 - ETA: 1s - loss: 0.3777 - accuracy: 0.83 - ETA: 1s - loss: 0.3773 - accuracy: 0.83 - ETA: 1s - loss: 0.3778 - accuracy: 0.83 - ETA: 1s - loss: 0.3768 - accuracy: 0.83 - ETA: 1s - loss: 0.3743 - accuracy: 0.84 - ETA: 0s - loss: 0.3710 - accuracy: 0.84 - ETA: 0s - loss: 0.3689 - accuracy: 0.84 - ETA: 0s - loss: 0.3667 - accuracy: 0.84 - ETA: 0s - loss: 0.3660 - accuracy: 0.84 - ETA: 0s - loss: 0.3652 - accuracy: 0.84 - ETA: 0s - loss: 0.3650 - accuracy: 0.84 - ETA: 0s - loss: 0.3642 - accuracy: 0.84 - ETA: 0s - loss: 0.3629 - accuracy: 0.84 - ETA: 0s - loss: 0.3627 - accuracy: 0.84 - 5s 151ms/step - loss: 0.3626 - accuracy: 0.8489 - val_loss: 0.3992 - val_accuracy: 0.8207\n" ] } ], "source": [ "history = model.fit(train_data.shuffle(10000).batch(512),\n", " epochs=10,\n", " validation_data = validation_data.batch(512),\n", " verbose=1)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "loss: 0.407\n", "accuracy: 0.818\n" ] } ], "source": [ "results = model.evaluate(test_data.batch(512),verbose=2)\n", "for name,value in zip(model.metrics_names,results):\n", " print(\"%s: %.3f\" % (name, value))" ] } ], "metadata": { "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.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "pile_set_name": "Github" }
/// <reference path="../../../dist/preview release/babylon.d.ts"/> var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var BABYLON; (function (BABYLON) { var SimpleMaterialDefines = /** @class */ (function (_super) { __extends(SimpleMaterialDefines, _super); function SimpleMaterialDefines() { var _this = _super.call(this) || this; _this.DIFFUSE = false; _this.CLIPPLANE = false; _this.ALPHATEST = false; _this.DEPTHPREPASS = false; _this.POINTSIZE = false; _this.FOG = false; _this.NORMAL = false; _this.UV1 = false; _this.UV2 = false; _this.VERTEXCOLOR = false; _this.VERTEXALPHA = false; _this.NUM_BONE_INFLUENCERS = 0; _this.BonesPerMesh = 0; _this.INSTANCES = false; _this.rebuild(); return _this; } return SimpleMaterialDefines; }(BABYLON.MaterialDefines)); var SimpleMaterial = /** @class */ (function (_super) { __extends(SimpleMaterial, _super); function SimpleMaterial(name, scene) { var _this = _super.call(this, name, scene) || this; _this.diffuseColor = new BABYLON.Color3(1, 1, 1); _this._disableLighting = false; _this._maxSimultaneousLights = 4; return _this; } SimpleMaterial.prototype.needAlphaBlending = function () { return (this.alpha < 1.0); }; SimpleMaterial.prototype.needAlphaTesting = function () { return false; }; SimpleMaterial.prototype.getAlphaTestTexture = function () { return null; }; // Methods SimpleMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) { if (this.isFrozen) { if (this._wasPreviouslyReady && subMesh.effect) { return true; } } if (!subMesh._materialDefines) { subMesh._materialDefines = new SimpleMaterialDefines(); } var defines = subMesh._materialDefines; var scene = this.getScene(); if (!this.checkReadyOnEveryCall && subMesh.effect) { if (this._renderId === scene.getRenderId()) { return true; } } var engine = scene.getEngine(); // Textures if (defines._areTexturesDirty) { defines._needUVs = false; if (scene.texturesEnabled) { if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) { if (!this._diffuseTexture.isReady()) { return false; } else { defines._needUVs = true; defines.DIFFUSE = true; } } } } // Misc. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines); // Lights defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights, this._disableLighting); // Values that need to be evaluated on every frame BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false); // Attribs BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true); // Get correct effect if (defines.isDirty) { defines.markAsProcessed(); scene.resetCachedMaterial(); // Fallbacks var fallbacks = new BABYLON.EffectFallbacks(); if (defines.FOG) { fallbacks.addFallback(1, "FOG"); } BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this.maxSimultaneousLights); if (defines.NUM_BONE_INFLUENCERS > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } //Attributes var attribs = [BABYLON.VertexBuffer.PositionKind]; if (defines.NORMAL) { attribs.push(BABYLON.VertexBuffer.NormalKind); } if (defines.UV1) { attribs.push(BABYLON.VertexBuffer.UVKind); } if (defines.UV2) { attribs.push(BABYLON.VertexBuffer.UV2Kind); } if (defines.VERTEXCOLOR) { attribs.push(BABYLON.VertexBuffer.ColorKind); } BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks); BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines); var shaderName = "simple"; var join = defines.toString(); var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vDiffuseColor", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "mBones", "vClipPlane", "diffuseMatrix" ]; var samplers = ["diffuseSampler"]; var uniformBuffers = new Array(); BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({ uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: defines, maxSimultaneousLights: this.maxSimultaneousLights }); subMesh.setEffect(scene.getEngine().createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers: samplers, defines: join, fallbacks: fallbacks, onCompiled: this.onCompiled, onError: this.onError, indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights - 1 } }, engine), defines); } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } this._renderId = scene.getRenderId(); this._wasPreviouslyReady = true; return true; }; SimpleMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) { var scene = this.getScene(); var defines = subMesh._materialDefines; if (!defines) { return; } var effect = subMesh.effect; if (!effect) { return; } this._activeEffect = effect; // Matrices this.bindOnlyWorldMatrix(world); this._activeEffect.setMatrix("viewProjection", scene.getTransformMatrix()); // Bones BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect); if (this._mustRebind(scene, effect)) { // Textures if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) { this._activeEffect.setTexture("diffuseSampler", this._diffuseTexture); this._activeEffect.setFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); this._activeEffect.setMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix()); } // Clip plane BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene); // Point size if (this.pointsCloud) { this._activeEffect.setFloat("pointSize", this.pointSize); } BABYLON.MaterialHelper.BindEyePosition(effect, scene); } this._activeEffect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility); // Lights if (scene.lightsEnabled && !this.disableLighting) { BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this.maxSimultaneousLights); } // View if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) { this._activeEffect.setMatrix("view", scene.getViewMatrix()); } // Fog BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect); this._afterBind(mesh, this._activeEffect); }; SimpleMaterial.prototype.getAnimatables = function () { var results = []; if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) { results.push(this._diffuseTexture); } return results; }; SimpleMaterial.prototype.getActiveTextures = function () { var activeTextures = _super.prototype.getActiveTextures.call(this); if (this._diffuseTexture) { activeTextures.push(this._diffuseTexture); } return activeTextures; }; SimpleMaterial.prototype.hasTexture = function (texture) { if (_super.prototype.hasTexture.call(this, texture)) { return true; } if (this.diffuseTexture === texture) { return true; } return false; }; SimpleMaterial.prototype.dispose = function (forceDisposeEffect) { if (this._diffuseTexture) { this._diffuseTexture.dispose(); } _super.prototype.dispose.call(this, forceDisposeEffect); }; SimpleMaterial.prototype.clone = function (name) { var _this = this; return BABYLON.SerializationHelper.Clone(function () { return new SimpleMaterial(name, _this.getScene()); }, this); }; SimpleMaterial.prototype.serialize = function () { var serializationObject = BABYLON.SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.SimpleMaterial"; return serializationObject; }; SimpleMaterial.prototype.getClassName = function () { return "SimpleMaterial"; }; // Statics SimpleMaterial.Parse = function (source, scene, rootUrl) { return BABYLON.SerializationHelper.Parse(function () { return new SimpleMaterial(source.name, scene); }, source, scene, rootUrl); }; __decorate([ BABYLON.serializeAsTexture("diffuseTexture") ], SimpleMaterial.prototype, "_diffuseTexture", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty") ], SimpleMaterial.prototype, "diffuseTexture", void 0); __decorate([ BABYLON.serializeAsColor3("diffuse") ], SimpleMaterial.prototype, "diffuseColor", void 0); __decorate([ BABYLON.serialize("disableLighting") ], SimpleMaterial.prototype, "_disableLighting", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], SimpleMaterial.prototype, "disableLighting", void 0); __decorate([ BABYLON.serialize("maxSimultaneousLights") ], SimpleMaterial.prototype, "_maxSimultaneousLights", void 0); __decorate([ BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty") ], SimpleMaterial.prototype, "maxSimultaneousLights", void 0); return SimpleMaterial; }(BABYLON.PushMaterial)); BABYLON.SimpleMaterial = SimpleMaterial; })(BABYLON || (BABYLON = {})); //# sourceMappingURL=babylon.simpleMaterial.js.map BABYLON.Effect.ShadersStore['simpleVertexShader'] = "precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n"; BABYLON.Effect.ShadersStore['simplePixelShader'] = "precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";
{ "pile_set_name": "Github" }
owner = SAU controller = SAU add_core = SAU infra = 2
{ "pile_set_name": "Github" }
+++ title = "BusyBox" description = "" date = 2014-11-21T15:14:09Z aliases = [] [extra] id = 18208 [taxonomies] categories = [] tags = [] +++ [[Category:AWK Implementations]] [[Category:UNIX Shell Implementations]] [[Category:Editor]] [[Category:Utility]] [[wp:BusyBox|BusyBox]] "The Swiss Army Knife of Embedded Linux" is a multiuse-utility, designed for embedded Linux-systems: :BusyBox combines tiny versions of many common UNIX utilities into a single small executable. :It provides replacements for most of the utilities you usually find in GNU fileutils, shellutils, etc. <!-- The utilities in BusyBox generally have fewer options than their full-featured GNU cousins; however, the options that are included provide the expected functionality and behave very much like their GNU counterparts. BusyBox provides a fairly complete environment for any small or embedded system. BusyBox has been written with size-optimization and limited resources in mind. It is also extremely modular so you can easily include or exclude commands (or features) at compile time. This makes it easy to customize your embedded systems. --> A working system may consist of just a Linux kernel, some device nodes in /dev, a few configuration files in /etc, BusyBox, and maybe a bootmanager. For example, BusyBox is used in [http://distro.ibiblio.org/tinycorelinux Tiny Core Linux]. BusyBox can provide most of the functionality of the many programs typical found in /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, all in a single binary, thus saving space on small systems. As a shell, BusyBox provides [[Almquist Shell‎|ash]]. As a calculator, BusyBox provides [[dc]], a "Tiny RPN calculator". As an editor, BusyBox provides [[sed]] and [[Vi]]. BusyBox can be configured (at compile-time) to include as little or as much "applets" as needed/desired. [http://www.busybox.net BusyBox] can be compiled to include an [[AWK]]-implementation.
{ "pile_set_name": "Github" }
import React, { PropTypes } from 'react'; import StyleSheet from 'react-style'; var ListStyles = StyleSheet.create({ normalListStyle: { overflow: 'auto', overflowY: 'auto', overflowX: 'none' } }); export default class extends React.Component { static displayName = 'List' static propTypes = { children: PropTypes.node } render() { return ( <div styles={ ListStyles.normalListStyle }> { this.props.children } </div> ); } }
{ "pile_set_name": "Github" }
prefix=INSTALL_PREFIX libdir=LIB_DIR includedir=HEADER_DIR Name: libtraceevent URL: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git Description: Linux kernel trace event library Version: LIB_VERSION Cflags: -I${includedir} Libs: -L${libdir} -ltraceevent
{ "pile_set_name": "Github" }
KotlinPoet ========== `KotlinPoet` is a Kotlin and Java API for generating `.kt` source files. Source file generation can be useful when doing things such as annotation processing or interacting with metadata files (e.g., database schemas, protocol formats). By generating code, you eliminate the need to write boilerplate while also keeping a single source of truth for the metadata. ### Example Here's a `HelloWorld` file: ```kotlin class Greeter(val name: String) { fun greet() { println("""Hello, $name""") } } fun main(vararg args: String) { Greeter(args[0]).greet() } ``` And this is the code to generate it with KotlinPoet: ```kotlin val greeterClass = ClassName("", "Greeter") val file = FileSpec.builder("", "HelloWorld") .addType(TypeSpec.classBuilder("Greeter") .primaryConstructor(FunSpec.constructorBuilder() .addParameter("name", String::class) .build()) .addProperty(PropertySpec.builder("name", String::class) .initializer("name") .build()) .addFunction(FunSpec.builder("greet") .addStatement("println(%P)", "Hello, \$name") .build()) .build()) .addFunction(FunSpec.builder("main") .addParameter("args", String::class, VARARG) .addStatement("%T(args[0]).greet()", greeterClass) .build()) .build() file.writeTo(System.out) ``` The [KDoc][kdoc] catalogs the complete KotlinPoet API, which is inspired by [JavaPoet][javapoet]. ### Code & Control Flow Most of KotlinPoet's API uses immutable Kotlin objects. There's also builders, method chaining and varargs to make the API friendly. KotlinPoet offers models for Kotlin files (`FileSpec`), classes, interfaces & objects (`TypeSpec`), type aliases (`TypeAliasSpec`), properties (`PropertySpec`), functions & constructors (`FunSpec`), parameters (`ParameterSpec`) and annotations (`AnnotationSpec`). But the _body_ of methods and constructors is not modeled. There's no expression class, no statement class or syntax tree nodes. Instead, KotlinPoet uses strings for code blocks, and you can take advantage of Kotlin's multiline strings to make this look nice: ```kotlin val main = FunSpec.builder("main") .addCode(""" |var total = 0 |for (i in 0 until 10) { | total += i |} |""".trimMargin()) .build() ``` Which generates this: ```kotlin fun main() { var total = 0 for (i in 0 until 10) { total += i } } ``` There are additional APIs to assist with newlines, braces and indentation: ```kotlin val main = FunSpec.builder("main") .addStatement("var total = 0") .beginControlFlow("for (i in 0 until 10)") .addStatement("total += i") .endControlFlow() .build() ``` This example is lame because the generated code is constant! Suppose instead of just adding 0 to 10, we want to make the operation and range configurable. Here's a method that generates a method: ```kotlin private fun computeRange(name: String, from: Int, to: Int, op: String): FunSpec { return FunSpec.builder(name) .returns(Int::class) .addStatement("var result = 1") .beginControlFlow("for (i in $from until $to)") .addStatement("result = result $op i") .endControlFlow() .addStatement("return result") .build() } ``` And here's what we get when we call `computeRange("multiply10to20", 10, 20, "*")`: ```kotlin fun multiply10to20(): kotlin.Int { var result = 1 for (i in 10 until 20) { result = result * i } return result } ``` Methods generating methods! And since KotlinPoet generates source instead of bytecode, you can read through it to make sure it's right. ### %S for Strings When emitting code that includes string literals, we can use **`%S`** to emit a **string**, complete with wrapping quotation marks and escaping. Here's a program that emits 3 methods, each of which returns its own name: ```kotlin fun main(args: Array<String>) { val helloWorld = TypeSpec.classBuilder("HelloWorld") .addFunction(whatsMyNameYo("slimShady")) .addFunction(whatsMyNameYo("eminem")) .addFunction(whatsMyNameYo("marshallMathers")) .build() val kotlinFile = FileSpec.builder("com.example.helloworld", "HelloWorld") .addType(helloWorld) .build() kotlinFile.writeTo(System.out) } private fun whatsMyNameYo(name: String): FunSpec { return FunSpec.builder(name) .returns(String::class) .addStatement("return %S", name) .build() } ``` In this case, using `%S` gives us quotation marks: ```kotlin class HelloWorld { fun slimShady(): String = "slimShady" fun eminem(): String = "eminem" fun marshallMathers(): String = "marshallMathers" } ``` ### %P for String Templates `%S` also handles the escaping of dollar signs (`$`), to avoid inadvertent creation of string templates, which may fail to compile in generated code: ```kotlin val stringWithADollar = "Your total is " + "$" + "50" val funSpec = FunSpec.builder("printTotal") .returns(String::class) .addStatement("return %S", stringWithADollar) .build() ``` produces: ```kotlin fun printTotal(): String = "Your total is ${'$'}50" ``` If you need to generate string templates, use `%P`, which doesn't escape dollars: ```kotlin val amount = 50 val stringWithADollar = "Your total is " + "$" + "amount" val funSpec = FunSpec.builder("printTotal") .returns(String::class) .addStatement("return %P", stringWithADollar) .build() ``` produces: ```kotlin fun printTotal(): String = "Your total is $amount" ``` You can also use `CodeBlock`s as arguments to `%P`, which is handy when you need to reference importable types or members inside the string template: ```kotlin val file = FileSpec.builder("com.example", "Digits") .addFunction(FunSpec.builder("print") .addParameter("digits", IntArray::class) .addStatement("println(%P)", buildCodeBlock { val contentToString = MemberName("kotlin.collections", "contentToString") add("These are the digits: \${digits.%M()}", contentToString) }) .build()) .build() println(file) ``` The snippet above will produce the following output, handling the imports properly: ```kotlin package com.example import kotlin.IntArray import kotlin.collections.contentToString fun print(digits: IntArray) { println("""These are the digits: ${digits.contentToString()}""") } ``` ### %T for Types KotlinPoet has rich built-in support for types, including automatic generation of `import` statements. Just use **`%T`** to reference **types**: ```kotlin val today = FunSpec.builder("today") .returns(Date::class) .addStatement("return %T()", Date::class) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addFunction(today) .build() val kotlinFile = FileSpec.builder("com.example.helloworld", "HelloWorld") .addType(helloWorld) .build() kotlinFile.writeTo(System.out) ``` That generates the following `.kt` file, complete with the necessary `import`: ```kotlin package com.example.helloworld import java.util.Date class HelloWorld { fun today(): Date = Date() } ``` We passed `Date::class` to reference a class that just-so-happens to be available when we're generating code. This doesn't need to be the case. Here's a similar example, but this one references a class that doesn't exist (yet): ```kotlin val hoverboard = ClassName("com.mattel", "Hoverboard") val tomorrow = FunSpec.builder("tomorrow") .returns(hoverboard) .addStatement("return %T()", hoverboard) .build() ``` And that not-yet-existent class is imported as well: ```kotlin package com.example.helloworld import com.mattel.Hoverboard class HelloWorld { fun tomorrow(): Hoverboard = Hoverboard() } ``` The `ClassName` type is very important, and you'll need it frequently when you're using KotlinPoet. It can identify any _declared_ class. Declared types are just the beginning of Kotlin's rich type system: we also have arrays, parameterized types, wildcard types, lambda types and type variables. KotlinPoet has classes for building each of these: ```kotlin import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy val hoverboard = ClassName("com.mattel", "Hoverboard") val list = ClassName("kotlin.collections", "List") val arrayList = ClassName("kotlin.collections", "ArrayList") val listOfHoverboards = list.parameterizedBy(hoverboard) val arrayListOfHoverboards = arrayList.parameterizedBy(hoverboard) val thing = ClassName("com.misc", "Thing") val array = ClassName("kotlin", "Array") val producerArrayOfThings = array.parameterizedBy(WildcardTypeName.producerOf(thing)) val beyond = FunSpec.builder("beyond") .returns(listOfHoverboards) .addStatement("val result = %T()", arrayListOfHoverboards) .addStatement("result += %T()", hoverboard) .addStatement("result += %T()", hoverboard) .addStatement("result += %T()", hoverboard) .addStatement("return result") .build() val printThings = FunSpec.builder("printThings") .addParameter("things", producerArrayOfThings) .addStatement("println(things)") .build() ``` KotlinPoet will decompose each type and import its components where possible. ```kotlin package com.example.helloworld import com.mattel.Hoverboard import com.misc.Thing import kotlin.Array import kotlin.collections.ArrayList import kotlin.collections.List class HelloWorld { fun beyond(): List<Hoverboard> { val result = ArrayList<Hoverboard>() result += Hoverboard() result += Hoverboard() result += Hoverboard() return result } fun printThings(things: Array<out Thing>) { println(things) } } ``` #### Nullable Types KotlinPoet supports nullable types. To convert a `TypeName` into its nullable counterpart, use the `copy()` method with `nullable` parameter set to `true`: ```kotlin val java = PropertySpec.builder("java", String::class.asTypeName().copy(nullable = true)) .mutable() .addModifiers(KModifier.PRIVATE) .initializer("null") .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addProperty(java) .addProperty("kotlin", String::class, KModifier.PRIVATE) .build() ``` generates: ```kotlin class HelloWorld { private var java: String? = null private val kotlin: String } ``` ### %M for Members Similar to types, KotlinPoet has a special placeholder for **members** (functions and properties), which comes handy when your code needs to access top-level members and members declared inside objects. Use **`%M`** to reference members, pass an instance of `MemberName` as the argument for the placeholder, and KotlinPoet will handle imports automatically: ```kotlin val createTaco = MemberName("com.squareup.tacos", "createTaco") val isVegan = MemberName("com.squareup.tacos", "isVegan") val file = FileSpec.builder("com.squareup.example", "TacoTest") .addFunction(FunSpec.builder("main") .addStatement("val taco = %M()", createTaco) .addStatement("println(taco.%M)", isVegan) .build()) .build() println(file) ``` The code above generates the following file: ```kotlin package com.squareup.example import com.squareup.tacos.createTaco import com.squareup.tacos.isVegan fun main() { val taco = createTaco() println(taco.isVegan) } ``` As you can see, it's also possible to use `%M` to reference extension functions and properties. You just need to make sure the member can be imported without simple name collisions, otherwise importing will fail and the code generator output will not pass compilation. There's a way to work around such cases though - use `FileSpec.addAliasedImport()` to create an alias for a clashing `MemberName`: ```kotlin val createTaco = MemberName("com.squareup.tacos", "createTaco") val createCake = MemberName("com.squareup.cakes", "createCake") val isTacoVegan = MemberName("com.squareup.tacos", "isVegan") val isCakeVegan = MemberName("com.squareup.cakes", "isVegan") val file = FileSpec.builder("com.squareup.example", "Test") .addAliasedImport(isTacoVegan, "isTacoVegan") .addAliasedImport(isCakeVegan, "isCakeVegan") .addFunction(FunSpec.builder("main") .addStatement("val taco = %M()", createTaco) .addStatement("val cake = %M()", createCake) .addStatement("println(taco.%M)", isTacoVegan) .addStatement("println(cake.%M)", isCakeVegan) .build()) .build() println(file) ``` KotlinPoet will produce an aliased import for `com.squareup.tacos2.isVegan`: ```kotlin package com.squareup.example import com.squareup.cakes.createCake import com.squareup.tacos.createTaco import com.squareup.cakes.isVegan as isCakeVegan import com.squareup.tacos.isVegan as isTacoVegan fun main() { val taco = createTaco() val cake = createCake() println(taco.isTacoVegan) println(cake.isCakeVegan) } ``` #### MemberName and operators MemberName also supports operators, you can use `MemberName(String, KOperator)` or `MemberName(ClassName, KOperator)` to import and reference operators. ```kotlin val taco = ClassName("com.squareup.tacos", "Taco") val meat = ClassName("com.squareup.tacos.ingredient", "Meat") val iterator = MemberName("com.squareup.tacos.internal", KOperator.ITERATOR) val minusAssign = MemberName("com.squareup.tacos.internal", KOperator.MINUS_ASSIGN) val file = FileSpec.builder("com.example", "Test") .addFunction(FunSpec.builder("makeTacoHealthy") .addParameter("taco", taco) .beginControlFlow("for (ingredient %M taco)", iterator) .addStatement("if (ingredient is %T) taco %M ingredient", meat, minusAssign) .endControlFlow() .addStatement("return taco") .build()) .build() println(file) ``` KotlinPoet will import the extension operator functions and emit the operator. ```kotlin package com.example import com.squareup.tacos.Taco import com.squareup.tacos.ingredient.Meat import com.squareup.tacos.internal.iterator import com.squareup.tacos.internal.minusAssign fun makeTacoHealthy(taco: Taco) { for (ingredient in taco) { if (ingredient is Meat) taco -= ingredient } return taco } ``` ### %N for Names Generated code is often self-referential. Use **`%N`** to refer to another generated declaration by its name. Here's a method that calls another: ```kotlin fun byteToHex(b: Int): String { val result = CharArray(2) result[0] = hexDigit((b ushr 4) and 0xf) result[1] = hexDigit(b and 0xf) return String(result) } fun hexDigit(i: Int): Char { return (if (i < 10) i + '0'.toInt() else i - 10 + 'a'.toInt()).toChar() } ``` When generating the code above, we pass the `hexDigit()` method as an argument to the `byteToHex()` method using `%N`: ```kotlin val hexDigit = FunSpec.builder("hexDigit") .addParameter("i", Int::class) .returns(Char::class) .addStatement("return (if (i < 10) i + '0'.toInt() else i - 10 + 'a'.toInt()).toChar()") .build() val byteToHex = FunSpec.builder("byteToHex") .addParameter("b", Int::class) .returns(String::class) .addStatement("val result = CharArray(2)") .addStatement("result[0] = %N((b ushr 4) and 0xf)", hexDigit) .addStatement("result[1] = %N(b and 0xf)", hexDigit) .addStatement("return String(result)") .build() ``` Another handy feature that `%N` provides is automatically escaping names that contain illegal identifier characters with double ticks. Suppose your code creates a `MemberName` with a Kotlin keyword as the simple name: ```kotlin val taco = ClassName("com.squareup.tacos", "Taco") val packager = ClassName("com.squareup.tacos", "TacoPackager") val file = FileSpec.builder("com.example", "Test") .addFunction(FunSpec.builder("packageTacos") .addParameter("tacos", LIST.parameterizedBy(taco)) .addParameter("packager", packager) .addStatement("packager.%N(tacos)", packager.member("package")) .build()) .build() ``` `%N` will escape the name for you, ensuring that the output will pass compilation: ```kotlin package com.example import com.squareup.tacos.Taco import com.squareup.tacos.TacoPackager import kotlin.collections.List fun packageTacos(tacos: List<Taco>, packager: TacoPackager) { packager.`package`(tacos) } ``` ### %L for Literals Although Kotlin's string templates usually work well in cases when you want to include literals into generated code, KotlinPoet offers additional syntax inspired-by but incompatible-with [`String.format()`][formatter]. It accepts **`%L`** to emit a **literal** value in the output. This works just like `Formatter`'s `%s`: ```kotlin private fun computeRange(name: String, from: Int, to: Int, op: String): FunSpec { return FunSpec.builder(name) .returns(Int::class) .addStatement("var result = 0") .beginControlFlow("for (i in %L until %L)", from, to) .addStatement("result = result %L i", op) .endControlFlow() .addStatement("return result") .build() } ``` Literals are emitted directly to the output code with no escaping. Arguments for literals may be strings, primitives, and a few KotlinPoet types described below. ### Code block format strings Code blocks may specify the values for their placeholders in a few ways. Only one style may be used for each operation on a code block. #### Relative Arguments Pass an argument value for each placeholder in the format string to `CodeBlock.add()`. In each example, we generate code to say "I ate 3 tacos" ```kotlin CodeBlock.builder().add("I ate %L %L", 3, "tacos") ``` #### Positional Arguments Place an integer index (1-based) before the placeholder in the format string to specify which argument to use. ```kotlin CodeBlock.builder().add("I ate %2L %1L", "tacos", 3) ``` #### Named Arguments Use the syntax `%argumentName:X` where `X` is the format character and call `CodeBlock.addNamed()` with a map containing all argument keys in the format string. Argument names use characters in `a-z`, `A-Z`, `0-9`, and `_`, and must start with a lowercase character. ```kotlin val map = LinkedHashMap<String, Any>() map += "food" to "tacos" map += "count" to 3 CodeBlock.builder().addNamed("I ate %count:L %food:L", map) ``` ### Functions All of the above functions have a code body. Use `KModifier.ABSTRACT` to get a function without any body. This is only legal if it is enclosed by an abstract class or an interface. ```kotlin val flux = FunSpec.builder("flux") .addModifiers(KModifier.ABSTRACT, KModifier.PROTECTED) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addModifiers(KModifier.ABSTRACT) .addFunction(flux) .build() ``` Which generates this: ```kotlin abstract class HelloWorld { protected abstract fun flux() } ``` The other modifiers work where permitted. Methods also have parameters, varargs, KDoc, annotations, type variables, return type and receiver type for extension functions. All of these are configured with `FunSpec.Builder`. #### Extension functions Extension functions can be generated by specifying a `receiver`. ```kotlin val square = FunSpec.builder("square") .receiver(Int::class) .returns(Int::class) .addStatement("var s = this * this") .addStatement("return s") .build() ``` Which outputs: ```kotlin fun Int.square(): Int { val s = this * this return s } ``` #### Single-expression functions KotlinPoet can recognize single-expression functions and print them out properly. It treats each function with a body that starts with `return` as a single-expression function: ```kotlin val abs = FunSpec.builder("abs") .addParameter("x", Int::class) .returns(Int::class) .addStatement("return if (x < 0) -x else x") .build() ``` Which outputs: ```kotlin fun abs(x: Int): Int = if (x < 0) -x else x ``` #### Default function arguments Consider the example below. Function argument `b` has a default value of 0 to avoid overloading this function. ```kotlin fun add(a: Int, b: Int = 0) { print("a + b = ${ a + b }") } ``` Use the `defaultValue()` builder function to declare default value for a function argument. ```kotlin FunSpec.builder("add") .addParameter("a", Int::class) .addParameter(ParameterSpec.builder("b", Int::class) .defaultValue("%L", 0) .build()) .addStatement("print(\"a + b = ${ a + b }\")") .build() ``` #### Spaces wrap by default! In order to provide meaningful formatting, KotlinPoet would replace spaces, found in blocks of code, with new line symbols, in cases when the line of code exceeds the length limit. Let's take this function for example: ```kotlin val funSpec = FunSpec.builder("foo") .addStatement("return (100..10000).map { number -> number * number }.map { number -> number.toString() }.also { string -> println(string) }") .build() ``` Depending on where it's found in the file, it may end up being printed out like this: ```kotlin fun foo() = (100..10000).map { number -> number * number }.map { number -> number.toString() }.also { string -> println(string) } ``` Unfortunately this code is broken: the compiler expects `also` and `{` to be on the same line. KotlinPoet is unable to understand the context of the expression and fix the formatting for you, but there's a trick you can use to declare a non-breaking space - use the `·` symbol where you would otherwise use a space. Let's apply this to our example: ```kotlin val funSpec = FunSpec.builder("foo") .addStatement("return (100..10000).map·{ number -> number * number }.map·{ number -> number.toString() }.also·{ string -> println(string) }") .build() ``` This will now produce the following result: ```kotlin fun foo() = (100..10000).map { number -> number * number }.map { number -> number.toString() }.also { string -> println(string) } ``` The code is now correct and will compile properly. It still doesn't look perfect - you can play with replacing other spaces in the code block with `·` symbols to achieve better formatting. ### Constructors `FunSpec` is a slight misnomer; it can also be used for constructors: ```kotlin val flux = FunSpec.constructorBuilder() .addParameter("greeting", String::class) .addStatement("this.%N = %N", "greeting", "greeting") .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addProperty("greeting", String::class, KModifier.PRIVATE) .addFunction(flux) .build() ``` Which generates this: ```kotlin class HelloWorld { private val greeting: String constructor(greeting: String) { this.greeting = greeting } } ``` For the most part, constructors work just like methods. When emitting code, KotlinPoet will place constructors before methods in the output file. Often times you'll need to generate the primary constructor for a class: ```kotlin val helloWorld = TypeSpec.classBuilder("HelloWorld") .primaryConstructor(flux) .addProperty("greeting", String::class, KModifier.PRIVATE) .build() ``` This code, however, generates the following: ```kotlin class HelloWorld(greeting: String) { private val greeting: String init { this.greeting = greeting } } ``` By default, KotlinPoet won't merge primary constructor parameters and properties, even if they share the same name. To achieve the effect, you have to tell KotlinPoet that the property is initialized via the constructor parameter: ```kotlin val flux = FunSpec.constructorBuilder() .addParameter("greeting", String::class) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .primaryConstructor(flux) .addProperty(PropertySpec.builder("greeting", String::class) .initializer("greeting") .addModifiers(KModifier.PRIVATE) .build()) .build() ``` Now we're getting the following output: ```kotlin class HelloWorld(private val greeting: String) ``` Notice that KotlinPoet omits `{}` for classes with empty bodies. ### Parameters Declare parameters on methods and constructors with either `ParameterSpec.builder()` or `FunSpec`'s convenient `addParameter()` API: ```kotlin val android = ParameterSpec.builder("android", String::class) .defaultValue("\"pie\"") .build() val welcomeOverlords = FunSpec.builder("welcomeOverlords") .addParameter(android) .addParameter("robot", String::class) .build() ``` The code above generates: ```kotlin fun welcomeOverlords(android: String = "pie", robot: String) { } ``` The extended `Builder` form is necessary when the parameter has annotations (such as `@Inject`). ### Properties Like parameters, properties can be created either with builders or by using convenient helper methods: ```kotlin val android = PropertySpec.builder("android", String::class) .addModifiers(KModifier.PRIVATE) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addProperty(android) .addProperty("robot", String::class, KModifier.PRIVATE) .build() ``` Which generates: ```kotlin class HelloWorld { private val android: String private val robot: String } ``` The extended `Builder` form is necessary when a field has KDoc, annotations, or a field initializer. Field initializers use the same [`String.format()`][formatter]-like syntax as the code blocks above: ```kotlin val android = PropertySpec.builder("android", String::class) .addModifiers(KModifier.PRIVATE) .initializer("%S + %L", "Oreo v.", 8.1) .build() ``` Which generates: ```kotlin private val android: String = "Oreo v." + 8.1 ``` By default `PropertySpec.Builder` produces `val` properties. Use `mutable()` if you need a `var`: ```kotlin val android = PropertySpec.builder("android", String::class) .mutable() .addModifiers(KModifier.PRIVATE) .initializer("%S + %L", "Oreo v.", 8.1) .build() ``` #### Inline properties The way KotlinPoet models inline properties deserves special mention. The following snippet of code: ```kotlin val android = PropertySpec.builder("android", String::class) .addModifiers(KModifier.INLINE) .build() ``` will produce an error: ``` java.lang.IllegalArgumentException: KotlinPoet doesn't allow setting the inline modifier on properties. You should mark either the getter, the setter, or both inline. ``` Indeed, a property marked with `inline` should have at least one accessor which will be inlined by the compiler. Let's add a getter to this property: ```kotlin val android = PropertySpec.builder("android", String::class) .getter(FunSpec.getterBuilder() .addModifiers(KModifier.INLINE) .addStatement("return %S", "foo") .build()) .build() ``` The result is the following: ```kotlin val android: kotlin.String inline get() = "foo" ``` Now, what if we wanted to add a non-inline setter to the property above? We can do so without modifying any of the code we wrote previously: ```kotlin val android = PropertySpec.builder("android", String::class) .getter(FunSpec.getterBuilder() .addModifiers(KModifier.INLINE) .addStatement("return %S", "foo") .build()) .setter(FunSpec.setterBuilder() .addParameter("value", String::class) .build()) .build() ``` We get the expected result: ```kotlin val android: kotlin.String inline get() = "foo" set(value) { } ``` Finally, if we go back and add `KModifier.INLINE` to the setter, KotlinPoet can wrap it nicely and produce the following result: ```kotlin inline val android: kotlin.String get() = "foo" set(value) { } ``` Removing the modifier from either the getter or the setter will unwrap the expression back. If, on the other hand, KotlinPoet had allowed marking a property `inline` directly, the programmer would have had to manually add/remove the modifier whenever the state of the accessors changes in order to get correct and compilable output. We're solving this problem by making accessors the source of truth for the `inline` modifier. ### Interfaces KotlinPoet has no trouble with interfaces. Note that interface methods must always be `ABSTRACT`. The modifier is necessary when defining the interface: ```kotlin val helloWorld = TypeSpec.interfaceBuilder("HelloWorld") .addProperty("buzz", String::class) .addFunction(FunSpec.builder("beep") .addModifiers(KModifier.ABSTRACT) .build()) .build() ``` But these modifiers are omitted when the code is generated. These are the default so we don't need to include them for `kotlinc`'s benefit! ```kotlin interface HelloWorld { val buzz: String fun beep() } ``` Kotlin 1.4 adds support for functional interfaces via `fun interface` syntax. To create this in KotlinPoet, use `TypeSpec.funInterfaceBuilder()`. ```kotlin val helloWorld = TypeSpec.funInterfaceBuilder("HelloWorld") .addFunction(FunSpec.builder("beep") .addModifiers(KModifier.ABSTRACT) .build()) .build() // Generates... fun interface HelloWorld { fun beep() } ``` ### Objects KotlinPoet supports objects: ```kotlin val helloWorld = TypeSpec.objectBuilder("HelloWorld") .addProperty(PropertySpec.builder("buzz", String::class) .initializer("%S", "buzz") .build()) .addFunction(FunSpec.builder("beep") .addStatement("println(%S)", "Beep!") .build()) .build() ``` Similarly, you can create companion objects and add them to classes using `addType()`: ```kotlin val companion = TypeSpec.companionObjectBuilder() .addProperty(PropertySpec.builder("buzz", String::class) .initializer("%S", "buzz") .build()) .addFunction(FunSpec.builder("beep") .addStatement("println(%S)", "Beep!") .build()) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addType(companion) .build() ``` You can provide an optional name for a companion object. ### Enums Use `enumBuilder` to create the enum type, and `addEnumConstant()` for each value: ```kotlin val helloWorld = TypeSpec.enumBuilder("Roshambo") .addEnumConstant("ROCK") .addEnumConstant("SCISSORS") .addEnumConstant("PAPER") .build() ``` To generate this: ```kotlin enum class Roshambo { ROCK, SCISSORS, PAPER } ``` Fancy enums are supported, where the enum values override methods or call a superclass constructor. Here's a comprehensive example: ```kotlin val helloWorld = TypeSpec.enumBuilder("Roshambo") .primaryConstructor(FunSpec.constructorBuilder() .addParameter("handsign", String::class) .build()) .addEnumConstant("ROCK", TypeSpec.anonymousClassBuilder() .addSuperclassConstructorParameter("%S", "fist") .addFunction(FunSpec.builder("toString") .addModifiers(KModifier.OVERRIDE) .addStatement("return %S", "avalanche!") .returns(String::class) .build()) .build()) .addEnumConstant("SCISSORS", TypeSpec.anonymousClassBuilder() .addSuperclassConstructorParameter("%S", "peace") .build()) .addEnumConstant("PAPER", TypeSpec.anonymousClassBuilder() .addSuperclassConstructorParameter("%S", "flat") .build()) .addProperty(PropertySpec.builder("handsign", String::class, KModifier.PRIVATE) .initializer("handsign") .build()) .build() ``` Which generates this: ```kotlin enum class Roshambo(private val handsign: String) { ROCK("fist") { override fun toString(): String = "avalanche!" }, SCISSORS("peace"), PAPER("flat"); } ``` ### Anonymous Inner Classes In the enum code, we used `TypeSpec.anonymousClassBuilder()`. Anonymous inner classes can also be used in code blocks. They are values that can be referenced with `%L`: ```kotlin val comparator = TypeSpec.anonymousClassBuilder() .addSuperinterface(Comparator::class.parameterizedBy(String::class)) .addFunction(FunSpec.builder("compare") .addModifiers(KModifier.OVERRIDE) .addParameter("a", String::class) .addParameter("b", String::class) .returns(Int::class) .addStatement("return %N.length - %N.length", "a", "b") .build()) .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addFunction(FunSpec.builder("sortByLength") .addParameter("strings", List::class.parameterizedBy(String::class)) .addStatement("%N.sortedWith(%L)", "strings", comparator) .build()) .build() ``` This generates a method that contains a class that contains a method: ```kotlin class HelloWorld { fun sortByLength(strings: List<String>) { strings.sortedWith(object : Comparator<String> { override fun compare(a: String, b: String): Int = a.length - b.length }) } } ``` One particularly tricky part of defining anonymous inner classes is the arguments to the superclass constructor. To pass them use `TypeSpec.Builder`'s `addSuperclassConstructorParameter()` method. ### Annotations Simple annotations are easy: ```kotlin val test = FunSpec.builder("test string equality") .addAnnotation(Test::class) .addStatement("assertThat(%1S).isEqualTo(%1S)", "foo") .build() ``` Which generates this function with an `@Test` annotation: ```kotlin @Test fun `test string equality`() { assertThat("foo").isEqualTo("foo") } ``` Use `AnnotationSpec.builder()` to set properties on annotations: ```kotlin val logRecord = FunSpec.builder("recordEvent") .addModifiers(KModifier.ABSTRACT) .addAnnotation(AnnotationSpec.builder(Headers::class) .addMember("accept = %S", "application/json; charset=utf-8") .addMember("userAgent = %S", "Square Cash") .build()) .addParameter("logRecord", LogRecord::class) .returns(LogReceipt::class) .build() ``` Which generates this annotation with `accept` and `userAgent` properties: ```kotlin @Headers( accept = "application/json; charset=utf-8", userAgent = "Square Cash" ) abstract fun recordEvent(logRecord: LogRecord): LogReceipt ``` When you get fancy, annotation values can be annotations themselves. Use `%L` for embedded annotations: ```kotlin val headerList = ClassName("", "HeaderList") val header = ClassName("", "Header") val logRecord = FunSpec.builder("recordEvent") .addModifiers(KModifier.ABSTRACT) .addAnnotation(AnnotationSpec.builder(headerList) .addMember( "[\n⇥%L,\n%L⇤\n]", AnnotationSpec.builder(header) .addMember("name = %S", "Accept") .addMember("value = %S", "application/json; charset=utf-8") .build(), AnnotationSpec.builder(header) .addMember("name = %S", "User-Agent") .addMember("value = %S", "Square Cash") .build()) .build()) .addParameter("logRecord", logRecordName) .returns(logReceipt) .build() ``` Which generates this: ```kotlin @HeaderList([ Header(name = "Accept", value = "application/json; charset=utf-8"), Header(name = "User-Agent", value = "Square Cash") ]) abstract fun recordEvent(logRecord: LogRecord): LogReceipt ``` KotlinPoet supports use-site targets for annotations: ```kotlin val utils = FileSpec.builder("com.example", "Utils") .addAnnotation(AnnotationSpec.builder(JvmName::class) .useSiteTarget(UseSiteTarget.FILE) .build()) .addFunction(FunSpec.builder("abs") .receiver(Int::class) .returns(Int::class) .addStatement("return if (this < 0) -this else this") .build()) .build() ``` Will output this: ```kotlin @file:JvmName package com.example import kotlin.Int import kotlin.jvm.JvmName fun Int.abs(): Int = if (this < 0) -this else this ``` ### Type Aliases KotlinPoet provides API for creating Type Aliases, which supports simple class names, parameterized types and lambdas: ```kotlin val fileTable = Map::class.asClassName() .parameterizedBy(TypeVariableName("K"), Set::class.parameterizedBy(File::class)) val predicate = LambdaTypeName.get(parameters = *arrayOf(TypeVariableName("T")), returnType = Boolean::class.asClassName()) val helloWorld = FileSpec.builder("com.example", "HelloWorld") .addTypeAlias(TypeAliasSpec.builder("Word", String::class).build()) .addTypeAlias(TypeAliasSpec.builder("FileTable<K>", fileTable).build()) .addTypeAlias(TypeAliasSpec.builder("Predicate<T>", predicate).build()) .build() ``` Which generates the following: ```kotlin package com.example import java.io.File import kotlin.Boolean import kotlin.String import kotlin.collections.Map import kotlin.collections.Set typealias Word = String typealias FileTable<K> = Map<K, Set<File>> typealias Predicate<T> = (T) -> Boolean ``` ### Callable References [Callable references](https://kotlinlang.org/docs/reference/reflection.html#callable-references) to constructors, functions, and properties may be emitted via: - `ClassName.constructorReference()` for constructors - `MemberName.reference()` for functions and properties For example, ```kotlin val helloClass = ClassName("com.example.hello", "Hello") val worldFunction: MemberName = helloClass.member("world") val byeProperty: MemberName = helloClass.nestedClass("World").member("bye") val factoriesFun = FunSpec.builder("factories") .addStatement("val hello = %L", helloClass.constructorReference()) .addStatement("val world = %L", worldFunction.reference()) .addStatement("val bye = %L", byeProperty.reference()) .build() FileSpec.builder("com.example", "HelloWorld") .addFunction(factoriesFun) .build() ``` would generate: ```kotlin package com.example import com.example.hello.Hello fun factories() { val hello = ::Hello val world = Hello::world val bye = Hello.World::bye } ``` Top-level classes and members with conflicting names may require aliased imports, as with [member names](#m-for-members). Download -------- Download [the latest .jar][dl] or depend via Maven: ```xml <dependency> <groupId>com.squareup</groupId> <artifactId>kotlinpoet</artifactId> <version>1.6.0</version> </dependency> ``` or Gradle: ```groovy implementation("com.squareup:kotlinpoet:1.6.0") ``` Snapshots of the development version are available in [Sonatype's `snapshots` repository][snap]. License ------- Copyright 2017 Square, Inc. 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. [dl]: https://search.maven.org/remote_content?g=com.squareup&a=kotlinpoet&v=LATEST [snap]: https://oss.sonatype.org/content/repositories/snapshots/com/squareup/kotlinpoet/ [kdoc]: https://square.github.io/kotlinpoet/1.x/kotlinpoet/com.squareup.kotlinpoet/ [javapoet]: https://github.com/square/javapoet/ [formatter]: https://developer.android.com/reference/java/util/Formatter.html
{ "pile_set_name": "Github" }
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.vcs.log.ui.actions; import com.intellij.vcs.log.impl.MainVcsLogUiProperties; import com.intellij.vcs.log.impl.VcsLogUiProperties; public class EnableFilterByRegexAction extends BooleanPropertyToggleAction { @Override protected VcsLogUiProperties.VcsLogUiProperty<Boolean> getProperty() { return MainVcsLogUiProperties.TEXT_FILTER_REGEX; } }
{ "pile_set_name": "Github" }
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package http2 import "math" // NewRandomWriteScheduler constructs a WriteScheduler that ignores HTTP/2 // priorities. Control frames like SETTINGS and PING are written before DATA // frames, but if no control frames are queued and multiple streams have queued // HEADERS or DATA frames, Pop selects a ready stream arbitrarily. func NewRandomWriteScheduler() WriteScheduler { return &randomWriteScheduler{sq: make(map[uint32]*writeQueue)} } type randomWriteScheduler struct { // zero are frames not associated with a specific stream. zero writeQueue // sq contains the stream-specific queues, keyed by stream ID. // When a stream is idle or closed, it's deleted from the map. sq map[uint32]*writeQueue // pool of empty queues for reuse. queuePool writeQueuePool } func (ws *randomWriteScheduler) OpenStream(streamID uint32, options OpenStreamOptions) { // no-op: idle streams are not tracked } func (ws *randomWriteScheduler) CloseStream(streamID uint32) { q, ok := ws.sq[streamID] if !ok { return } delete(ws.sq, streamID) ws.queuePool.put(q) } func (ws *randomWriteScheduler) AdjustStream(streamID uint32, priority PriorityParam) { // no-op: priorities are ignored } func (ws *randomWriteScheduler) Push(wr FrameWriteRequest) { id := wr.StreamID() if id == 0 { ws.zero.push(wr) return } q, ok := ws.sq[id] if !ok { q = ws.queuePool.get() ws.sq[id] = q } q.push(wr) } func (ws *randomWriteScheduler) Pop() (FrameWriteRequest, bool) { // Control frames first. if !ws.zero.empty() { return ws.zero.shift(), true } // Iterate over all non-idle streams until finding one that can be consumed. for _, q := range ws.sq { if wr, ok := q.consume(math.MaxInt32); ok { return wr, true } } return FrameWriteRequest{}, false }
{ "pile_set_name": "Github" }
from __future__ import print_function, division import argparse import torch import torch.nn as nn import torch.optim as optim from torchvision import datasets, models, transforms import os import smdebug.pytorch as smd from smdebug import modes from smdebug.core.modes import ModeKeys from custom_hook import CustomHook def get_dataloaders(batch_size_train, batch_size_val): train_transform = transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) val_transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) dataset = datasets.ImageFolder(os.environ['SM_CHANNEL_TRAIN'], train_transform) train_dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size_train, shuffle=True) dataset = datasets.ImageFolder(os.environ['SM_CHANNEL_TEST'], val_transform) val_dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size_val, shuffle=False) return train_dataloader, val_dataloader def relu_inplace(model): for child_name, child in model.named_children(): if isinstance(child, torch.nn.ReLU): setattr(model, child_name, torch.nn.ReLU(inplace=False)) else: relu_inplace(child) def train_model(epochs, batch_size_train, batch_size_val): #check if GPU is available and set context device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") #get pretrained ResNet model model = models.resnet18(pretrained=True) #replace inplace operators relu_inplace(model) nfeatures = model.fc.in_features #traffic sign dataset has 43 classes model.fc = nn.Linear(nfeatures, 43) #copy model to GPU or CPU model = model.to(device) # loss for multi label classification loss_function = nn.CrossEntropyLoss() # optimizer optimizer = optim.SGD(model.parameters(), lr=args.learning_rate, momentum=args.momentum) #configure smdebug hook: #save all iterations from validation phase #save only first iteration from training phase save_config = smd.SaveConfig(mode_save_configs={ smd.modes.TRAIN: smd.SaveConfigMode(save_steps=[0]), smd.modes.EVAL: smd.SaveConfigMode(save_interval=1) }) #create custom hook that has a customized forward function, so that we can get gradients of outputs hook = CustomHook(args.smdebug_dir, save_config=save_config, include_regex='.*bn|.*bias|.*downsample|.*ResNet_input|.*image|.*fc_output' ) #register hook hook.register_module(model) #get the dataloaders for train and test data train_loader, val_loader = get_dataloaders(batch_size_train, batch_size_val) #training loop for epoch in range(epochs): epoch_loss = 0 epoch_acc = 0 #set hook training phase hook.set_mode(modes.TRAIN) model.train() for inputs, labels in train_loader: inputs = inputs.to(device).requires_grad_() labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward pass outputs = model(inputs) #get predictions _, preds = torch.max(outputs, 1) #compute loss loss = loss_function(outputs, labels) #backward pass loss.backward() #optimize parameters optimizer.step() # statistics epoch_loss += loss.item() epoch_acc += torch.sum(preds == labels.data) #set hook validation phase hook.set_mode(modes.EVAL) model.eval() for inputs, labels in val_loader: inputs = inputs.to(device).requires_grad_() hook.image_gradients(inputs) model.eval() #forward pass outputs = model(inputs) #get prediction predicted_class = outputs.data.max(1, keepdim=True)[1] agg = 0 for i in range(outputs.shape[0]): agg += outputs[i,predicted_class[i]] model.zero_grad() #compute gradients with respect to outputs agg.backward() print('Epoch {}/{} Loss: {:.4f} Acc: {:.4f}'.format( epoch, epochs - 1, epoch_loss, epoch_acc)) return model if __name__ =='__main__': parser = argparse.ArgumentParser() # hyperparameters sent by the client are passed as command-line arguments to the script. parser.add_argument('--epochs', type=int, default=20) parser.add_argument('--batch_size_train', type=int, default=64) parser.add_argument('--batch_size_val', type=int, default=4) parser.add_argument('--learning_rate', type=float, default=0.001) parser.add_argument('--momentum', type=float, default=0.9) # Data, model, and output directories parser.add_argument('--smdebug_dir', type=str, default=None) #parse arguments args, _ = parser.parse_known_args() #train model model = train_model(epochs=args.epochs, batch_size_train=args.batch_size_train, batch_size_val=args.batch_size_val)
{ "pile_set_name": "Github" }
# Translation of Odoo Server. # This file contains the translation of the following modules: # * mass_mailing_crm # # Translators: # Kostas Goutoudis <[email protected]>, 2019 # msgid "" msgstr "" "Project-Id-Version: Odoo Server 13.0\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-10-07 07:12+0000\n" "PO-Revision-Date: 2019-08-26 09:11+0000\n" "Last-Translator: Kostas Goutoudis <[email protected]>, 2019\n" "Language-Team: Greek (https://www.transifex.com/odoo/teams/41243/el/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Language: el\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #. module: mass_mailing_crm #: model:ir.model.fields,field_description:mass_mailing_crm.field_mailing_mailing__crm_lead_count msgid "Lead Count" msgstr "" #. module: mass_mailing_crm #: model:mailing.mailing,name:mass_mailing_crm.mass_mail_lead_0 #: model:utm.source,name:mass_mailing_crm.mass_mail_lead_0_utm_source msgid "Lead Recall" msgstr "" #. module: mass_mailing_crm #: model_terms:ir.ui.view,arch_db:mass_mailing_crm.mailing_mailing_view_form msgid "Leads" msgstr "Συστάσεις" #. module: mass_mailing_crm #: model:ir.model,name:mass_mailing_crm.model_mailing_mailing msgid "Mass Mailing" msgstr "Ομαδική Αλληλογραφία" #. module: mass_mailing_crm #: model_terms:ir.ui.view,arch_db:mass_mailing_crm.mailing_mailing_view_form msgid "Opportunities" msgstr "Ευκαιρίες" #. module: mass_mailing_crm #: model:ir.model.fields,field_description:mass_mailing_crm.field_mailing_mailing__crm_opportunities_count msgid "Opportunities Count" msgstr "" #. module: mass_mailing_crm #: model:ir.model.fields,field_description:mass_mailing_crm.field_mailing_mailing__crm_lead_activated msgid "Use Leads" msgstr "" #. module: mass_mailing_crm #: model:mailing.mailing,subject:mass_mailing_crm.mass_mail_lead_0 msgid "We want to hear from you !" msgstr ""
{ "pile_set_name": "Github" }
GLIBC_2.0 __ctype_get_mb_cur_max F
{ "pile_set_name": "Github" }
/** * OWASP Benchmark Project v1.2 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark 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, version 2. * * The OWASP Benchmark 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. * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value="/pathtraver-01/BenchmarkTest01159") public class BenchmarkTest01159 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String param = ""; java.util.Enumeration<String> headers = request.getHeaders("BenchmarkTest01159"); if (headers != null && headers.hasMoreElements()) { param = headers.nextElement(); // just grab first element } // URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters(). param = java.net.URLDecoder.decode(param, "UTF-8"); String bar = new Test().doSomething(request, param); String fileName = null; java.io.FileInputStream fis = null; try { fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar; fis = new java.io.FileInputStream(fileName); byte[] b = new byte[1000]; int size = fis.read(b); response.getWriter().println( "The beginning of file: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName) + "' is:\n\n" ); response.getWriter().println( org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(b,0,size)) ); } catch (Exception e) { System.out.println("Couldn't open FileInputStream on file: '" + fileName + "'"); // System.out.println("File exception caught and swallowed: " + e.getMessage()); } finally { if (fis != null) { try { fis.close(); fis = null; } catch (Exception e) { // we tried... } } } } // end doPost private class Test { public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException { // Chain a bunch of propagators in sequence String a54259 = param; //assign StringBuilder b54259 = new StringBuilder(a54259); // stick in stringbuilder b54259.append(" SafeStuff"); // append some safe content b54259.replace(b54259.length()-"Chars".length(),b54259.length(),"Chars"); //replace some of the end content java.util.HashMap<String,Object> map54259 = new java.util.HashMap<String,Object>(); map54259.put("key54259", b54259.toString()); // put in a collection String c54259 = (String)map54259.get("key54259"); // get it back out String d54259 = c54259.substring(0,c54259.length()-1); // extract most of it String e54259 = new String( org.apache.commons.codec.binary.Base64.decodeBase64( org.apache.commons.codec.binary.Base64.encodeBase64( d54259.getBytes() ) )); // B64 encode and decode it String f54259 = e54259.split(" ")[0]; // split it on a space org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing(); String g54259 = "barbarians_at_the_gate"; // This is static so this whole flow is 'safe' String bar = thing.doSomething(g54259); // reflection return bar; } } // end innerclass Test } // end DataflowThruInnerClass
{ "pile_set_name": "Github" }
Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: git-lfs Source: https://github.com/git-lfs/git-lfs Files: * Copyright: 2013-2015 Github, Inc. License: Expat Copyright (c) GitHub, Inc. and Git LFS contributors . 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. Files: vendor/github.com/alexbrainman/sspi/* vendor/golang.org/x/* vendor/github.com/jcmturner/gofork/* Copyright: 2009, 2012, 2017 The Go Authors License: Go 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. Files: vendor/github.com/davecgh/go-spew/* Copyright: 2012-2016 Dave Collins License: ISC Copyright (c) 2012-2016 Dave Collins <[email protected]> . Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. . THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Files: vendor/github.com/pkg/errors/* Copyright: 2015 Dave Cheney License: BSD-2-Clause 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. . 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 HOLDER 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. Files: vendor/github.com/pmezard/go-difflib/* Copyright: 2013 Patrick Mezard License: BSD-3-Clause 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. The names of its contributors may not 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 HOLDER 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. Files: vendor/github.com/hashicorp/go-uuid/* License: MPL-2.0 The complete text of the Mozilla Public License 2.0 can be found in the file `/usr/share/common-licenses/MPL-2.0'. Files: vendor/github.com/inconshreveable/mousetrap/* Copyright: 2014 Alan Shreve License: Apache-2.0 The complete text of the Apache License 2.0 can be found in the file `/usr/share/common-licenses/Apache-2.0`. Files: vendor/github.com/avast/retry-go Copyright: 2017 Avast License: Expat Files: vendor/github.com/dpotapov/go-spnego/* Copyright: 2018 Daniel Potapov License: Expat Files: vendor/github.com/mattn/go-isatty/* Copyright: Yasuhiro MATSUMOTO License: Expat Files: vendor/github.com/rubyist/tracerx/* Copyright: 2014 Scott Barron License: Expat Files: vendor/github.com/spf13/cobra/* vendor/github.com/xeipuuv/* vendor/gopkg.in/jcmturner/* License: Apache-2.0 Files: vendor/github.com/spf13/pflag/* Copyright: 2012 Alex Ogier 2012 The Go Authors License: Go Files: vendor/github.com/ssgelm/cookiejarparser/* Copyright: 2019 Stephen Gelman License: Expat Files: vendor/github.com/stretchr/testify/* Copyright: 2012-2013 Mat Ryer and Tyler Bunnell License: Expat
{ "pile_set_name": "Github" }
package com.hp.hpl.sparta; import java.util.Hashtable; /** This utility class allows you to configure some low-level behavior * of the Sparta code such as caching and String interning. * If you do not set any of the configurations here then sparta will use * default implementations that will work in smaller JVMs such as J2ME. * However if you are running in a bigger JVM then you will get better * performance if you ocerride the defaults as described in the method * descriptions below. Note that these static methods need to be called * <b>before</b> any Sparta classes are loaded, therefore it is best to * call them in a static block at the very beginning of your main application * class. * <blockquote><small> Copyright (C) 2003 Hewlett-Packard Company. This file is part of Sparta, an XML Parser, DOM, and XPath library. 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 License, 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. </small></blockquote> @see <a "href="doc-files/LGPL.txt">GNU Lesser General Public License</a> @version $Date: 2003/07/18 01:48:41 $ $Revision: 1.2 $ @author Eamonn O'Brien-Strain * */ public class Sparta { /** Used internally by Sparta code to intern strings because the * String.intern method is not supported in older and smaller JVMs. * @see String#intern */ static public String intern(String s) { return internment_.intern(s); } /** Pass an object that implements this interface to setInternment. */ static public interface Internment { String intern(String s); } /** Change the String intern to something custom. For example if * you are running on a modern full J2EE or JDSE JVM you almost certainly * want to tell Sparta to use the standard String.inter method like this: <PRE> public class MyApplication { static{ Sparta.setInternment(new Sparta.Internment(){ public String intern(String s) { return s.intern(); } }); } public static void main(String[] args) { ... </PRE> * */ static public void setInternment(Internment i) { internment_ = i; } /** The default internment used internally that does not rely on * String.intern being supported by the JVM. */ static private Internment internment_ = new Internment() { private final Hashtable strings_ = new Hashtable(); public String intern(String s) { String ss = (String) strings_.get(s); if (ss == null) { strings_.put(s, s); return s; } else return ss; } }; ////////////////////////////////////////////////////////////// /** What a CacheFactory generates. Used internally to cache collections * of objects.*/ static public interface Cache { Object get(Object key); Object put(Object key, Object value); int size(); } /** You should pass an object that implements this interface to * setCacheFactory. */ static public interface CacheFactory { Cache create(); } /** Used internally to create a cache. */ static Cache newCache() { return cacheFactory_.create(); } /** Change the caching to something custom. The default CacheFactory * simply creates Hashtables which grow without bound. If you are * running Sparta in a long-lived application and you want to avoid * memory leaks you should use caches that automatically evict using, for * example an LRU mechanism or soft reference. For example if you have * a class called LruMap that sub-classes from hava.util.Map then you * can tell Sparta to use that by as follows <PRE> * public class MyApplication { static private class LruCache extends LruMap implements Sparta.Cache {} static{ Sparta.setCacheFactory(new Sparta.CacheFactory(){ public Sparta.Cache create() { return new SoftCache(); } }); } public static void main(String[] args) { ... </PRE> * */ static public void setCacheFactory(CacheFactory f) { cacheFactory_ = f; } static private class HashtableCache extends Hashtable implements Cache {} static private CacheFactory cacheFactory_ = new CacheFactory() { public Cache create() { return new HashtableCache(); } }; }
{ "pile_set_name": "Github" }
# Copyright (c) 2012-2019, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 8.1.0 from . import AWSObject from . import AWSProperty from .validators import integer class EventBus(AWSObject): resource_type = "AWS::Events::EventBus" props = { 'EventSourceName': (basestring, False), 'Name': (basestring, True), } class Condition(AWSProperty): props = { 'Key': (basestring, False), 'Type': (basestring, False), 'Value': (basestring, False), } class EventBusPolicy(AWSObject): resource_type = "AWS::Events::EventBusPolicy" props = { 'Action': (basestring, True), 'Condition': (Condition, False), 'EventBusName': (basestring, False), 'Principal': (basestring, True), 'StatementId': (basestring, True), } class BatchArrayProperties(AWSProperty): props = { 'Size': (integer, False), } class BatchRetryStrategy(AWSProperty): props = { 'Attempts': (integer, False), } class BatchParameters(AWSProperty): props = { 'ArrayProperties': (BatchArrayProperties, False), 'JobDefinition': (basestring, True), 'JobName': (basestring, True), 'RetryStrategy': (BatchRetryStrategy, False), } class AwsVpcConfiguration(AWSProperty): props = { 'AssignPublicIp': (basestring, False), 'SecurityGroups': ([basestring], False), 'Subnets': ([basestring], True), } class NetworkConfiguration(AWSProperty): props = { 'AwsVpcConfiguration': (AwsVpcConfiguration, False), } class EcsParameters(AWSProperty): props = { 'Group': (basestring, False), 'LaunchType': (basestring, False), 'NetworkConfiguration': (NetworkConfiguration, False), 'PlatformVersion': (basestring, False), 'TaskCount': (integer, False), 'TaskDefinitionArn': (basestring, True), } class HttpParameters(AWSProperty): props = { 'HeaderParameters': (dict, False), 'PathParameterValues': ([basestring], False), 'QueryStringParameters': (dict, False), } class InputTransformer(AWSProperty): props = { 'InputPathsMap': (dict, False), 'InputTemplate': (basestring, True), } class KinesisParameters(AWSProperty): props = { 'PartitionKeyPath': (basestring, True), } class RunCommandTarget(AWSProperty): props = { 'Key': (basestring, True), 'Values': ([basestring], True), } class RunCommandParameters(AWSProperty): props = { 'RunCommandTargets': ([RunCommandTarget], True), } class SqsParameters(AWSProperty): props = { 'MessageGroupId': (basestring, True), } class Target(AWSProperty): props = { 'Arn': (basestring, True), 'BatchParameters': (BatchParameters, False), 'EcsParameters': (EcsParameters, False), 'HttpParameters': (HttpParameters, False), 'Id': (basestring, True), 'Input': (basestring, False), 'InputPath': (basestring, False), 'InputTransformer': (InputTransformer, False), 'KinesisParameters': (KinesisParameters, False), 'RoleArn': (basestring, False), 'RunCommandParameters': (RunCommandParameters, False), 'SqsParameters': (SqsParameters, False), } class Rule(AWSObject): resource_type = "AWS::Events::Rule" props = { 'Description': (basestring, False), 'EventBusName': (basestring, False), 'EventPattern': (dict, False), 'Name': (basestring, False), 'RoleArn': (basestring, False), 'ScheduleExpression': (basestring, False), 'State': (basestring, False), 'Targets': ([Target], False), }
{ "pile_set_name": "Github" }
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.impl.internal.loaderwriter.writebehind.operations; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; /** * Interface to implement batch operations that are executed on a cache writer * * @author Geert Bevin * @author Chris Dennis * */ public interface BatchOperation<K, V> { /** * Perform the batch operation for a particular batch writer * */ void performOperation(CacheLoaderWriter<K, V> cacheLoaderWriter) throws BulkCacheWritingException, Exception; }
{ "pile_set_name": "Github" }
#!/usr/bin/env bash # # Set up a vm on packstack. Use the iso in RHEL_ISO (defaults to home dir) # set -fv source ./copy_func.sh source ./fix_conf_file.sh openstack_node=${1} ceph_node=${2} RHEL_ISO=${RHEL_ISO:-~/rhel-server-7.2-x86_64-boot.iso} copy_file ${RHEL_ISO} $openstack_node . copy_file execs/run_openstack.sh $openstack_node . 0755 filler=`date +%s` ssh $openstack_node ./run_openstack.sh "${openstack_node}X${filler}" rhel-server-7.2-x86_64-boot.iso ssh $ceph_node sudo ceph df
{ "pile_set_name": "Github" }
# Application Structure Clone the [dinoloop-starter](https://github.com/ParallelTask/dinoloop-starter) and install the dependencies. Here are few steps: ``` git clone https://github.com/ParallelTask/dinoloop-starter.git cd dinoloop-starter npm install ``` ## Files Open project in your favorite editor (Recommended [VSCode](https://code.visualstudio.com/)). You will find bare minimum files in order to work with Dinoloop. ### app.ts ``` import express = require('express'); import bodyParser = require('body-parser'); import { Dino } from 'dinoloop'; import { HomeController } from './controllers/home.controller'; /**** basic express-setup ****/ const app = express(); app.use(bodyParser.json()); // Dino requires express instance // and base-uri to which dino will be mounted const dino = new Dino(app, '/api'); // Dino requires express router too dino.useRouter(() => express.Router()); // Register controller dino.registerController(HomeController); // Bind dino to express dino.bind(); // Start your express app app.listen(8088, () => console.log('Server started on port 8088')); ``` * Make sure to `bind()` dino before you start express. ### home.controller.ts ``` import { ApiController, Controller, HttpGet } from 'dinoloop'; // Set baseUri for all action methods @Controller('/home') export class HomeController extends ApiController { // Responds to HttpGet request @HttpGet('/get') get(): string { return 'Hello World!'; } } ```
{ "pile_set_name": "Github" }
cheats = 27 cheat0_desc = "Infinite Lives" cheat0_code = "Z 8 61219 201 0" cheat0_enable = false cheat1_desc = "Immunity" cheat1_code = "Z 8 58518 33 0" cheat1_enable = false cheat2_desc = "Infinite Time" cheat2_code = "Z 8 56734 182 0" cheat2_enable = false cheat3_desc = "Infinite Letter Spells" cheat3_code = "M 8 61853 183 0\nZ 8 62184 201 0" cheat3_enable = false cheat4_desc = "Infinite Changeling Spells" cheat4_code = "M 8 57526 182 0\nZ 8 62184 201 0" cheat4_enable = false cheat5_desc = "Infinite Ingredients" cheat5_code = "Z 8 61657 182 0" cheat5_enable = false cheat6_desc = "Always Have Free Letter" cheat6_code = "Z 8 61834 195 0" cheat6_enable = false cheat7_desc = "Open All Letters" cheat7_code = "Z 8 61969 0 0" cheat7_enable = false cheat8_desc = "Letter Gates Doesn't Disappear" cheat8_code = "Z 8 62011 55 0" cheat8_enable = false cheat9_desc = "Lightning Spells 99% (max)" cheat9_code = "Z 8 56594 153 0" cheat9_enable = false cheat10_desc = "Fireball Spells max" cheat10_code = "Z 8 56595 153 0" cheat10_enable = false cheat11_desc = "Hallucinate Spells max" cheat11_code = "Z 8 56596 153 0" cheat11_enable = false cheat12_desc = "Freeze Spells max" cheat12_code = "Z 8 56597 153 0" cheat12_enable = false cheat13_desc = "Stun Spells max" cheat13_code = "Z 8 56598 153 0" cheat13_enable = false cheat14_desc = "Changeling Spells max" cheat14_code = "Z 8 56599 153 0" cheat14_enable = false cheat15_desc = "Reveal Spells max" cheat15_code = "Z 8 56600 153 0" cheat15_enable = false cheat16_desc = "Protection Spells max" cheat16_code = "Z 8 56601 153 0" cheat16_enable = false cheat17_desc = "Transport Spells max" cheat17_code = "Z 8 56602 153 0" cheat17_enable = false cheat18_desc = "Letter Spells max" cheat18_code = "Z 8 56603 153 0" cheat18_enable = false cheat19_desc = "Worm Ingredients 7 (max)" cheat19_code = "Z 8 56586 7 0" cheat19_enable = false cheat20_desc = "Caterpillar Ingredients max" cheat20_code = "Z 8 56587 7 0" cheat20_enable = false cheat21_desc = "Frog Ingredients max" cheat21_code = "Z 8 56588 7 0" cheat21_enable = false cheat22_desc = "Cockroach Ingredients max" cheat22_code = "Z 8 56589 7 0" cheat22_enable = false cheat23_desc = "Bumble-Bee Ingredients max" cheat23_code = "Z 8 56590 7 0" cheat23_enable = false cheat24_desc = "Moth Ingredients max" cheat24_code = "Z 8 56591 7 0" cheat24_enable = false cheat25_desc = "Mosquito Ingredients max" cheat25_code = "Z 8 56592 7 0" cheat25_enable = false cheat26_desc = "Butterfly Ingredients max" cheat26_code = "Z 8 56593 7 0" cheat26_enable = false
{ "pile_set_name": "Github" }
#![cfg_attr(feature = "strict", deny(warnings, missing_docs))] //! The flux crate handles the parsing and semantic analysis of flux source //! code. extern crate chrono; #[macro_use] extern crate serde_derive; extern crate serde_aux; pub mod ast; pub mod formatter; pub mod parser; pub mod scanner; pub mod semantic; use std::error; use std::fmt; pub use ast::DEFAULT_PACKAGE_NAME; /// An error that can occur due to problems in ast generation or semantic /// analysis. #[derive(Debug, Clone)] pub struct Error { /// Message. pub msg: String, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.msg) } } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error + 'static)> { None } } impl From<String> for Error { fn from(msg: String) -> Self { Error { msg } } } impl From<&str> for Error { fn from(msg: &str) -> Self { Error { msg: String::from(msg), } } } impl From<semantic::nodes::Error> for Error { fn from(sn_err: semantic::nodes::Error) -> Self { Error { msg: sn_err.to_string(), } } } impl From<semantic::check::Error> for Error { fn from(err: semantic::check::Error) -> Self { Error { msg: format!("{}", err), } } }
{ "pile_set_name": "Github" }
From 9a0067e0fa4636efa37212d7d56376f8ec02a802 Mon Sep 17 00:00:00 2001 From: Mart Raudsepp <[email protected]> Date: Sat, 21 Mar 2020 18:40:09 +0200 Subject: [PATCH] build: Workaround chmod on root filesystem sandbox issue Just delete this again, but keep the server enabling from commit ec662d01dac16b81; the suid part has to be handled at package level instead. --- libgtop-sysdeps.m4 | 1 - 1 file changed, 1 deletion(-) diff --git a/libgtop-sysdeps.m4 b/libgtop-sysdeps.m4 index b363dae0..81aa5350 100644 --- a/libgtop-sysdeps.m4 +++ b/libgtop-sysdeps.m4 @@ -36,7 +36,6 @@ AC_DEFUN([GNOME_LIBGTOP_SYSDEPS],[ libgtop_need_server=yes libgtop_sysdeps_private_mountlist=yes libgtop_sysdeps_private_fsusage=yes - libgtop_postinstall='chown root $(bindir)/libgtop_server2 && chmod 4755 $(bindir)/libgtop_server2' ;; netbsd*|bsdi*) libgtop_sysdeps_dir=bsd -- 2.20.1
{ "pile_set_name": "Github" }
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SU2 configuration file % % Case description: 3D, inviscid flow inside a pipe with rotating sections % % nearest neighbour approach holds at sliding interface % % Author: G. Gori % % Institution: Politecnico di Milano % % Date: Oct 5th, 2016 % % File Version 4.3.0 "cardinal" % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Enable multizone mode MULTIZONE= YES % % List of config files for zone specific options CONFIG_LIST= (zone_1.cfg, zone_2.cfg, zone_3.cfg, zone_4.cfg, zone_5.cfg) % TIME_DOMAIN=YES % TIME_STEP= 0.1 % TIME_ITER= 10 % OUTER_ITER=200 % INNER_ITER=1 % % ------------- DIRECT, ADJOINT, AND LINEARIZED PROBLEM DEFINITION ------------% % % Physical governing equations (EULER, NAVIER_STOKES) SOLVER= EULER % % Mathematical problem (DIRECT, ADJOINT, LINEARIZED) MATH_PROBLEM= DIRECT % % Restart solution (NO, YES) RESTART_SOL= NO % % ------------------------- UNSTEADY SIMULATION -------------------------------% % % Unsteady simulation (NO, TIME_STEPPING, DUAL_TIME_STEPPING-1ST_ORDER, % DUAL_TIME_STEPPING-2ND_ORDER) TIME_MARCHING= DUAL_TIME_STEPPING-2ND_ORDER % -------------------- COMPRESSIBLE FREE-STREAM DEFINITION --------------------% % % Mach number (non-dimensional, based on the free-stream values) MACH_NUMBER= 3.0 % % Angle of attack (degrees, only for compressible flows) AOA= 0.0 % % Free-stream pressure (101325.0 N/m^2 by default, only Euler flows) FREESTREAM_PRESSURE= 95750 % % Free-stream temperature (273.15 K by default) FREESTREAM_TEMPERATURE= 288.15 % % Free-stream Turbulence Intensity FREESTREAM_TURBULENCEINTENSITY = 0.1 % % Free-stream Turbulent to Laminar viscosity ratio FREESTREAM_TURB2LAMVISCRATIO = 100.0 % % Free-stream option to choose if you want to use Density (DENSITY_FS) or Temperature (TEMPERATURE_FS) to initialize the solution FREESTREAM_OPTION= TEMPERATURE_FS % %Init option to choose between Reynolds (default) or thermodynamics quantities for initializing the solution (REYNOLDS, TD_CONDITIONS) INIT_OPTION= TD_CONDITIONS % % % -------------------- BOUNDARY CONDITION DEFINITION --------------------------% % % Euler wall boundary marker(s) (NONE = no marker) MARKER_EULER= ( intake_sidewall, component_sidewall_1, component_sidewall_2, component_sidewall_3, component_sidewall_4 ) % % Riemann boundary marker(s) % Format inlet: ( marker, TOTAL_CONDITIONS_PT, Total Pressure, Total Temperature, Flow dir-x, Flow dir-y, Flow dir-z) % Format outlet: ( marker, type, STATIC_PRESSURE, Static Pressure, 0.0, 0.0, 0.0, 0.0) % MARKER_RIEMANN= (intake_upper_inlet, STATIC_SUPERSONIC_INFLOW_PT, 95750, 288.15, 3.0, 0.0, 0.0, intake_lower_inlet, STATIC_SUPERSONIC_INFLOW_PT, 95750, 288.15, 1.5, 0.0, 0.0, outlet_interface_4 STATIC_PRESSURE, 95750.0, 0.0, 0.0, 0.0, 0.0 ) % % Zone interaction boundary definition MARKER_ZONE_INTERFACE= ( intake_interface, inlet_interface_1, outlet_interface_1, inlet_interface_2, outlet_interface_2, inlet_interface_3, outlet_interface_3, inlet_interface_4 ) % MARKER_FLUID_INTERFACE= ( intake_interface, inlet_interface_1, outlet_interface_1, inlet_interface_2, outlet_interface_2, inlet_interface_3, outlet_interface_3, inlet_interface_4 ) % % KIND_INTERPOLATION= WEIGHTED_AVERAGE % % % % % ------------- COMMON PARAMETERS DEFINING THE NUMERICAL METHOD ---------------% % % Numerical method for spatial gradients (GREEN_GAUSS, WEIGHTED_LEAST_SQUARES) NUM_METHOD_GRAD= WEIGHTED_LEAST_SQUARES % % Courant-Friedrichs-Lewy condition of the finest grid CFL_NUMBER= 5.0 % % Adaptive CFL number (NO, YES) CFL_ADAPT= NO % % Parameters of the adaptive CFL number (factor down, factor up, CFL min value, CFL max value ) CFL_ADAPT_PARAM= ( 0.3, 0.5, 1.0, 1000.0) % % % % ------------------------ LINEAR SOLVER DEFINITION ---------------------------% % % Linear solver or smoother for implicit formulations (BCGSTAB, FGMRES, SMOOTHER) LINEAR_SOLVER= FGMRES % % Preconditioner of the Krylov linear solver (ILU, LU_SGS, LINELET, JACOBI) LINEAR_SOLVER_PREC= LU_SGS % % Min error of the linear solver for the implicit formulation LINEAR_SOLVER_ERROR= 1E-4 % % Max number of iterations of the linear solver for the implicit formulation LINEAR_SOLVER_ITER= 5 % % % % -------------------------- MULTIGRID PARAMETERS -----------------------------% % % Multi-Grid Levels (0 = no multi-grid) MGLEVEL= 0 % % Multigrid pre-smoothing level MG_PRE_SMOOTH= ( 1, 2, 3, 3 ) % % Multigrid post-smoothing level MG_POST_SMOOTH= ( 0, 0, 0, 0 ) % % Jacobi implicit smoothing of the correction MG_CORRECTION_SMOOTH= ( 0, 0, 0, 0 ) % % Damping factor for the residual restriction MG_DAMP_RESTRICTION= 0.75 % % Damping factor for the correction prolongation MG_DAMP_PROLONGATION= 0.75 % % % % ----------------------- SLOPE LIMITER DEFINITION ----------------------------% % % Coefficient for the limiter VENKAT_LIMITER_COEFF= 0.05 % % Freeze the value of the limiter after a number of iterations LIMITER_ITER= 999999 % % % % -------------------- FLOW NUMERICAL METHOD DEFINITION -----------------------% % % Convective numerical method (JST, ROE, AUSM, HLLC) CONV_NUM_METHOD_FLOW= ROE % % Monotonic Upwind Scheme for Conservation Laws (TVD) in the flow equations. % Required for 2nd order upwind schemes (NO, YES) MUSCL_FLOW= YES % % Entropy fix coefficient (0.0 implies no entropy fixing, 1.0 implies scalar artificial dissipation, 0.001 default) ENTROPY_FIX_COEFF= 0.001 % % 2nd and 4th order artificial dissipation coefficients JST_SENSOR_COEFF= ( 0.5, 0.02 ) % % Slope limiter (NONE, VENKATAKRISHNAN, VENKATAKRISHNAN_WANG, % BARTH_JESPERSEN, VAN_ALBADA_EDGE) SLOPE_LIMITER_FLOW= NONE % % Time discretization (RUNGE-KUTTA_EXPLICIT, EULER_IMPLICIT, EULER_EXPLICIT) TIME_DISCRE_FLOW= EULER_IMPLICIT % % Relaxation coefficient % % % --------------------------- CONVERGENCE PARAMETERS --------------------------% % Convergence criteria (CAUCHY, RESIDUAL) CONV_CRITERIA= RESIDUAL % % Flow functional for the Residual criteria (RHO, RHO_ENERGY) % % % Min value of the residual (log10 of the residual) CONV_RESIDUAL_MINVAL= -16 % % Start convergence criteria at iteration number CONV_STARTITER= 10 % % Number of elements to apply the criteria CONV_CAUCHY_ELEMS= 100 % % Epsilon to control the series convergence CONV_CAUCHY_EPS= 1E-6 % % % % % ------------------------- INPUT/OUTPUT INFORMATION --------------------------% % % Mesh input file MESH_FILENAME= pipe.su2 % % Mesh input file format (SU2, CGNS) MESH_FORMAT= SU2 % % Mesh output file MESH_OUT_FILENAME= su2mesh_per.su2 % % Restart flow input file SOLUTION_FILENAME= restart_flow.dat % % Output file format (PARAVIEW, TECPLOT, STL) TABULAR_FORMAT= CSV % % Output file convergence history (w/o extension) CONV_FILENAME= history % % Output file restart flow RESTART_FILENAME= restart_flow.dat % % Output file flow (w/o extension) variables VOLUME_FILENAME= flow % % Output file surface flow coefficient (w/o extension) SURFACE_FILENAME= surface_flow % % Writing solution file frequency WRT_SOL_FREQ= 50 % % Writing convergence history frequency WRT_CON_FREQ= 1
{ "pile_set_name": "Github" }
{ "_args": [ [ { "raw": "compressible@~2.0.5", "scope": null, "escapedName": "compressible", "name": "compressible", "rawSpec": "~2.0.5", "spec": ">=2.0.5 <2.1.0", "type": "range" }, "/Users/liyuechun/Desktop/demo/ComicBook/node_modules/compression" ] ], "_from": "compressible@>=2.0.5 <2.1.0", "_id": "[email protected]", "_inCache": true, "_location": "/compressible", "_nodeVersion": "4.7.3", "_npmOperationalInternal": { "host": "packages-12-west.internal.npmjs.com", "tmp": "tmp/compressible-2.0.10.tgz_1490330888540_0.3248714415822178" }, "_npmUser": { "name": "dougwilson", "email": "[email protected]" }, "_npmVersion": "2.15.11", "_phantomChildren": {}, "_requested": { "raw": "compressible@~2.0.5", "scope": null, "escapedName": "compressible", "name": "compressible", "rawSpec": "~2.0.5", "spec": ">=2.0.5 <2.1.0", "type": "range" }, "_requiredBy": [ "/compression" ], "_resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.10.tgz", "_shasum": "feda1c7f7617912732b29bf8cf26252a20b9eecd", "_shrinkwrap": null, "_spec": "compressible@~2.0.5", "_where": "/Users/liyuechun/Desktop/demo/ComicBook/node_modules/compression", "bugs": { "url": "https://github.com/jshttp/compressible/issues" }, "contributors": [ { "name": "Douglas Christopher Wilson", "email": "[email protected]" }, { "name": "Jonathan Ong", "email": "[email protected]", "url": "http://jongleberry.com" }, { "name": "Jeremiah Senkpiel", "email": "[email protected]", "url": "https://searchbeam.jit.su" } ], "dependencies": { "mime-db": ">= 1.27.0 < 2" }, "description": "Compressible Content-Type / mime checking", "devDependencies": { "eslint": "3.18.0", "eslint-config-standard": "7.1.0", "eslint-plugin-markdown": "1.0.0-beta.4", "eslint-plugin-promise": "3.5.0", "eslint-plugin-standard": "2.1.1", "istanbul": "0.4.5", "mocha": "~1.21.5" }, "directories": {}, "dist": { "shasum": "feda1c7f7617912732b29bf8cf26252a20b9eecd", "tarball": "https://registry.npmjs.org/compressible/-/compressible-2.0.10.tgz" }, "engines": { "node": ">= 0.6" }, "files": [ "HISTORY.md", "LICENSE", "README.md", "index.js" ], "gitHead": "235bc74b36aa7fe854df88ce2c68242c0a4ca938", "homepage": "https://github.com/jshttp/compressible#readme", "keywords": [ "compress", "gzip", "mime", "content-type" ], "license": "MIT", "maintainers": [ { "name": "defunctzombie", "email": "[email protected]" }, { "name": "dougwilson", "email": "[email protected]" }, { "name": "federomero", "email": "[email protected]" }, { "name": "fishrock123", "email": "[email protected]" }, { "name": "jongleberry", "email": "[email protected]" }, { "name": "mscdex", "email": "[email protected]" }, { "name": "tjholowaychuk", "email": "[email protected]" } ], "name": "compressible", "optionalDependencies": {}, "readme": "ERROR: No README data found!", "repository": { "type": "git", "url": "git+https://github.com/jshttp/compressible.git" }, "scripts": { "lint": "eslint --plugin markdown --ext js,md .", "test": "mocha --reporter spec --bail --check-leaks test/", "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks", "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot --check-leaks" }, "version": "2.0.10" }
{ "pile_set_name": "Github" }
//ошибки которые возвращает бот админке при выполнении команд namespace TaskErr { const int Succesfully = 0; //нет ошибки const int Wrong = 1; //команда не выполнилась const int Param = 2; //неверные параметры const int PluginNotLoad = 3; //не загрузился плагин const int NotCreateDir = 4; //не удалось создать папку const int Runned = 5; //уже запущено const int OutOfMemory = 6; //нехватка памяти const int NotRunInMem = 7; //не удалось стартануть в памяти const int NotExportFunc = 8; //не удалось найти экспортируемые функции в длл const int BadCab = 9; //не удалось распаковать cab архив }
{ "pile_set_name": "Github" }
# Copyright 2014 Square Inc. # # 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. require 'rails_helper' RSpec.describe ArticleRecalculator do it "should recalculate Article readiness" do article = nil # This call will disable all sidekiq jobs in the call chain. # In this case, we only have ArticleImporter and we need to stub it to prevent # it form creating keys. If you do need some sidekiq jobs to run, you need refactor this line. Sidekiq::Testing.fake! do article = FactoryBot.create(:article, ready: false) ArticleImporter::Finisher.new.on_success(nil, {'article_id' => article.id}) ArticleRecalculator.new.perform(article.id) end expect(article.reload).to be_ready end end
{ "pile_set_name": "Github" }
#include "config.h" #include "gskvulkanbufferprivate.h" #include "gskvulkanmemoryprivate.h" #include "gskvulkanpipelineprivate.h" struct _GskVulkanBuffer { GdkVulkanContext *vulkan; gsize size; VkBuffer vk_buffer; GskVulkanMemory *memory; }; static GskVulkanBuffer * gsk_vulkan_buffer_new_internal (GdkVulkanContext *context, gsize size, VkBufferUsageFlags usage) { VkMemoryRequirements requirements; GskVulkanBuffer *self; self = g_slice_new0 (GskVulkanBuffer); self->vulkan = g_object_ref (context); self->size = size; GSK_VK_CHECK (vkCreateBuffer, gdk_vulkan_context_get_device (context), &(VkBufferCreateInfo) { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size, .flags = 0, .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE }, NULL, &self->vk_buffer); vkGetBufferMemoryRequirements (gdk_vulkan_context_get_device (context), self->vk_buffer, &requirements); self->memory = gsk_vulkan_memory_new (context, requirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, size); GSK_VK_CHECK (vkBindBufferMemory, gdk_vulkan_context_get_device (context), self->vk_buffer, gsk_vulkan_memory_get_device_memory (self->memory), 0); return self; } GskVulkanBuffer * gsk_vulkan_buffer_new (GdkVulkanContext *context, gsize size) { return gsk_vulkan_buffer_new_internal (context, size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); } GskVulkanBuffer * gsk_vulkan_buffer_new_staging (GdkVulkanContext *context, gsize size) { return gsk_vulkan_buffer_new_internal (context, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT); } GskVulkanBuffer * gsk_vulkan_buffer_new_download (GdkVulkanContext *context, gsize size) { return gsk_vulkan_buffer_new_internal (context, size, VK_BUFFER_USAGE_TRANSFER_DST_BIT); } void gsk_vulkan_buffer_free (GskVulkanBuffer *self) { vkDestroyBuffer (gdk_vulkan_context_get_device (self->vulkan), self->vk_buffer, NULL); gsk_vulkan_memory_free (self->memory); g_object_unref (self->vulkan); g_slice_free (GskVulkanBuffer, self); } VkBuffer gsk_vulkan_buffer_get_buffer (GskVulkanBuffer *self) { return self->vk_buffer; } guchar * gsk_vulkan_buffer_map (GskVulkanBuffer *self) { return gsk_vulkan_memory_map (self->memory); } void gsk_vulkan_buffer_unmap (GskVulkanBuffer *self) { gsk_vulkan_memory_unmap (self->memory); }
{ "pile_set_name": "Github" }
"use strict"; module.exports = function (t, a) { a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 3 }), true, "Same"); a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2, 3: 4 }), false, "Different property value"); a(t({ 1: 1, 2: 2, 3: 3 }, { 1: 1, 2: 2 }), false, "Property only in source"); a(t({ 1: 1, 2: 2 }, { 1: 1, 2: 2, 3: 4 }), false, "Property only in target"); a(t("raz", "dwa"), false, "String: diff"); a(t("raz", "raz"), true, "String: same"); a(t("32", 32), false, "String & Number"); a(t([1, "raz", true], [1, "raz", true]), true, "Array: same"); a(t([1, "raz", undefined], [1, "raz"]), false, "Array: diff"); };
{ "pile_set_name": "Github" }
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * Copyright (C) 2017 OVH * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #ifndef CEPH_COMMON_PERF_COUNTERS_H #define CEPH_COMMON_PERF_COUNTERS_H #include <string> #include <vector> #include <memory> #include <atomic> #include <cstdint> #include "common/perf_histogram.h" #include "include/utime.h" #include "include/common_fwd.h" #include "common/ceph_mutex.h" #include "common/ceph_time.h" namespace TOPNSPC::common { class CephContext; class PerfCountersBuilder; class PerfCounters; } enum perfcounter_type_d : uint8_t { PERFCOUNTER_NONE = 0, PERFCOUNTER_TIME = 0x1, // float (measuring seconds) PERFCOUNTER_U64 = 0x2, // integer (note: either TIME or U64 *must* be set) PERFCOUNTER_LONGRUNAVG = 0x4, // paired counter + sum (time) PERFCOUNTER_COUNTER = 0x8, // counter (vs gauge) PERFCOUNTER_HISTOGRAM = 0x10, // histogram (vector) of values }; enum unit_t : uint8_t { UNIT_BYTES, UNIT_NONE }; /* Class for constructing a PerfCounters object. * * This class performs some validation that the parameters we have supplied are * correct in create_perf_counters(). * * In the future, we will probably get rid of the first/last arguments, since * PerfCountersBuilder can deduce them itself. */ namespace TOPNSPC::common { class PerfCountersBuilder { public: PerfCountersBuilder(CephContext *cct, const std::string &name, int first, int last); ~PerfCountersBuilder(); // prio values: higher is better, and higher values get included in // 'ceph daemonperf' (and similar) results. // Use of priorities enables us to add large numbers of counters // internally without necessarily overwhelming consumers. enum { PRIO_CRITICAL = 10, // 'interesting' is the default threshold for `daemonperf` output PRIO_INTERESTING = 8, // `useful` is the default threshold for transmission to ceph-mgr // and inclusion in prometheus/influxdb plugin output PRIO_USEFUL = 5, PRIO_UNINTERESTING = 2, PRIO_DEBUGONLY = 0, }; void add_u64(int key, const char *name, const char *description=NULL, const char *nick = NULL, int prio=0, int unit=UNIT_NONE); void add_u64_counter(int key, const char *name, const char *description=NULL, const char *nick = NULL, int prio=0, int unit=UNIT_NONE); void add_u64_avg(int key, const char *name, const char *description=NULL, const char *nick = NULL, int prio=0, int unit=UNIT_NONE); void add_time(int key, const char *name, const char *description=NULL, const char *nick = NULL, int prio=0); void add_time_avg(int key, const char *name, const char *description=NULL, const char *nick = NULL, int prio=0); void add_u64_counter_histogram( int key, const char* name, PerfHistogramCommon::axis_config_d x_axis_config, PerfHistogramCommon::axis_config_d y_axis_config, const char *description=NULL, const char* nick = NULL, int prio=0, int unit=UNIT_NONE); void set_prio_default(int prio_) { prio_default = prio_; } PerfCounters* create_perf_counters(); private: PerfCountersBuilder(const PerfCountersBuilder &rhs); PerfCountersBuilder& operator=(const PerfCountersBuilder &rhs); void add_impl(int idx, const char *name, const char *description, const char *nick, int prio, int ty, int unit=UNIT_NONE, std::unique_ptr<PerfHistogram<>> histogram = nullptr); PerfCounters *m_perf_counters; int prio_default = 0; }; /* * A PerfCounters object is usually associated with a single subsystem. * It contains counters which we modify to track performance and throughput * over time. * * PerfCounters can track several different types of values: * 1) integer values & counters * 2) floating-point values & counters * 3) floating-point averages * 4) 2D histograms of quantized value pairs * * The difference between values, counters and histograms is in how they are initialized * and accessed. For a counter, use the inc(counter, amount) function (note * that amount defaults to 1 if you don't set it). For a value, use the * set(index, value) function. For histogram use the hinc(value1, value2) function. * (For time, use the tinc and tset variants.) * * If for some reason you would like to reset your counters, you can do so using * the set functions even if they are counters, and you can also * increment your values if for some reason you wish to. * * For the time average, it returns the current value and * the "avgcount" member when read off. avgcount is incremented when you call * tinc. Calling tset on an average is an error and will assert out. */ class PerfCounters { public: /** Represents a PerfCounters data element. */ struct perf_counter_data_any_d { perf_counter_data_any_d() : name(NULL), description(NULL), nick(NULL), type(PERFCOUNTER_NONE), unit(UNIT_NONE) {} perf_counter_data_any_d(const perf_counter_data_any_d& other) : name(other.name), description(other.description), nick(other.nick), type(other.type), unit(other.unit), u64(other.u64.load()) { auto a = other.read_avg(); u64 = a.first; avgcount = a.second; avgcount2 = a.second; if (other.histogram) { histogram.reset(new PerfHistogram<>(*other.histogram)); } } const char *name; const char *description; const char *nick; uint8_t prio = 0; enum perfcounter_type_d type; enum unit_t unit; std::atomic<uint64_t> u64 = { 0 }; std::atomic<uint64_t> avgcount = { 0 }; std::atomic<uint64_t> avgcount2 = { 0 }; std::unique_ptr<PerfHistogram<>> histogram; void reset() { if (type != PERFCOUNTER_U64) { u64 = 0; avgcount = 0; avgcount2 = 0; } if (histogram) { histogram->reset(); } } // read <sum, count> safely by making sure the post- and pre-count // are identical; in other words the whole loop needs to be run // without any intervening calls to inc, set, or tinc. std::pair<uint64_t,uint64_t> read_avg() const { uint64_t sum, count; do { count = avgcount2; sum = u64; } while (avgcount != count); return { sum, count }; } }; template <typename T> struct avg_tracker { std::pair<uint64_t, T> last; std::pair<uint64_t, T> cur; avg_tracker() : last(0, 0), cur(0, 0) {} T current_avg() const { if (cur.first == last.first) return 0; return (cur.second - last.second) / (cur.first - last.first); } void consume_next(const std::pair<uint64_t, T> &next) { last = cur; cur = next; } }; ~PerfCounters(); void inc(int idx, uint64_t v = 1); void dec(int idx, uint64_t v = 1); void set(int idx, uint64_t v); uint64_t get(int idx) const; void tset(int idx, utime_t v); void tinc(int idx, utime_t v); void tinc(int idx, ceph::timespan v); utime_t tget(int idx) const; void hinc(int idx, int64_t x, int64_t y); void reset(); void dump_formatted(ceph::Formatter *f, bool schema, const std::string &counter = "") const { dump_formatted_generic(f, schema, false, counter); } void dump_formatted_histograms(ceph::Formatter *f, bool schema, const std::string &counter = "") const { dump_formatted_generic(f, schema, true, counter); } std::pair<uint64_t, uint64_t> get_tavg_ns(int idx) const; const std::string& get_name() const; void set_name(std::string s) { m_name = s; } /// adjust priority values by some value void set_prio_adjust(int p) { prio_adjust = p; } int get_adjusted_priority(int p) const { return std::max(std::min(p + prio_adjust, (int)PerfCountersBuilder::PRIO_CRITICAL), 0); } private: PerfCounters(CephContext *cct, const std::string &name, int lower_bound, int upper_bound); PerfCounters(const PerfCounters &rhs); PerfCounters& operator=(const PerfCounters &rhs); void dump_formatted_generic(ceph::Formatter *f, bool schema, bool histograms, const std::string &counter = "") const; typedef std::vector<perf_counter_data_any_d> perf_counter_data_vec_t; CephContext *m_cct; int m_lower_bound; int m_upper_bound; std::string m_name; int prio_adjust = 0; #if !defined(WITH_SEASTAR) || defined(WITH_ALIEN) const std::string m_lock_name; /** Protects m_data */ ceph::mutex m_lock; #endif perf_counter_data_vec_t m_data; friend class PerfCountersBuilder; friend class PerfCountersCollectionImpl; }; class SortPerfCountersByName { public: bool operator()(const PerfCounters* lhs, const PerfCounters* rhs) const { return (lhs->get_name() < rhs->get_name()); } }; typedef std::set <PerfCounters*, SortPerfCountersByName> perf_counters_set_t; /* * PerfCountersCollectionImp manages PerfCounters objects for a Ceph process. */ class PerfCountersCollectionImpl { public: PerfCountersCollectionImpl(); ~PerfCountersCollectionImpl(); void add(PerfCounters *l); void remove(PerfCounters *l); void clear(); bool reset(const std::string &name); void dump_formatted(ceph::Formatter *f, bool schema, const std::string &logger = "", const std::string &counter = "") const { dump_formatted_generic(f, schema, false, logger, counter); } void dump_formatted_histograms(ceph::Formatter *f, bool schema, const std::string &logger = "", const std::string &counter = "") const { dump_formatted_generic(f, schema, true, logger, counter); } // A reference to a perf_counter_data_any_d, with an accompanying // pointer to the enclosing PerfCounters, in order that the consumer // can see the prio_adjust class PerfCounterRef { public: PerfCounters::perf_counter_data_any_d *data; PerfCounters *perf_counters; }; typedef std::map<std::string, PerfCounterRef> CounterMap; void with_counters(std::function<void(const CounterMap &)>) const; private: void dump_formatted_generic(ceph::Formatter *f, bool schema, bool histograms, const std::string &logger = "", const std::string &counter = "") const; perf_counters_set_t m_loggers; CounterMap by_path; }; class PerfGuard { const ceph::real_clock::time_point start; PerfCounters* const counters; const int event; public: PerfGuard(PerfCounters* const counters, const int event) : start(ceph::real_clock::now()), counters(counters), event(event) { } ~PerfGuard() { counters->tinc(event, ceph::real_clock::now() - start); } }; } #endif
{ "pile_set_name": "Github" }
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. The code included in this file is provided under the terms of the ISC license http://www.isc.org/downloads/software-support-policy/isc-license. Permission To use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted provided that the above copyright notice and this permission notice appear in all copies. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ /******************************************************************************* The block below describes the properties of this module, and is read by the Projucer to automatically generate project code that uses it. For details about the syntax and how to create or use a module, see the JUCE Module Format.txt file. BEGIN_JUCE_MODULE_DECLARATION ID: juce_events vendor: juce version: 5.2.0 name: JUCE message and event handling classes description: Classes for running an application's main event loop and sending/receiving messages, timers, etc. website: http://www.juce.com/juce license: ISC dependencies: juce_core END_JUCE_MODULE_DECLARATION *******************************************************************************/ #pragma once #define JUCE_EVENTS_H_INCLUDED #include <juce_core/juce_core.h> //============================================================================== /** Config: JUCE_EXECUTE_APP_SUSPEND_ON_IOS_BACKGROUND_TASK Will execute your application's suspend method on an iOS background task, giving you extra time to save your applications state. */ #ifndef JUCE_EXECUTE_APP_SUSPEND_ON_BACKGROUND_TASK #define JUCE_EXECUTE_APP_SUSPEND_ON_BACKGROUND_TASK 0 #endif #if JUCE_EVENTS_INCLUDE_WINRT_WRAPPER && JUCE_WINDOWS #include <hstring.h> #endif #include "messages/juce_MessageManager.h" #include "messages/juce_Message.h" #include "messages/juce_MessageListener.h" #include "messages/juce_CallbackMessage.h" #include "messages/juce_DeletedAtShutdown.h" #include "messages/juce_NotificationType.h" #include "messages/juce_ApplicationBase.h" #include "messages/juce_Initialisation.h" #include "messages/juce_MountedVolumeListChangeDetector.h" #include "broadcasters/juce_ActionBroadcaster.h" #include "broadcasters/juce_ActionListener.h" #include "broadcasters/juce_AsyncUpdater.h" #include "broadcasters/juce_ChangeListener.h" #include "broadcasters/juce_ChangeBroadcaster.h" #include "timers/juce_Timer.h" #include "timers/juce_MultiTimer.h" #include "interprocess/juce_InterprocessConnection.h" #include "interprocess/juce_InterprocessConnectionServer.h" #include "interprocess/juce_ConnectedChildProcess.h" #if JUCE_LINUX #include "native/juce_linux_EventLoop.h" #endif #if JUCE_WINDOWS #if JUCE_EVENTS_INCLUDE_WIN32_MESSAGE_WINDOW #include "native/juce_win32_HiddenMessageWindow.h" #endif #if JUCE_EVENTS_INCLUDE_WINRT_WRAPPER #include "native/juce_win32_WinRTWrapper.h" #endif #endif
{ "pile_set_name": "Github" }
/* * This file is part of the UCB release of Plan 9. It is subject to the license * terms in the LICENSE file found in the top-level directory of this * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No * part of the UCB release of Plan 9, including this file, may be copied, * modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ #include "stdinc.h" #include "dat.h" #include "fns.h" enum { IDATSIZE = 20000, FilterNone = 0 }; typedef struct ZlibR ZlibR; typedef struct ZlibW ZlibW; struct ZlibR { uint8_t *data; int width; int dx; int dy; int x; int y; int pixwid; }; struct ZlibW { Hio *io; uint8_t *buf; uint8_t *b; uint8_t *e; }; static uint32_t *crctab; static uint8_t PNGmagic[] = { 137, 'P', 'N', 'G', '\r', '\n', 26, '\n'}; static void put4(uint8_t *a, uint32_t v) { a[0] = v>>24; a[1] = v>>16; a[2] = v>>8; a[3] = v; } static void chunk(Hio *io, char *type, uint8_t *d, int n) { uint8_t buf[4]; uint32_t crc = 0; if(strlen(type) != 4) return; put4(buf, n); hwrite(io, buf, 4); hwrite(io, type, 4); hwrite(io, d, n); crc = blockcrc(crctab, crc, type, 4); crc = blockcrc(crctab, crc, d, n); put4(buf, crc); hwrite(io, buf, 4); } static int zread(void *va, void *buf, int n) { int a, i, pixels, pixwid; uint8_t *b, *e, *img; ZlibR *z; z = va; pixwid = z->pixwid; b = buf; e = b+n; while(b+pixwid <= e){ if(z->y >= z->dy) break; if(z->x == 0) *b++ = FilterNone; pixels = (e-b)/pixwid; if(pixels > z->dx - z->x) pixels = z->dx - z->x; img = z->data + z->width*z->y + pixwid*z->x; memmove(b, img, pixwid*pixels); if(pixwid == 4){ /* * Convert to non-premultiplied alpha. */ for(i=0; i<pixels; i++, b+=4){ a = b[3]; if(a != 0 && a != 255){ if(b[0] >= a) b[0] = a; b[0] = (b[0]*255)/a; if(b[1] >= a) b[1] = a; b[1] = (b[1]*255)/a; if(b[2] >= a) b[2] = a; b[2] = (b[2]*255)/a; } } }else b += pixwid*pixels; z->x += pixels; if(z->x >= z->dx){ z->x = 0; z->y++; } } return b - (uint8_t*)buf; } static void IDAT(ZlibW *z) { chunk(z->io, "IDAT", z->buf, z->b - z->buf); z->b = z->buf; } static int zwrite(void *va, void *buf, int n) { int m; uint8_t *b, *e; ZlibW *z; z = va; b = buf; e = b+n; while(b < e){ m = z->e - z->b; if(m > e - b) m = e - b; memmove(z->b, b, m); z->b += m; b += m; if(z->b >= z->e) IDAT(z); } return n; } static Memimage* memRGBA(Memimage *i) { Memimage *ni; char buf[32]; uint32_t dst; /* * [A]BGR because we want R,G,B,[A] in big-endian order. Sigh. */ chantostr(buf, i->chan); if(strchr(buf, 'a')) dst = ABGR32; else dst = BGR24; if(i->chan == dst) return i; qlock(&memdrawlock); ni = allocmemimage(i->r, dst); if(ni) memimagedraw(ni, ni->r, i, i->r.min, nil, i->r.min, S); qunlock(&memdrawlock); return ni; } int writepng(Hio *io, Memimage *m) { static int first = 1; static QLock lk; uint8_t buf[200], *h; Memimage *rgb; ZlibR zr; ZlibW zw; if(first){ qlock(&lk); if(first){ deflateinit(); crctab = mkcrctab(0xedb88320); first = 0; } qunlock(&lk); } rgb = memRGBA(m); if(rgb == nil) return -1; hwrite(io, PNGmagic, sizeof PNGmagic); /* IHDR chunk */ h = buf; put4(h, Dx(m->r)); h += 4; put4(h, Dy(m->r)); h += 4; *h++ = 8; /* 8 bits per channel */ if(rgb->chan == BGR24) *h++ = 2; /* RGB */ else *h++ = 6; /* RGBA */ *h++ = 0; /* compression - deflate */ *h++ = 0; /* filter - none */ *h++ = 0; /* interlace - none */ chunk(io, "IHDR", buf, h-buf); /* image data */ zr.dx = Dx(m->r); zr.dy = Dy(m->r); zr.width = rgb->width * sizeof(uint32_t); zr.data = rgb->data->bdata; zr.x = 0; zr.y = 0; zr.pixwid = chantodepth(rgb->chan)/8; zw.io = io; zw.buf = vtmalloc(IDATSIZE); zw.b = zw.buf; zw.e = zw.b + IDATSIZE; if(deflatezlib(&zw, zwrite, &zr, zread, 6, 0) < 0){ free(zw.buf); return -1; } if(zw.b > zw.buf) IDAT(&zw); free(zw.buf); chunk(io, "IEND", nil, 0); if(m != rgb){ qlock(&memdrawlock); freememimage(rgb); qunlock(&memdrawlock); } return 0; }
{ "pile_set_name": "Github" }
{ "translation": { "aboutCovidDescription": "Na stronie covid.is znajdziesz różne wskazówki i wiarygodne informacje.", "aboutCovidTitle": "Informacje o COVID-19", "announcements": "Ogłoszenia", "announcementsLink": "https://www.covid.is/ogoszenia", "avoidInfectionLabel": "W jaki sposób zarażam?", "avoidInfectionLink": "https://www.covid.is/flokkar-polsku/w-jaki-sposob-zarazam", "childrenAndTeensLabel": "Dzieci i młodzież", "childrenAndTeensLink": "https://www.covid.is/undirflokkar-polsku/dzieci-i-mlodziez", "covidLabel": "Więcej na", "covidLink": "https://www.covid.is/polski", "enableLocationAllow": "Zezwolenie na udzielenie lokalizacji i wysyłanie powiadomień", "enableLocationButton": "Do przodu", "changeLocationAllow": "Udostępnij lokalizację", "changeLocationDescriptionIOS": "Bardzo ważne jest, aby umożliwić aplikacji monitorowanie Twojej lokalizacji. Zmień ustawienie udostępniania lokalizacji na <0>„Zawsze”</0>.", "changeLocationSettings": "Change setting", "enableLocationDescriptionAndroid": "Aplikacja poprosi o pozwolenie na rejestrowanie twoich podróży / lokalizacji. Bardzo ważne jest wybranie opcji <0>„Pozwól cały czas”</0>.", "enableLocationDescriptionIOS": "Aplikacja poprosi o pozwolenie na rejestrowanie twoich podróży / lokalizacji. Bardzo ważne jest wybranie opcji <0>„Zezwól podczas korzystania z aplikacji”</0>.", "enableLocationMessageIOS": "Po zainstalowaniu aplikacji na Twoim urządzeniu, poprosi Cię o pozwolenie na zapisywanie lokalizacji, gdy aplikacja nie jest używana. Bardzo ważne jest, aby wybrać <0>„Zmień na zawsze zezwalaj”</0>. Jest to warunek, aby aplikacja mogła odgrywać swoją rolę.", "enableNotificationDescription": "Aplikacja poprosi również o pozwolenie na wysyłanie powiadomień.", "foodPetsAndAnimalsLabel": "Żywność i zwierzęta", "foodPetsAndAnimalsLink": "https://www.covid.is/undirflokkar-polsku/zywnosci-i-zwierzeta", "genericErrorMessage": "Coś poszło nie tak. Spróbuj ponownie za chwilę.", "groupsAtRiskLabel": "Grupy zagrożenia", "groupsAtRiskLink": "https://www.covid.is/undirflokkar-polsku/grupy-zagrozenia", "incorrentPINMessage": "Niepoprawny numer PIN, spróbuj ponownie.", "isolationLabel": "Co to izlolacja", "isolationLink": "https://www.covid.is/flokkar-polsku/izolacja", "languageDescription": "Pomoc Obronie Cywilnej w śledzeniu potencjalnych infekcji COVID-19 na Islandii", "languageContinue": "Prześlij do polskiego", "next": "Kolejny", "phoneNr": "Phone nr.", "phoneNumber": "Phone number", "phoneNumberDescription": "Otrzymasz kod, który należy wprowadzić w następnym kroku", "phoneNumberTitle": "Wpisz Twoj numer telefonu", "phoneValidationMessage": "Nieprawidłowy numer telefonu", "pinNumberDescription": "Wpisz kod otrzymany w wiadomości SMS na numer telefonu {{phoneNumber}}.", "pinNumberTitle": "Wpisz kod", "pinResendBtn": "SMS nie dotarł. Spróbuj ponownie", "possibleInfectionLabel": "Potencjalne zarażenie", "possibleInfectionLink": "https://www.covid.is/flokkar-polsku/potencjalne-zarazenie", "quarantineLabel": "Co to kwarantanna", "quarantineLink": "https://www.covid.is/flokkar-polsku/kwarantannie", "requestDataButton": "Wyślij dane", "requestDataKennitala": "Kennitala", "requestDataKennitalaInfo": "Wprowadź swój numer ewidencyjny przed przesłaniem swojej lokalizacji.", "requestDataSubTitle": "Zespół śledczy Krajowej Agencji Ochrony Ludności prosi o podanie lokalizacji w celu pomocy w śledzeniu zarażenia.", "requestDataThanks": "Dziękujemy za przesłanie danych Krajowej Agencji Obrony Cywilnej!", "requestDataTitle": "Prośba od Zespołu Śledczego", "requestDataWrongKennitala": "Numer identyfikacyjny nie zgadza się z numerem identyfikacyjnym z zapisanym w bazie danych zespołu monitorującego ", "requestDataExitButton": "Nie dziękuję, nie wysyłaj danych ", "requestDataExitTitle": "Jesteś pewien?", "requestDataExitDescription": "Wybierając Tak, nie wysyłasz danych do Zespołu monitorującego ds. Ochrony Ludności. Aby pomóc w monitorowaniu infekcji COVID-19, wybierz Nie.", "requestDataExitYes": "Tak", "requestDataExitNo": "Nie .", "requestDataExit": "Nie chcę wysyłać moich danych do Zespołu Monitorującego ds.Ochrony Ludności.", "riskAreasLabel": "Strefy zagrożenia", "riskAreasLink": "https://www.covid.is/undirflokkar-polsku/strefy-zagrozenia", "seniorCitizensLabel": "Seniorzy", "seniorCitizensLink": "https://www.covid.is/undirflokkar-polsku/seniorzy", "tosAcceptance": "Zgadzam się z <1>Polityką prywatności</1>.", "privacyPolicy": "Polityką prywatności", "trackingSubtitle": "Dobra robota! Przyczyniasz się do śledzenia zakażeń COVID-19.", "trackingTitle": "Trwa śledzenie", "trackingNotification": "Dobra robota! Teraz jesteś częścią zespołu śledczego.", "travelLabel": "Podróże", "travelLink": "https://www.covid.is/undirflokkar-polsku/podroze", "welcomeHowDescription": "Aplikacja zapisuje Twoje podróże i bezpiecznie przechowuje je na twoim urządzeniu. W niektórych przypadkach zespół śledczy może wysłać Ci powiadomienie z prośbą o przesłanie danych. Następnie za pomocą jednego kliknięcia możesz wysłać dane do Zespołu Śledczego Sztabu Ochrony Cywilnej. Odbywa się to w celu ułatwienia śledzenia/ monitorowania infekcji COVID-19.", "welcomeHowTitle": "Jak działa i jakie informacje przechowuje aplikacja?", "welcomeInfoDescription": "Żadne inne informacje prócz Twojego numeru telefonu nie są przechowywane w centralnej bazie danych użytkowników.", "welcomeInfoTitle": "Urządzenie przechowuje lokalizacje z ostatnich 14 dni. Starsze dane są automatycznie usuwane.", "welcomeRegisterButton": "Zarejestruj mnie", "welcomeSubtitle": "Pomóżmy Zespołowi Śledczemu Sztabu Obrony Cywilnej śledzić potencjalne infekcje COVID-19 na Islandii.", "welcomeTitle": "Śledzenie - COVID-19", "workplacesLabel": "Miejsca pracy", "workplacesLink": "https://www.covid.is/undirflokkar-polsku/miejsca-pracy", "worriesAndAnxietyLabel": "Zmartwienia i lęki", "worriesAndAnxietyLink": "https://www.covid.is/undirflokkar-polsku/zmartwienia-i-leki", "links": { "primary": [ "avoidInfection", "possibleInfection", "isolation", "quarantine" ], "secondary": [ "groupsAtRisk", "seniorCitizens", "childrenAndTeens", "worriesAndAnxiety", "workplaces", "travel", "foodPetsAndAnimals", "riskAreas" ] } } }
{ "pile_set_name": "Github" }
{ $method->exe("campaign","search_form") } { if ($method->result == FALSE) } { $block->display("core:method_error") } {else} <form name="campaign_search" method="post" action=""> <table width=100% border="0" cellspacing="0" cellpadding="0" class="table_background"> <tr> <td> <table width="100%" border="0" cellspacing="1" cellpadding="0"> <tr valign="top"> <td width="65%" class="table_heading"> <center> {translate module=campaign}title_search{/translate} </center> </td> </tr> <tr valign="top"> <td width="65%" class="row1"> <table width="100%" border="0" cellspacing="3" cellpadding="1" class="row1"> <tr valign="top"> <td width="35%"> {translate module=campaign} field_date_orig {/translate} </td> <td width="65%"> { $list->calender_search("campaign_date_orig", $VAR.campaign_date_orig, "form_field", "") } </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_date_last {/translate} </td> <td width="65%"> { $list->calender_search("campaign_date_last", $VAR.campaign_date_last, "form_field", "") } </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_date_start {/translate} </td> <td width="65%"> { $list->calender_search("campaign_date_start", $VAR.campaign_date_start, "form_field", "") } </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_date_expire {/translate} </td> <td width="65%"> { $list->calender_search("campaign_date_expire", $VAR.campaign_date_expire, "form_field", "") } </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_status {/translate} </td> <td width="65%"> { $list->bool("campaign_status", "all", "form_menu") } </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_name {/translate} </td> <td width="65%"> <input type="text" name="campaign_name" value="{$VAR.campaign_name}" {if $campaign_name == true}class="form_field_error"{/if}> &nbsp;&nbsp; {translate} search_partial {/translate} </td> </tr> <tr valign="top"> <td width="35%"> {translate module=campaign} field_description {/translate} </td> <td width="65%"> <input type="text" name="campaign_description" value="{$VAR.campaign_description}" {if $campaign_description == true}class="form_field_error"{/if}> &nbsp;&nbsp; {translate} search_partial {/translate} </td> </tr> <!-- Define the results per page --> <tr class="row1" valign="top"> <td width="35%"> {translate} search_results_per {/translate} </td> <td width="65%"> <input type="text" name="limit" size="5" value="{$campaign_limit}"> </td> </tr> <!-- Define the order by field per page --> <tr class="row1" valign="top"> <td width="35%"> {translate} search_order_by {/translate} </td> <td width="65%"> <select name="order_by"> {foreach from=$campaign item=record} <option value="{$record.field}"> {$record.translate} </option> {/foreach} </select> </td> </tr> <tr class="row1" valign="top"> <td width="35%"></td> <td width="65%"> <input type="submit" name="Submit" value="{translate}search{/translate}" class="form_button"> <input type="hidden" name="_page" value="core:search"> <input type="hidden" name="_escape" value="Y"> <input type="hidden" name="module" value="campaign"> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </form> { $block->display("core:saved_searches") } { $block->display("core:recent_searches") } {/if}
{ "pile_set_name": "Github" }
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_PUNCTUATION_HPP # define BOOST_PREPROCESSOR_PUNCTUATION_HPP # # include <boost/preprocessor/punctuation/comma.hpp> # include <boost/preprocessor/punctuation/comma_if.hpp> # include <boost/preprocessor/punctuation/paren.hpp> # include <boost/preprocessor/punctuation/paren_if.hpp> # # endif
{ "pile_set_name": "Github" }
#!/bin/bash -eux # Ensure a nameserver is being used that won't return an IP for non-existent domain names. printf "nameserver 4.2.2.1\nnameserver 4.2.2.2\nnameserver 208.67.220.220\n"> /etc/resolv.conf # Set the hostname, and then ensure it will resolve properly. if [[ "$PACKER_BUILD_NAME" =~ ^generic-centos8-(vmware|hyperv|libvirt|parallels|virtualbox)$ ]]; then printf "centos8.localdomain\n" > /etc/hostname printf "\n127.0.0.1 centos8.localdomain\n\n" >> /etc/hosts else printf "magma.builder\n" > /etc/hostname printf "\n127.0.0.1 magma.builder\n\n" >> /etc/hosts fi # Disable IPv6 or dnf will resolve mirror names to IPv6 address and then fail to connect with them. sysctl net.ipv6.conf.all.disable_ipv6=1 # Disable IPv6 and the iptables module used to firewall IPv6. printf "\n\nnet.ipv6.conf.all.disable_ipv6 = 1\n" >> /etc/sysctl.conf sed -i -e "/IPV6INIT.*/d;$ a IPV6INIT=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6_AUTOCONF.*/d;$ a IPV6_AUTOCONF=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6_DEFROUTE.*/d;$ a IPV6_DEFROUTE=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6_PEERDNS.*/d;$ a IPV6_PEERDNS=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6_PEERROUTES.*/d;$ a IPV6_PEERROUTES=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6FORWARDING.*/d;$ a IPV6FORWARDING=no" /etc/sysconfig/network-scripts/ifcfg-eth0 sed -i -e "/IPV6_AUTOTUNNEL.*/d;$ a IPV6_AUTOTUNNEL=no" /etc/sysconfig/network-scripts/ifcfg-eth0 # If postfix is installed, configure it use only ipv4 interfaces, or it will fail to start properly. if [ -f /etc/postfix/main.cf ]; then sed -i "s/^inet_protocols.*$/inet_protocols = ipv4/g" /etc/postfix/main.cf fi # Works around a bug which slows down DNS queries on Virtualbox. # We assume that this bug applies to CentOS as well. # https://access.redhat.com/site/solutions/58625 # Bail if we are not running atop VirtualBox. if [[ "$PACKER_BUILDER_TYPE" != virtualbox-iso ]]; then exit 0 fi printf "Fixing the problem with slow DNS queries.\n" cat >> /etc/NetworkManager/dispatcher.d/fix-slow-dns <<EOF #!/bin/bash echo "options single-request-reopen" >> /etc/resolv.conf EOF chmod +x /etc/NetworkManager/dispatcher.d/fix-slow-dns systemctl restart NetworkManager.service
{ "pile_set_name": "Github" }
# 『食』 ------ フェルトの名前をこそぎ取り、『食事』を始めたはずのバテンカイトスが嘔吐する。 苦しげに呻き、胃液を吐き出す『暴食』の態度には嘘がない。実際に形のあるモノを口にしたわけではないのに、嘔吐するときは胃を絞り出されるのか。 そんな益体のない感想が浮かぶ、不可思議な光景だった。   「クソ、いてーな……ふざけやがって……」   突き飛ばされた胸を撫でつけ、擦り傷だらけの姿でフェルトが立ち上がる。その表情は苛立ちと不満を宿しているが、致命的な被害を受けた様子はない。 彼女を視界の端に捉えるベアトリスらも、フェルトを忘れてなどいない。   『暴食』の食事は失敗したのだ。   「がっ、げほっ、おええッ!」   「理由はわからんが……好機だ!」   口の端から胃液をこぼし、完全に戦場から意識の外れるバテンカイトスへとダイナスが強襲を仕掛ける。 二刀が翻り、容赦なくバテンカイトスへ叩きつけられた。 無防備な首筋に、小刀の剣閃が迫り――、   「ぎ、ォォ!」   獣の雄叫びのような声が上がり、バテンカイトスが体術で刃をいなす。 回避の遅れた髪の毛が斬撃に持っていかれるが、肌を切り裂くには至らない。小柄な体を高速で回転させ、悪夢めいた挙動で『暴食』は攻撃範囲から逃れる。   「商人!」   「わかってます、よ!!」   ベアトリスの呼びかけに、応じるオットーが右腕を振り切った。その袖から投じられる二発の魔鉱石が、攻撃を逃れたバテンカイトスに当たる。 瞬間、光が爆ぜて、生じる魔力の奔流がその体を吹き飛ばす――だが、バテンカイトスはこれに驚異的な反射神経で対応した。   「ヒューマぁ!」   膨れ上がる光が、その破壊の力にバテンカイトスを呑み込む瞬間、バテンカイトスは魔法を発動し、爆ぜる魔鉱石を氷の中に包んで固めたのだ。 魔鉱石の爆裂は力の行き場を失い、ただの氷の塊になって音を立てて地面に落ちる。無色の魔力波に、高速で術式を割り込ませる超高等技術だ。   それすらもおそらく、バテンカイトスがこれまでに喰らった『名前』の中の一つがやってのけたのだろう。それだけの技術を習得した『誰か』も、誰の記憶にも残らないまま胃袋に奥に沈められていると考えると反吐が出る。   だが、今はそれらの感慨も後回しだ。 この場で重要なのは――。   「はァッ!危ない危ない……けど、しのいだよッ」   魔鉱石を閉じ込めた氷を蹴りつけ、水路に落としたバテンカイトスが笑う。彼は口の中に残る胃液をペッと吐くと、口元を腕で拭って首を傾けた。 その濁った瞳が見るのは、手足を回して負傷の程度を確かめるフェルトだ。フェルトは自分を見るバテンカイトスに気付くと、その鼻を鳴らす。   「んだよ。てめーにムカついてんのはアタシも同じだぞ」   「ムカついてるだなんてとんでもないッ、感心してるところさァ。見た目で、おつむの出来が悪そうだなんて思って悪かったよォ」   「はぁ?何を言い出してやが……」   「まさか、僕たち相手に偽名を使うだけの小賢しさがあるだなんて思わなかった。すっかり騙されたよ。『名前』を暴くまでがっつくのは避けてたつもりだったんだけど……まァさか、それを逆手に取られるだなんてね」   「――――」   偽名、とバテンカイトスが口にしたのを聞いて、フェルトが押し黙った。 眉をひそめるフェルトの反応は、思わぬ内容を聞かされたものが示す反応だ。彼女には今のバテンカイトスの言い分に、心当たりがないと見るべきだろう。   一方で、今の話を聞いていたベアトリスには、先のバテンカイトスの『食事』の失敗の原因が理解できていた。 バテンカイトスは『名前』を知った人間に触れて、いかなる手段か『名前』を喰らう権能の持ち主――だが、それは正式な名前である必要があるのだ。   偽名、あるいは愛称のようなものではそれは機能しない。 フェルトの名前だけでは『食事』としての条件を満たしていなかったため、それを味わったバテンカイトスが痛い目を見ることになった。 となれば、   「そっちのお兄さんにフェルトちゃん……名前のわからないのが二人もいて、どっちも食べると決めた相手だなんて厄介だなァ」   純粋に名前のわからないオットーと、偽名を用いているらしいフェルト。 すでに名前の割れているダイナスと、レムの記憶から知られているベアトリスはもはや障害ではないような『暴食』の振る舞いは癇に障るが、美食家を名乗って『名前』を喰らうことに拘り続けるのであれば、そこに付け入る隙もある。   「おい!さっきっから黙って聞いてりゃー、何の言いがかりだ?」   考え込むベアトリスと、睥睨するバテンカイトス。オットーやダイナスも機を見計らう最中、声を荒げたのはフェルトだ。 彼女は自分を余所に結論を出されたことに苛立ち、ミーティアを突き付けてバテンカイトスに吠える。   「偽名だのなんだの、ふざっけんな。アタシはもう十五年、ロム爺にもらったフェルトって名前で生きてきてんだ。それが嘘だなんて冗談じゃねーぞ」   「当人に偽名の自覚がないタイプかァ。そりゃ、君の育ての親がよっぽどうまくやったってことだろうねッ。僕たちにとっちゃ厄介極まりないけど……つまり、その名前より前にちゃァんと付けられた名前があるんだよ、君には」   「アタシを路地裏に捨ててったクソ親がつけた名前か?ならきっと、『厄介者』か『無駄飯食らい』か『ゴミ』だぜ。そう言って、ぺろっと食べてみるか?」   「当てずっぽうの総当たりとか、美食家の意識に反するなァ。――あァ、そうだ」   八重歯を見せ、怒りの笑みを浮かべるフェルトにバテンカイトスが手を打った。彼はフェルトの体を上から下まで眺めると、   「君以外を喰らったあとで、君は大切に保管しよう。で、君に偽物の名前を付けたロム爺に会いにいこうじゃないか。ロム爺なら君の名前を知ってるかもしれない。俺たちは、知ってることを聞き出すのは得意なんだ。任せてくれていいさァ」   「……そこまで手間暇かけて。諦めるって選択肢はないんですかね?」   醜悪な予定を口にする『暴食』に、思わずオットーが口を挟んだ。それを聞いたバテンカイトスは口に手を当て、愉しげに喉を鳴らすと、   「世に命の数が有限なら、その中で美食に値する数もまた有限なのさァ。なら、僕たちは限られた美食と出会える機会を逃さないッ。暴飲ッ!暴食ッ!舐めてしゃぶって啜ってこそいで、皿の上のタレまで舐め尽くして味わってやるさァ。おっと、もちろんお兄さんも例外じゃァないから安心していいよォ?」   バテンカイトスの視線は、この場に残る四人を決して逃すまいと決めている。 『暴食』の食事への拘りは、『美食』に値すると評価されたベアトリスたちには理解不能だ。ただ、執念深い厄介者に目を付けられた以上の意味はない。 そして、その冒涜者の食へ至る欲求は、いたくフェルトの不興を買った。   「そーかよ。ここでどうにかしねーと、ロム爺にまで手ぇ出すってんだな」   静かな声で言って、フェルトが自分の足を振った。 履いていた靴がすっぽ抜け、フェルトはもう片方の足も同じように。両足を素足の状態で石畳を踏み、彼女はミーティアを横へ転がすと短剣を抜いた。   「――?わっかんないなァ、フェルトちゃん。それ、切り札なんじゃァないの?」   「慣れてねー道具に頼るより、こっちの方がやりやすいんだよ。もともと、そこまで拘るもんでもねー。道具は使える奴が、使いやすいのを使うのがいいって、な!」   素足が地面を掴むように丸まり、次の瞬間にフェルトの体が弾かれるように前に射出されていた。瞬きの合間に接敵する速度、まさに風のようだ。 これにはバテンカイトスも目を剥き、振りかぶられる刃に対して余裕の態度を忘れて対応する。腕を振り、身を捌き、記憶に沈めた体術を引っ張り出す応戦だ。   「っらぁ!」   裸足のフェルトの速度は、ただ身軽な少女の出せる勢いを凌駕している。 人智を超えた力の援護――すなわち加護を帯びていることは間違いない。短剣が幾度も閃いて、バテンカイトスの短剣術とそれなりに渡り合っている。 無論、その技量はバテンカイトスに圧倒的に軍配が上がるが、ただフェルトが押し切られずに済むのはダイナスの援護が入るからだ。   「大事な体で、あまり無茶をするな!」 「オッサンこそうっせーな、遅れてんじゃねーよ!」   巧みに二刀を操り、ダイナスは『暴食』の反撃の隙間をどうにか塞ぐ。その間にフェルトが『暴食』の死角に回り込んで急襲、鋼同士が噛み合う音がして、火花を散らしながらもみ合う三人の影が入り乱れる。   またしても決定打に欠ける乱戦。 ただし今回は、決定打がきっちりと乱戦の外側に用意されている――。   「術式……通した、ぶちかますかしら!」   「お二人とも、離れてください!」   蚊帳の外に置かれながら、じっくりと時間をかけて一つの術式を組み上げる。 普段ならばさして手こずる必要もない作業に、余計なフィルターを挟んでいるせいで細心の注意を払う工程が入った。 それだけの労力を払った結果、ようやくそれが形になる。   「――――」   オットーの叫びに従い、フェルトとダイナスがバテンカイトスの傍を離れる。とっさにフェルトに手を伸ばす『暴食』だが、触れたところでフェルトの『名前』を喰らう準備は整っていない。   「はな、せ!」   乱暴に掴まれた足首を振りほどき、フェルトは片足で大きく背後へ飛んだ。ダイナスも転がるようにその場を離れて、ベアトリスの射線上に『暴食』だけが残る。 そこへ目掛けて、ベアトリスは発動に『千』の力を必要とする魔法を、『千』の力を真っ当に通して完成させた。   「今度は冗談じゃなく、本当に……ウル・ミーニャ!!」   詠唱に応じて紫の輝きが迸り、バテンカイトスを中心に光が円を描く。何事が起こるのかと顔を上げるバテンカイトスだが、その反応では遅い。 構えるのではなく、形振り構わず逃げ出すのが正解だ。   「――ッ!」   光の輪が一気に収束し、バテンカイトスの胴体が腕ごと輪に抑え込まれる。上半身の動きを拘束された『暴食』に、さらに光の輪が連鎖して閉ざしにかかった。 そのまま全身を光の輪に包まれれば、ウル・ミーニャの威力から逃れられない。   結晶化する紫の光が、バテンカイトスの上半身を次々と締め付ける。そのまま輪の支配は下半身にまで及び、身動きを感じられた『暴食』がその場に倒れ込んだ。 そして大気が軋むような音を立てて、強大な紫紺の輝きが倒れる冒涜者の頭上に浮かび上がり、その先端をバテンカイトスへと向けている。   拘束し、叩き潰すウル・ミーニャの威力。 ベアトリスの持てる技術を緊急的に叩き込み、実現させた破壊がバテンカイトスへと降り注いだ。   「――――!」   雄叫びが掠れて聞こえたが、それは破壊を生み出す紫の光の前に掻き消された。 圧倒的な光の威力に石畳がめくれ上がり、巻き起こる爆風が大広場を光と噴煙で包み込み、ベアトリスのドレスのスカートが大きくはためく。   「やったか!?」 「やりましたか!?」 「やったのか!?」   爆風に煽られながら、身を伏せていた三者が同時にそう声を上げた。 爆心地のど真ん中、そこにいたバテンカイトスに回避の手段はなかった。今の一撃をまともに浴びていれば、その肉体は骨片すら残さず消滅して――。   「まだ終わっちゃいないかしら!」   ――そう、まともに当たっていればだ。   ベアトリスが高い声で警戒を促し、快哉を叫んだ三人の顔色が変わる。三人よりもいち早く、ベアトリスが失策に気付けたのは難しい話ではない。 感触だ。   「――あと、四つ」   懐に仕舞い込んでいた大魔石が、今のウル・ミーニャの術式に耐え切れず、バテンカイトスを仕留める寸前で砕け散っていた。 発動まで持ち込めたものの、効果の十全な発揮には不十分な位置での消失。輝きはバテンカイトスを焼き尽くすには届かず、『暴食』の体は――、   「今のはちょっとだけ焦ったかもッ!」   「――!」   噴煙の中を突き抜けて、バテンカイトスが低い姿勢からベアトリスへ飛びかかる。今の魔法の威力から、もっとも早々に消すべきが誰かを判断した結果だろう。 魔法使いとして卓越した技術を持つベアトリスだが、その身のこなしは常人――外見通り、幼い少女の域を脱してはいない。   達人の体術を操るバテンカイトスと、接近戦を行えるだけの能力はないのだ。 故にベアトリスはこの接敵に対して、即座に三つ目の魔石を利用する。   「――ムラク!」   「小細工したところで――」   バテンカイトスの手が届く寸前、かろうじてベアトリスの詠唱が先手を打った。 伸び上がる指先は、いかなる妨害があってもベアトリスを逃がすまい、それだけの意思が込められたものだった。だが、その意はまたしても外れる。   指先がドレスを掠めたかと思った瞬間、ベアトリスの体がまるで風に押される木の葉のように真後ろへ吹っ飛んだのだ。   「――――」   ベアトリスの詠唱した『ムラク』は、重力に干渉する陰魔法だ。地面へ引きつけられる力や、自らの体重などに干渉する魔法だが、ベアトリスはそれを利用して自分の体重を一瞬だけ完全にゼロにした。 それこそ風に浮かび、触れようとする指先に大きく弾かれるほどに。   「こ、っの――!?」   目論見通りに、ベアトリスの体はバテンカイトスを離れて、一気に大広場の端っこの方まで飛んでいく。それに追い縋ろうとしたバテンカイトスは、しかし背後に生じた大げさな足音を聞いて、とっさにそちらへ振り返ってしまった。   短剣を背後へ繰り出し、無粋な乱入者を斬りつけようとする。しかし、その一撃は空を切った。なぜなら、そこに足音の人物はおらず、   「ガーフィールとか『腸狩り』とか、そういう人ばっかり引っかかりますよねえ!」   風魔法の応用で、『足音を飛ばした』オットーが背中を向けさせたバテンカイトスにさらに魔石を投じた。剥き出しの背中に破裂する魔石の熱波が襲い掛かり、今度は防がれなかった爆風にバテンカイトスが吹っ飛ぶ。   「今度こそ終わりだ!」   ゴロゴロと広場を転がり、五体を投げ出して倒れるバテンカイトス。その姿に飛びかかり、二刀を逆手に構えたダイナスが止めを刺そうと――、   「――――」   ぼそりと、倒れる少年が何事か囁いた。 それが命乞いか、あるいは後悔の言葉であってもダイナスは躊躇わない。傭兵稼業を生きてきた彼にとって、命の奪い合いはシビアに競った結果だ。 そこに大人か子どもかの問題は些少なことであり、悼むことも悔やむことも全ては生き残ったあとにこそできる感傷でしかない。   故に割り切った。ただ、割り切ったダイナスの動きに淀みはないが、それでも不可解を胸に抱かずにはおれなかった。 今のバテンカイトスの囁きが、こう聞こえたからだ。   ――月食、と。   「――お?」   その音の正しい響きに至った直後、間の抜けた声が漏れた。 次の瞬間、小刀を振りかぶるダイナスの四肢が一斉に血を噴いている。四肢にはそれぞれ深々と短剣を突き込まれた傷が浮かび、正確に腱を抉られていた。   すなわち、四肢の機能の完全な喪失を意味し、崩れ落ちる体を止められない。   「く、あ!?」   顔面から石畳に落ちたダイナス、その頭が真上から思い切り踏みつけにされる。鼻面を石畳に潰されて、衝撃に呑まれたダイナスの意識が吹っ飛んだ。 うつ伏せで動かなくなるダイナス、その体を蹴りつけて、立ち上がったバテンカイトスがゆっくりと、オットーの方を振り返った。   「……ぁ」   その濁った瞳と、視線を交わすのは初めてではない。 なのにオットーの精神は、その濁った瞳に一瞬で絡め取られてしまった。   渦巻く狂気と怨嗟が、先ほどまでのそれと段違いにどす黒いものだったから。   「――――」   一瞬だった。 瞬きの間に距離が詰まり、気付いたときにはオットーの両足を灼熱が貫いた。見れば両足の腿の前面を、短剣が十字の傷口を生むように抉っている。   果物の皮でも剥くように、ぺろりとズボンとその下の肌がめくれた。肌の裏の赤い断面と桃色の筋肉、その中を這い回る白い神経と骨に、緑の血管が一切、傷付けられずに摘出されていて、オットーの喉が場違いな感慨に詰まった。   呆気に取られる。ここまで美しい技法は、お目にかかったことがない。 最小限の出血――否、一切の出血がないのだ。真に卓越した熟練の刃の扱いは、人間の肉体をこれほど耽美に破壊してせしめる。   「――――」   しゃがみ込んで、バテンカイトスがその傷口に口付けした。ざらりとした舌の感触が、肌の内側にあったオットーの足の重要部分の全てを舐める。 筋肉、骨、血管、神経、それらが舐られる感覚に身震いがあり、次の瞬間に視覚的にも触覚的にも、堪え難い嫌悪と激痛がオットーの脳を沸騰させた。   「あ、ぎゃあああああ――ッ!?」   血は、出ていない。意味がわからない。 ただ痛みだけがある。それも血の噴出の代わりとばかりに、剥き出しの骨や神経が湿った風に撫ぜられ、筋肉を丹念に針で剥かれるような凄絶な痛みが。 視界が明滅し、脳が爆ぜる。痛みを理解する器官が、その理解を拒絶する。絶叫する喉は血を吐くように震え上がり、動かない両足で悶えることもできない。   そうしてオットーが絶叫する中、それを見下ろすバテンカイトスは首を傾げた。長い焦げ茶の髪が肩を滑り落ち、『暴食』は疲れたような嘆息する。   「食休みかと思えばこの有様。美食だの悪食だのどうでもいいのに……本当、私たち以外は食事のなんたるかが全然わかってない」   それまでの、狂気的な笑みも態度も仕舞い込んで、ひどく達観した声音だった。 バテンカイトスがゆっくりと首を振り、まるで自嘲するかのような振る舞い――かと思えば、パッとその表情が変わり、   「そういう言い方はするなよォ。確かにちょっと遊んでて面倒はあったけど、それでもルイ好みの御馳走は見つけたんだからさァ」   牙を見せ、首を巡らせたバテンカイトスの視線がベアトリスたちを見た。その視線と、オットーの惨状に思わず二人の少女は息を呑む。が、そんな二人の反応を見たバテンカイトスの表情がまた、空虚でけだるげなものへと変わった。   「確かに悪くはないみたいだけど……中身より器の確保でしょう。それに、福音書の記述だって読み切れてないし」 「ルイは見えないかもだけど、それは僕たちの中にいる子が教えてくれてるさァ。あそこにいる、ベアトリス様がそうだよ、たぶん。やりきれば心身ともに満ちる、絶好の機会ってやつじゃないかッ!」   右を見て言い合い、左を見て言い合い、バテンカイトスは己の胸中ではなく、外からもはっきり見えるような形で自問自答する。 まるでそれは、自分の内側にいる別の何者かと会話するような光景だった。   いや、事実、その可能性がある。 『名前』を喰らう冒涜者、ライ・バテンカイトスの中には無数の魂がある。ならばそのいずれかと言葉を交わし、あるいは合議することすら可能なのかもしれない。 ならばこのおぞましい自問自答にも、理解が及ぶというものだ。   「動けるかしら、チビッ子」   「ああ?そっちの方こそ、ビビッてねーだろうな、チビ」   互いを罵り合いながら、ベアトリスとフェルトが意思疎通を交わす。お互いの瞳を覗き込み、どちらの戦意も折れていないことを確認。 フェルトは小さく鼻を鳴らすと、顎をしゃくって大広場の一角を示した。ベアトリスはそこに散らばるものを確かめて、その意図を察する。   「……あいつらはこのあと、ベティー狙いでくるかしら。足止めはしてやるのよ」   「止められんのかよ?攪乱ならアタシの方が……」   「二回ゲロ吐くほどアホなのを期待するわけにもいかんかしら。それに決め手はどう足掻いても、ベティーには扱えないものなのよ。お前がやるしかないかしら」   ベアトリスの提言に、フェルトが考え込む素振りを見せる。が、眉間に皺を寄せた彼女はすぐに首をひねり、金髪を掻き毟って「あー!」と声を上げた。 そして、ベアトリスに拳を向けると、   「しくじんなよ、チビッ子」   「お前こそかしら、チビ」   向けられた拳には特に何も返さず、互いに悪態だけついて決戦に挑む。 ベアトリスたちの話し合いが終わるのと、バテンカイトスの自問自答の終わりはほとんど同時だ。ダイナスとオットーを切り倒した戦闘力、あれが十全に発揮される場合、それと真っ向からぶつかれる自信はベアトリスにはない。   「それで、準備はよろしいですかァ、ベアトリス様ァ?」   「できてないって答えて猶予がもらえるならそうするのよ。でも、そうじゃないなら質問に意味なんてないかしら」   「まったくその通りです。んじゃァ、改めて――イタダキマス!」   真っ向から、バテンカイトスがベアトリスを目掛けて一直線に飛びついてくる。速度は先ほどの、悪夢じみた脅威ほどではない。とはいえ、それでもベアトリスには十分な脅威。接近戦の不利は変わらない。 だから、真っ向からぶつからないことが陰魔法の使い手としての本領だ。   「そォ、らァ――!」   ベアトリスの前方で、地面に手をついたバテンカイトスの体が縦に回る。振り下ろされる踵がベアトリスの真上から迫り、鋭い一撃が少女の脳天に突き刺さる。   「そうはいかないのよ」   ――寸前、ベアトリスの体がまたしても蹴りの風圧に背後へ傾いた。先ほど発動した『ムラク』の効果を切らずに残していた結果だ。 風圧に背後へ傾き、ベアトリスはその場で大きく真上へ飛び上がる。重力から解放され、体重という頸木もない少女の体はあまりにも軽々と浮かび上がった。 ドレスの裾を巧みに翻し、風を浴びるベアトリスの体が不規則に宙を舞う。   「お見事!ですがァ、対処が甘い!」   舌を伸ばしたバテンカイトスが落下地点に回り込んで、その着地を待たずに中空のベアトリスへ向かって掴みかかった。 猛禽が獲物を捕らえるような勢いと正確さで、その指先がベアトリスへ届く。しかしそれは同時に、逃げ場のない中空へ相手も上がった証拠だ。   魔法の残弾が限られている以上、当てることが最大の焦点。 ベアトリスは真下から迫るバテンカイトスへ掌を向け、四百年の生涯、そしてこの一年でもっとも使い慣れた魔法を詠唱する。 すなわち――、   「シャマク!!」   懐で魔石が砕け散り、ベアトリスの詠唱に応じて黒い靄が噴出――跳躍するバテンカイトスはそれに頭から突っ込み、無理解の世界へと閉じ込められた。   「もがァ――!?」   黒い靄が取り付き、バテンカイトスの体が無防備に石畳へ落ちる。振り切るまで何もできない状態が続くはずだが、シャマクの効果はそれほど長くない。 今のベアトリスの手札――利用できる魔石一つで致命打は奪えない。ならばベアトリスがこの瞬間、選ぶべき手段は。   「あァ!やってくれるなァ、ベアトリス様ッ。まるで、あの人みたいな戦い方をして……影響でも受けたんですかァ!?」   シャマクを振り払い、身を回したバテンカイトスが牙を剥いた。彼はぐるりと広場を見渡し、ベアトリスを目に留めるとそうのたまう。 彼の中にいる少女の記憶では、ベアトリスがスバルの隣に並び立っている光景はないはずだ。だから、ベアトリスがこうして奮戦する姿に彼の影響を見ても、それがどれだけ大きな意味を持つのか気付けない。   「そら、最後の魔石で大盤振る舞いなのよ!」   感傷を振り切り、ベアトリスは足下に転がるオットーへと掌を向けた。最後の魔石の魔力を使って、のたうち回るオットーの足の傷に癒しの波動を送る。 完全治癒は遠いが、それでも絶望的な痛みは遠のいたはずだ。涙を流して転がっていたオットーが、嗚咽まじりに大きく咳き込む。   「そんな役立たず、今、復活させてどうなるのッ?」   「こうなるのよ!」   一手を無駄にしたと嘲笑うバテンカイトスに、ベアトリスが怒鳴り返した。 その啖呵に眉を寄せた直後、バテンカイトスの足に背後から何かが食らいついた。左足に深々と牙を立てられて、体勢の崩れるバテンカイトス。 とっさの自分の足を見下ろし、それを見たバテンカイトスの目が見開かれた。   「はァ!?」   理解できないものへの驚き、そこにいたのは血塗れの水竜だ。 首を伸ばして、石畳を猛進した水竜がバテンカイトスに食らいついている。一度は戦闘不能まで追い込まれた水竜が、最後の意地を貫いて。   五つの魔石のうち、三つ目の魔石の使い道だ。 一つ目で強烈な、しかし不発に終わったウル・ミーニャ、二つ目が緊急回避用のムラクに使用され、そしてムラクで弾かれた先にいた瀕死の水竜を、三つ目の魔石で回復。 四つ目でシャマクを放ち、五つ目でオットーの痛みを遠ざけた。   それがベアトリスの五手、勝利を掴むための魔石の使い道だ。   「――ぁぁ!痛い痛い、痛いぃ!」   喉が嗄れるほど叫び、絶叫の中に水竜への呼びかけを隠したオットーが、役目を果たして今度こそ自分の痛覚のために泣き叫ぶ。 ベアトリスの治療を受けた直後、即座に求められるところを理解するあたり、オットーは本当に優秀だ。不本意にも戦いに巻き込まれることの多い、エミリア陣営の内政官は彼にしか勤まるまい。   「よくやったかしら、天職なのよ!」   「なんかわかんないけど嬉しくないんですが!」   ベアトリスの滅多にない称賛を浴びて、涙を流すオットーがそう応じる。そして二人の眼前、水竜に足を食らいつかれたバテンカイトスが地面に引き倒され、どうにかその牙を外して立ち上がろうとする。 しかし、それらの反応全てが、切り札を前に間に合わない。   「――準備、万端。よく稼いだぜ、チビッ子」   勝ち誇った声がして、硬い音を立ててミーティアの尻が地面を叩いた。 腰溜めに杖を構えて、フェルトはその先端をバテンカイトスへ向ける。彼女の手の中でミーティアはうっすらと光を帯び、その余波が包みを吹き飛ばした。   白い包みが外されると、そこから露わになったのは純白の細長い杖だ。 柄の長さは槍といっても通じるほど長く、凝った意匠もなければ、目を惹くような機構が組み込まれているわけでもない。 実用性一辺倒のその造りは、まさに造物主の精神を反映しているといえる。   道具に道具以上の価値を求めない、エキドナという『魔女』の精神そのものを。   「お母様……」   ベアトリスは実際に、エキドナがその杖を振るうところを見たことはない。それでもその杖の製作された目的と、その威力は知っている。 神龍ボルカニカへの嫌がらせ――神龍に干渉し得る、そうした兵器であると。   とはいえ、使用にはいくつかの条件がある。 その条件を満たすことが難しいのと、使用者の問題もあり、その底無しのスペックの全てを発揮しきることは厳しいが――。   「さぁ、ラインハルトさんにも通用する威力、味わってみろやぁ!」   条件を満たした状態で、マナが満タンのフェルトが使用者ならば期待値は十分。 握る所有者のマナをぐんぐんと吸い上げて、ミーティアは際限なく力を溜め込み、先端へ集まる光がバテンカイトスへ照準を定めた。   「――ッ」   さすがのバテンカイトスも、その威力には余裕を保っていられない。 致命の可能性があると見るや、バテンカイトスは即座に足を拘束する水竜の鼻面を短剣で一撃、牙がゆるんだ瞬間に足を引き抜き、裂傷を負いながら飛びずさる。 その瞬間、ミーティアが一際強く瞬いた。   「いっけ――っ!!」   ミーティアの先端で光が膨れ上がり、白光がバテンカイトスへ放たれた。 とっさに水竜の拘束を逃れたバテンカイトスは、その傷付いた足でどうにかその射線上から転がり出る。そのまま光は狙いを外し、水竜へと衝突――する直前、軌道が曲がった。光は複雑な軌道を描き、バテンカイトスへ追い縋る。   「な――ッ!?」   逃れる自分へ追い縋る光弾に、バテンカイトスは声を上げた。そのまま鋭い身のこなしと跳躍で、再接近する光弾の軌道から外れる。 しかし、無駄だ。光弾はバテンカイトスが逃れても、転がっても、跳躍しても、弧を描き、円を描き、追い縋り、直撃を狙う。   あれがエキドナの生み出した魔法兵器『ミーティア』の、最大の強み。 照準と定めた対象への、永続的な追尾機能だ。   エキドナが神龍ボルカニカへの『嫌がらせ』のために作った兵器。凝り性のエキドナが本気で、ただ『嫌がらせ』のために道具を製作すれば、それはその目的のために妥協を許さないものに仕上がって当然だ。 故にあの魔法器は、対象を逃さず、外れず、確実に届く兵器に成り果てた。   「ぬ、っぐ……なら、これはどうかなァ!?」   逃げても逃げても限度のない光弾の追跡に、業を煮やしたバテンカイトスが逆襲に打って出る。魔法力が高まり、バテンカイトスの周囲が凍り付いた。 浮かび上がる複数の氷柱が鋭い先端を光弾へ向け、嵐のような弾幕が白光へと飛び込んでいく――だが、その抗いは間違いだ。   氷柱は白光に当たる寸前、その先端からマナへと還元されて、命中する前に粉々になって光弾へ呑み込まれてしまう。それだけに留まらず、光弾は迫ってきた魔法迎撃を全て吸収して、ますますその威力と規模を拡大して対象へ迫るのだ。   「クソ、こんな……こんなッ!」   転がり、軌道からなんとか逃れ、バテンカイトスが悪態をこぼす。しかし、その左足の傷は深く、万全な跳躍を可能とはしない。 あるいは機敏に動ければ、ベアトリスたちの方へと光弾を誘導したり、フェルト本人を狙うことが可能だったかもしれないが、そこまでの余力はない。   やがて光弾は転がるバテンカイトスの周囲を回り、その逃げ場を塞ぎながら、ゆっくりと嬲るように『暴食』の体を破壊の力に押し包み――、   「こんな、馬鹿みたいなことで、僕たちが俺たちが――!」 「ごちゃごちゃうるさい。さっさと、日食を切ればいい」   直撃の瞬間、みじめったらしい声をバテンカイトスが上げ、それがまたひどく冷めた声に塗り潰された。そして、光が炸裂する。   「――――」   眩い白光が大広場の中央で膨れ上がり、これまでで最大のクレーターが生じる。 膨らんだ光は世界を白く塗り潰し、塗り潰された部分は色を失ったかのように消失してしまっていた。 丸い球状に大広場が抉られて、水路へ通じたそこに水が流れ込む。 だが、   「やれやれ、まったく。本当に出来の悪い兄弟を持つと苦労する」   その破壊の惨状の横で、水路を覗き込んでいる影がある。 焦げ茶の髪を長く伸ばし、傷だらけの体をした人物だ。その肉体的特徴は言うまでもなく、相対していたライ・バテンカイトスに他ならない。 如何なる方法でか、あの光弾の攻撃を回避したのか――しかし、この場でもっとも驚きに値するのはそこではない。   「どういう、ことかしら」   ベアトリスの呟きは、攻撃が当たらなかったことへの驚きではない。 そもそも、攻撃の当たる当たらないの問題ではないのだ。光弾が当たるべきはバテンカイトスであって、バテンカイトス以外には当たらないのだから。   だから、そこでこちらに背中を向ける、筋骨隆々とした大男には当たらなくて当然。問題はその男が、いったいどこから現れたのか。   「あれは『暴食』……ですか?」   苦しげに顔を上げて、同じものを見るオットーがそうこぼした。 否定してやりたいところだが、今のベアトリスにはそのための言葉がない。押し黙るベアトリスたちの視線に、ふとその大男が振り返った。   そこにいたのは、バテンカイトスとは似ても似つかない厳つい顔つきの男だ。 四十路に迫ろうかという見た目で、あの冒涜者と重なる部分は微塵もない。目を細めるベアトリスの前で、その男は自分の顎に手を当てて、   「そう不思議そうな顔をする必要はないわ。私たちはただ、こうしただけ」   と、見た目を裏切る女言葉で言って、男は自分の長い髪を軽く手刀で断つ。パラパラと髪の毛が舞い散り、それを見たベアトリスは光弾の回避方法を理解した。   ミーティアの追尾は、命中したという判定が為されるまで成立する。 あの威力だ。体の一部分にでも当たれば、十分に全身を巻き込むことができる。その点を逆手に取られた。   男――おそらくバテンカイトスは、自らの髪の毛を切断し、それを光弾に『肉体への接触』と錯覚させたのだ。そして、攻撃範囲から全力で逃れて、被害を免れた。 あるいは成立しない可能性もあった方策だが、今回に限れば満点の回答だ。   もともと、ミーティアに標的を定めさせるためには、標的となるものを識別するための『照準』を合わせる必要がある。 対象のオド、あるいはゲートと繋げて狙わせるのがベストだが、今回の場合は緊急的な措置として、戦いの最中に落ちたバテンカイトスの髪の毛を利用した。その分、髪の毛の囮の方に光弾の方も逸れてしまったのだ。   「――――」   そこまで考えたところで、ベアトリスは状況の悪さに歯噛みする。 切り札であったミーティアを、まさかそんな方法で回避されるとは思わなかった。魔石は使い切り、手元にあるのは自活用であり、パックのために温存したい一個。 オットーや他の男たちも戦えず、ミーティアにマナの大半を吸われたフェルトも、その場に崩れ落ちて荒い息をついている。   万事休す――そんな考えが浮かびかけるが、ベアトリスは首を横に振る。 敗北を受け入れるのは死んでからにすべきだ。スバルが絶望的な状況でこそ活路を見出すように、自分もそうしなくてはならない。   だからベアトリスはキッと顔を上げ、その男を睨みつけた。 視線を向けられて、バテンカイトスは目を丸くする。それから彼は腰に片手を当て、もう片方の掌で顔を覆った。そして、   「いい、いいわ、いいわね、いいわよ、いいじゃない、いいじゃないのさ、いいだろうからこそ……私たちも、あたしたちも、『食す』価値をあなたに見る」   「――っ」   告げられる戯言にベアトリスが反論する前に、バテンカイトスの体に変化が生じる。音を立てて骨が歪み、痛々しく血が噴出、大男の体が萎んだ。 新たに生じた傷口から大量の血を流し、息を荒げるのは少年の姿を取り戻したバテンカイトスだった。 バテンカイトスはその満身創痍の状態で、しかし狂的な笑みを浮かべる。低く喉を鳴らしながらこちらを見る『暴食』は、嬉しそうに両手を広げた。   「私たちの名前は、魔女教大罪司教『暴食』担当、ルイ・アルネブ」   「ルイ……?」   ライ・バテンカイトス、それが奴の名前のはずだ。 ふいに違う名前を名乗る意図が読めず、ベアトリスは眉を寄せる。と、その戸惑いの隙間を縫って、バテンカイトスは右足だけで強く地を蹴った。 何事かと身を固くするベアトリスだが、『暴食』は広場の端っこへ飛び、そこに落ちていたボロ切れを回収すると、傷だらけの肌を隠すようにまとう。 その上で、   「残念だけど今日はここまで。ライもロイも消耗しすぎたから。これ以上は産み落とすのに支障をきたすわ。また会いましょう、可愛いお嬢ちゃん」   「――!逃がすと、思っているのかしら!」   「強がりはやめなさいな。『蝕』はこの体じゃまともに扱えないけど、それでも全滅させるぐらいはできるのよ。そうしないのは、食卓が整っていないから」   踏み込もうとするベアトリスに、指を突き付けてバテンカイトスは首を振る。 ひどく女性的な仕草――否、実際、今のバテンカイトスは女性なのかもしれない。その本質の部分で、理解しがたい何かが起きている。 嫌悪感と警戒心から足の止まるベアトリスに、バテンカイトスは頷いた。   「美食のライも、悪食のロイもなァんにもわかってない。だってそう。食事は『何を食べるか』じゃない。『誰と食べるか』だもの」   「――――」   「じゃァね。次はきっと、あなたの大切な人と一緒に会いにきてね」   「待――」   待て、と呼びかけるより早く、バテンカイトスは大広場の影に滑り込んで消えた。あとを追いかけることは、負傷者だらけの状況でベアトリスにはできない。 深追いして、『暴食』の有利な状況へ引き込まれるのも無謀だ。   切り札であるミーティアが外された時点で、こうなる他にない。   「……してやられたって、ことなのよ」   舌打ちしたい気持ちを堪えて、ベアトリスは周囲を見渡す。 痛みにオットーは意識を朦朧とさせ、傭兵たちとフェルトの従者は気絶、失神。フェルトは悔しげにしているが、今にも倒れ込んでしまいそうだ。   そしてそれはベアトリスも例外ではない。 キリタカの必死の訴えに応じて、どうにか死者を出さずに済んだことだけが、ベアトリスがこの戦場へ参じた結果と受け止めるべきか。 いずれにせよ――。   「胸を張って、スバルに抱っこしてもらうわけにもいかなそうかしら……」   逃がした獲物――ライ・バテンカイトスの中に、少女の魂が眠っている。 そのことに確信を得て、それをスバルにどう伝えるべきか。   ベアトリスはひどく重苦しい悩みを抱きながら、朦朧とするフェルトに声をかけるためにそちらへ足を向けたのだった。   皮肉にも、大罪司教の離脱によってこの戦場の戦いも終息し――、   水門都市の戦場も、残すところあとわずかであった。
{ "pile_set_name": "Github" }
{ "name": "jss-swinging-cat-rx-example", "version": "1.0.0", "license": "ISC", "dependencies": { "dynamics.js": "^1.1.5", "hammerjs": "^2.0.8", "jss": "^10.0.3", "jss-preset-default": "^10.0.3", "rxjs": "^6.5.4" }, "devDependencies": { "parcel-bundler": "^1.6.1" } }
{ "pile_set_name": "Github" }
package managedapplications // Copyright (c) Microsoft and contributors. 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. // 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // ApplianceArtifactType enumerates the values for appliance artifact type. type ApplianceArtifactType string const ( // Custom ... Custom ApplianceArtifactType = "Custom" // Template ... Template ApplianceArtifactType = "Template" ) // PossibleApplianceArtifactTypeValues returns an array of possible values for the ApplianceArtifactType const type. func PossibleApplianceArtifactTypeValues() []ApplianceArtifactType { return []ApplianceArtifactType{Custom, Template} } // ApplianceLockLevel enumerates the values for appliance lock level. type ApplianceLockLevel string const ( // CanNotDelete ... CanNotDelete ApplianceLockLevel = "CanNotDelete" // None ... None ApplianceLockLevel = "None" // ReadOnly ... ReadOnly ApplianceLockLevel = "ReadOnly" ) // PossibleApplianceLockLevelValues returns an array of possible values for the ApplianceLockLevel const type. func PossibleApplianceLockLevelValues() []ApplianceLockLevel { return []ApplianceLockLevel{CanNotDelete, None, ReadOnly} } // ProvisioningState enumerates the values for provisioning state. type ProvisioningState string const ( // Accepted ... Accepted ProvisioningState = "Accepted" // Canceled ... Canceled ProvisioningState = "Canceled" // Created ... Created ProvisioningState = "Created" // Creating ... Creating ProvisioningState = "Creating" // Deleted ... Deleted ProvisioningState = "Deleted" // Deleting ... Deleting ProvisioningState = "Deleting" // Failed ... Failed ProvisioningState = "Failed" // Ready ... Ready ProvisioningState = "Ready" // Running ... Running ProvisioningState = "Running" // Succeeded ... Succeeded ProvisioningState = "Succeeded" // Updating ... Updating ProvisioningState = "Updating" ) // PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. func PossibleProvisioningStateValues() []ProvisioningState { return []ProvisioningState{Accepted, Canceled, Created, Creating, Deleted, Deleting, Failed, Ready, Running, Succeeded, Updating} } // ResourceIdentityType enumerates the values for resource identity type. type ResourceIdentityType string const ( // SystemAssigned ... SystemAssigned ResourceIdentityType = "SystemAssigned" ) // PossibleResourceIdentityTypeValues returns an array of possible values for the ResourceIdentityType const type. func PossibleResourceIdentityTypeValues() []ResourceIdentityType { return []ResourceIdentityType{SystemAssigned} }
{ "pile_set_name": "Github" }
// Generated from definition io.k8s.api.apps.v1beta2.ReplicaSetCondition /// ReplicaSetCondition describes the state of a replica set at a certain point. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReplicaSetCondition { /// The last time the condition transitioned from one status to another. pub last_transition_time: Option<crate::apimachinery::pkg::apis::meta::v1::Time>, /// A human readable message indicating details about the transition. pub message: Option<String>, /// The reason for the condition's last transition. pub reason: Option<String>, /// Status of the condition, one of True, False, Unknown. pub status: String, /// Type of replica set condition. pub type_: String, } impl<'de> serde::Deserialize<'de> for ReplicaSetCondition { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_last_transition_time, Key_message, Key_reason, Key_status, Key_type_, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "lastTransitionTime" => Field::Key_last_transition_time, "message" => Field::Key_message, "reason" => Field::Key_reason, "status" => Field::Key_status, "type" => Field::Key_type_, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = ReplicaSetCondition; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("ReplicaSetCondition") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_last_transition_time: Option<crate::apimachinery::pkg::apis::meta::v1::Time> = None; let mut value_message: Option<String> = None; let mut value_reason: Option<String> = None; let mut value_status: Option<String> = None; let mut value_type_: Option<String> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_last_transition_time => value_last_transition_time = serde::de::MapAccess::next_value(&mut map)?, Field::Key_message => value_message = serde::de::MapAccess::next_value(&mut map)?, Field::Key_reason => value_reason = serde::de::MapAccess::next_value(&mut map)?, Field::Key_status => value_status = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Key_type_ => value_type_ = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(ReplicaSetCondition { last_transition_time: value_last_transition_time, message: value_message, reason: value_reason, status: value_status.ok_or_else(|| serde::de::Error::missing_field("status"))?, type_: value_type_.ok_or_else(|| serde::de::Error::missing_field("type"))?, }) } } deserializer.deserialize_struct( "ReplicaSetCondition", &[ "lastTransitionTime", "message", "reason", "status", "type", ], Visitor, ) } } impl serde::Serialize for ReplicaSetCondition { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "ReplicaSetCondition", 2 + self.last_transition_time.as_ref().map_or(0, |_| 1) + self.message.as_ref().map_or(0, |_| 1) + self.reason.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.last_transition_time { serde::ser::SerializeStruct::serialize_field(&mut state, "lastTransitionTime", value)?; } if let Some(value) = &self.message { serde::ser::SerializeStruct::serialize_field(&mut state, "message", value)?; } if let Some(value) = &self.reason { serde::ser::SerializeStruct::serialize_field(&mut state, "reason", value)?; } serde::ser::SerializeStruct::serialize_field(&mut state, "status", &self.status)?; serde::ser::SerializeStruct::serialize_field(&mut state, "type", &self.type_)?; serde::ser::SerializeStruct::end(state) } }
{ "pile_set_name": "Github" }
package com.linkedin.camus.sweeper; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; public abstract class CamusSweeperPlanner { private static final Logger LOG = Logger.getLogger(CamusSweeperPlanner.class); protected Properties props; protected Set<Properties> outlierProperties = new HashSet<Properties>(); public CamusSweeperPlanner setPropertiesLogger(Properties props, Logger log) { this.props = props; return this; } public abstract List<Properties> createSweeperJobProps(String topic, Path inputDir, Path outputDir, FileSystem fs) throws IOException; protected abstract List<Properties> createSweeperJobProps(String topic, Path inputDir, Path outputDir, FileSystem fs, CamusSweeperMetrics metrics) throws IOException; // Simple check for reprocessing depending on the modified time of the source and destination // folder protected boolean shouldReprocess(FileSystem fs, List<Path> sources, Path dest) throws IOException { LOG.debug("source:" + sources.toString()); LOG.debug("dest:" + dest.toString()); FileStatus destStatus = fs.getFileStatus(dest); long destinationModTime = destStatus.getModificationTime(); for (Path source : sources) { if (shouldReprocess(fs, source, dest, destinationModTime)) return true; } return false; } private boolean shouldReprocess(FileSystem fs, Path source, Path dest, long destinationModTime) throws IOException { FileStatus sourceStatus = fs.getFileStatus(source); LOG.debug("source mod:" + sourceStatus.getModificationTime()); LOG.debug("dest mod:" + destinationModTime); if (sourceStatus.getModificationTime() > destinationModTime) { LOG.warn(String.format("mod time of source %s is %d, later than mod time of %s: %d", source, sourceStatus.getModificationTime(), dest, destinationModTime)); return true; } FileStatus[] statuses = fs.globStatus(new Path(source, "*"), new HiddenFilter()); for (FileStatus status : statuses) { if (shouldReprocess(fs, status.getPath(), dest, destinationModTime)) { return true; } } return false; } protected String pathListToCommaSeperated(List<Path> list) { ArrayList<Path> tmpList = new ArrayList<Path>(); tmpList.addAll(list); StringBuilder sb = new StringBuilder(tmpList.get(0).toString()); tmpList.remove(0); for (Path p : tmpList) { sb.append(",").append(p.toString()); } return sb.toString(); } public Set<Properties> getOutlierProperties() { return this.outlierProperties; } /** * Blocks processing of a job until the input is ready. * By default, will return immediately and proceed with the job. * @param jobProps Job properties. * @return true to proceed with the job, false to cancel the job. */ protected boolean waitUntilReadyToProcess(Properties jobProps, FileSystem fs) { return true; } }
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <[email protected]> // Copyright (C) 2008 Benoit Jacob <[email protected]> // // 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_HYPERPLANE_H #define EIGEN_HYPERPLANE_H namespace Eigen { /** \geometry_module \ingroup Geometry_Module * * \class Hyperplane * * \brief A hyperplane * * A hyperplane is an affine subspace of dimension n-1 in a space of dimension n. * For example, a hyperplane in a plane is a line; a hyperplane in 3-space is a plane. * * \param _Scalar the scalar type, i.e., the type of the coefficients * \param _AmbientDim the dimension of the ambient space, can be a compile time value or Dynamic. * Notice that the dimension of the hyperplane is _AmbientDim-1. * * This class represents an hyperplane as the zero set of the implicit equation * \f$ n \cdot x + d = 0 \f$ where \f$ n \f$ is a unit normal vector of the plane (linear part) * and \f$ d \f$ is the distance (offset) to the origin. */ template <typename _Scalar, int _AmbientDim, int _Options> class Hyperplane { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(_Scalar,_AmbientDim==Dynamic ? Dynamic : _AmbientDim+1) enum { AmbientDimAtCompileTime = _AmbientDim, Options = _Options }; typedef _Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; typedef DenseIndex Index; typedef Matrix<Scalar,AmbientDimAtCompileTime,1> VectorType; typedef Matrix<Scalar,Index(AmbientDimAtCompileTime)==Dynamic ? Dynamic : Index(AmbientDimAtCompileTime)+1,1,Options> Coefficients; typedef Block<Coefficients,AmbientDimAtCompileTime,1> NormalReturnType; typedef const Block<const Coefficients,AmbientDimAtCompileTime,1> ConstNormalReturnType; /** Default constructor without initialization */ inline Hyperplane() {} template<int OtherOptions> Hyperplane(const Hyperplane<Scalar,AmbientDimAtCompileTime,OtherOptions>& other) : m_coeffs(other.coeffs()) {} /** Constructs a dynamic-size hyperplane with \a _dim the dimension * of the ambient space */ inline explicit Hyperplane(Index _dim) : m_coeffs(_dim+1) {} /** Construct a plane from its normal \a n and a point \a e onto the plane. * \warning the vector normal is assumed to be normalized. */ inline Hyperplane(const VectorType& n, const VectorType& e) : m_coeffs(n.size()+1) { normal() = n; offset() = -n.dot(e); } /** Constructs a plane from its normal \a n and distance to the origin \a d * such that the algebraic equation of the plane is \f$ n \cdot x + d = 0 \f$. * \warning the vector normal is assumed to be normalized. */ inline Hyperplane(const VectorType& n, const Scalar& d) : m_coeffs(n.size()+1) { normal() = n; offset() = d; } /** Constructs a hyperplane passing through the two points. If the dimension of the ambient space * is greater than 2, then there isn't uniqueness, so an arbitrary choice is made. */ static inline Hyperplane Through(const VectorType& p0, const VectorType& p1) { Hyperplane result(p0.size()); result.normal() = (p1 - p0).unitOrthogonal(); result.offset() = -p0.dot(result.normal()); return result; } /** Constructs a hyperplane passing through the three points. The dimension of the ambient space * is required to be exactly 3. */ static inline Hyperplane Through(const VectorType& p0, const VectorType& p1, const VectorType& p2) { EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VectorType, 3) Hyperplane result(p0.size()); VectorType v0(p2 - p0), v1(p1 - p0); result.normal() = v0.cross(v1); RealScalar norm = result.normal().norm(); if(norm <= v0.norm() * v1.norm() * NumTraits<RealScalar>::epsilon()) { Matrix<Scalar,2,3> m; m << v0.transpose(), v1.transpose(); JacobiSVD<Matrix<Scalar,2,3> > svd(m, ComputeFullV); result.normal() = svd.matrixV().col(2); } else result.normal() /= norm; result.offset() = -p0.dot(result.normal()); return result; } /** Constructs a hyperplane passing through the parametrized line \a parametrized. * If the dimension of the ambient space is greater than 2, then there isn't uniqueness, * so an arbitrary choice is made. */ // FIXME to be consitent with the rest this could be implemented as a static Through function ?? explicit Hyperplane(const ParametrizedLine<Scalar, AmbientDimAtCompileTime>& parametrized) { normal() = parametrized.direction().unitOrthogonal(); offset() = -parametrized.origin().dot(normal()); } ~Hyperplane() {} /** \returns the dimension in which the plane holds */ inline Index dim() const { return AmbientDimAtCompileTime==Dynamic ? m_coeffs.size()-1 : Index(AmbientDimAtCompileTime); } /** normalizes \c *this */ void normalize(void) { m_coeffs /= normal().norm(); } /** \returns the signed distance between the plane \c *this and a point \a p. * \sa absDistance() */ inline Scalar signedDistance(const VectorType& p) const { return normal().dot(p) + offset(); } /** \returns the absolute distance between the plane \c *this and a point \a p. * \sa signedDistance() */ inline Scalar absDistance(const VectorType& p) const { using std::abs; return abs(signedDistance(p)); } /** \returns the projection of a point \a p onto the plane \c *this. */ inline VectorType projection(const VectorType& p) const { return p - signedDistance(p) * normal(); } /** \returns a constant reference to the unit normal vector of the plane, which corresponds * to the linear part of the implicit equation. */ inline ConstNormalReturnType normal() const { return ConstNormalReturnType(m_coeffs,0,0,dim(),1); } /** \returns a non-constant reference to the unit normal vector of the plane, which corresponds * to the linear part of the implicit equation. */ inline NormalReturnType normal() { return NormalReturnType(m_coeffs,0,0,dim(),1); } /** \returns the distance to the origin, which is also the "constant term" of the implicit equation * \warning the vector normal is assumed to be normalized. */ inline const Scalar& offset() const { return m_coeffs.coeff(dim()); } /** \returns a non-constant reference to the distance to the origin, which is also the constant part * of the implicit equation */ inline Scalar& offset() { return m_coeffs(dim()); } /** \returns a constant reference to the coefficients c_i of the plane equation: * \f$ c_0*x_0 + ... + c_{d-1}*x_{d-1} + c_d = 0 \f$ */ inline const Coefficients& coeffs() const { return m_coeffs; } /** \returns a non-constant reference to the coefficients c_i of the plane equation: * \f$ c_0*x_0 + ... + c_{d-1}*x_{d-1} + c_d = 0 \f$ */ inline Coefficients& coeffs() { return m_coeffs; } /** \returns the intersection of *this with \a other. * * \warning The ambient space must be a plane, i.e. have dimension 2, so that \c *this and \a other are lines. * * \note If \a other is approximately parallel to *this, this method will return any point on *this. */ VectorType intersection(const Hyperplane& other) const { using std::abs; EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(VectorType, 2) Scalar det = coeffs().coeff(0) * other.coeffs().coeff(1) - coeffs().coeff(1) * other.coeffs().coeff(0); // since the line equations ax+by=c are normalized with a^2+b^2=1, the following tests // whether the two lines are approximately parallel. if(internal::isMuchSmallerThan(det, Scalar(1))) { // special case where the two lines are approximately parallel. Pick any point on the first line. if(abs(coeffs().coeff(1))>abs(coeffs().coeff(0))) return VectorType(coeffs().coeff(1), -coeffs().coeff(2)/coeffs().coeff(1)-coeffs().coeff(0)); else return VectorType(-coeffs().coeff(2)/coeffs().coeff(0)-coeffs().coeff(1), coeffs().coeff(0)); } else { // general case Scalar invdet = Scalar(1) / det; return VectorType(invdet*(coeffs().coeff(1)*other.coeffs().coeff(2)-other.coeffs().coeff(1)*coeffs().coeff(2)), invdet*(other.coeffs().coeff(0)*coeffs().coeff(2)-coeffs().coeff(0)*other.coeffs().coeff(2))); } } /** Applies the transformation matrix \a mat to \c *this and returns a reference to \c *this. * * \param mat the Dim x Dim transformation matrix * \param traits specifies whether the matrix \a mat represents an #Isometry * or a more generic #Affine transformation. The default is #Affine. */ template<typename XprType> inline Hyperplane& transform(const MatrixBase<XprType>& mat, TransformTraits traits = Affine) { if (traits==Affine) normal() = mat.inverse().transpose() * normal(); else if (traits==Isometry) normal() = mat * normal(); else { eigen_assert(0 && "invalid traits value in Hyperplane::transform()"); } return *this; } /** Applies the transformation \a t to \c *this and returns a reference to \c *this. * * \param t the transformation of dimension Dim * \param traits specifies whether the transformation \a t represents an #Isometry * or a more generic #Affine transformation. The default is #Affine. * Other kind of transformations are not supported. */ template<int TrOptions> inline Hyperplane& transform(const Transform<Scalar,AmbientDimAtCompileTime,Affine,TrOptions>& t, TransformTraits traits = Affine) { transform(t.linear(), traits); offset() -= normal().dot(t.translation()); return *this; } /** \returns \c *this with scalar type casted to \a NewScalarType * * Note that if \a NewScalarType is equal to the current scalar type of \c *this * then this function smartly returns a const reference to \c *this. */ template<typename NewScalarType> inline typename internal::cast_return_type<Hyperplane, Hyperplane<NewScalarType,AmbientDimAtCompileTime,Options> >::type cast() const { return typename internal::cast_return_type<Hyperplane, Hyperplane<NewScalarType,AmbientDimAtCompileTime,Options> >::type(*this); } /** Copy constructor with scalar type conversion */ template<typename OtherScalarType,int OtherOptions> inline explicit Hyperplane(const Hyperplane<OtherScalarType,AmbientDimAtCompileTime,OtherOptions>& other) { m_coeffs = other.coeffs().template cast<Scalar>(); } /** \returns \c true if \c *this is approximately equal to \a other, within the precision * determined by \a prec. * * \sa MatrixBase::isApprox() */ template<int OtherOptions> bool isApprox(const Hyperplane<Scalar,AmbientDimAtCompileTime,OtherOptions>& other, const typename NumTraits<Scalar>::Real& prec = NumTraits<Scalar>::dummy_precision()) const { return m_coeffs.isApprox(other.m_coeffs, prec); } protected: Coefficients m_coeffs; }; } // end namespace Eigen #endif // EIGEN_HYPERPLANE_H
{ "pile_set_name": "Github" }
% test for meshing the inside of an object path(path,'toolbox/'); path(path,'data/'); name = 'mm'; n = 400; Ma = load_image(name,n-10); Ma = rescale(abs(Ma)); % to avoid that the shape touches the boundary M = zeros(n,n,3); M(6:n-5,6:n-5,:) = Ma; repimg = 'results/meshing-shape/'; if ~exist(repimg) mkdir(repimg); end M1 = mean(M,3); mask = 1-(M1==M1(1)); boundary = compute_shape_boundary(mask)'; Ibound = boundary(1,:) + (boundary(2,:)-1)*n; for k=1:size(M,3) Ma = M(:,:,k); Ma(M1<=0) = 1; Ma(Ibound) = 1; M(:,:,k) = Ma; end % number of samples for the mesh if not(exist('p')) p = 400; end % use an adaptive distance field if not(exist('use_adaptive')) use_adaptive = 1; end if use_adaptive % compute boundary points boundary = compute_shape_boundary(mask)'; % compute distance to boundary [D,Z,Q] = perform_fast_marching(ones(n), boundary); % set up a distancing field R = 0.8; D1 = min(rescale(D),R); H = sqrt( R^2 - (D1-R).^2 ) * n; W = rescale( D, 0.1,1 ); else W = ones(n); end %% perform sampling using farthest point L = zeros(n) - Inf; I = find(mask); L(I) = Inf; vertex = [n/2;n/2]; options.constraint_map = L; vertex = perform_farthest_point_sampling(W, vertex, p, options ); %% compute the associated triangulation [D,Z,Q] = perform_fast_marching(W, vertex, options); faces = compute_voronoi_triangulation(Q, vertex); %% display clf; hold on; imagesc(rescale(M)); axis image; axis off; plot_edges(compute_edges(faces), vertex(2:-1:1,:), 'r'); plot(vertex(2,:), vertex(1,:), 'b.', 'MarkerSize', 8); hold off; axis tight; axis image; axis off; colormap gray(256); axis ij; str = [name '-mesh-' num2str(p)]; if use_adaptive str = [str '-adaptive']; end saveas(gcf, [repimg str '.png'], 'png');
{ "pile_set_name": "Github" }
/* * drivers/pcmcia/sa1100_cerf.c * * PCMCIA implementation routines for CerfBoard * Based off the Assabet. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/device.h> #include <linux/init.h> #include <linux/delay.h> #include <mach/hardware.h> #include <asm/mach-types.h> #include <asm/irq.h> #include <mach/cerf.h> #include "sa1100_generic.h" #define CERF_SOCKET 1 static struct pcmcia_irqs irqs[] = { { CERF_SOCKET, CERF_IRQ_GPIO_CF_CD, "CF_CD" }, { CERF_SOCKET, CERF_IRQ_GPIO_CF_BVD2, "CF_BVD2" }, { CERF_SOCKET, CERF_IRQ_GPIO_CF_BVD1, "CF_BVD1" } }; static int cerf_pcmcia_hw_init(struct soc_pcmcia_socket *skt) { skt->irq = CERF_IRQ_GPIO_CF_IRQ; return soc_pcmcia_request_irqs(skt, irqs, ARRAY_SIZE(irqs)); } static void cerf_pcmcia_hw_shutdown(struct soc_pcmcia_socket *skt) { soc_pcmcia_free_irqs(skt, irqs, ARRAY_SIZE(irqs)); } static void cerf_pcmcia_socket_state(struct soc_pcmcia_socket *skt, struct pcmcia_state *state) { unsigned long levels = GPLR; state->detect = (levels & CERF_GPIO_CF_CD) ?0:1; state->ready = (levels & CERF_GPIO_CF_IRQ) ?1:0; state->bvd1 = (levels & CERF_GPIO_CF_BVD1)?1:0; state->bvd2 = (levels & CERF_GPIO_CF_BVD2)?1:0; state->wrprot = 0; state->vs_3v = 1; state->vs_Xv = 0; } static int cerf_pcmcia_configure_socket(struct soc_pcmcia_socket *skt, const socket_state_t *state) { switch (state->Vcc) { case 0: case 50: case 33: break; default: printk(KERN_ERR "%s(): unrecognized Vcc %u\n", __func__, state->Vcc); return -1; } if (state->flags & SS_RESET) { GPSR = CERF_GPIO_CF_RESET; } else { GPCR = CERF_GPIO_CF_RESET; } return 0; } static void cerf_pcmcia_socket_init(struct soc_pcmcia_socket *skt) { soc_pcmcia_enable_irqs(skt, irqs, ARRAY_SIZE(irqs)); } static void cerf_pcmcia_socket_suspend(struct soc_pcmcia_socket *skt) { soc_pcmcia_disable_irqs(skt, irqs, ARRAY_SIZE(irqs)); } static struct pcmcia_low_level cerf_pcmcia_ops = { .owner = THIS_MODULE, .hw_init = cerf_pcmcia_hw_init, .hw_shutdown = cerf_pcmcia_hw_shutdown, .socket_state = cerf_pcmcia_socket_state, .configure_socket = cerf_pcmcia_configure_socket, .socket_init = cerf_pcmcia_socket_init, .socket_suspend = cerf_pcmcia_socket_suspend, }; int __init pcmcia_cerf_init(struct device *dev) { int ret = -ENODEV; if (machine_is_cerf()) ret = sa11xx_drv_pcmcia_probe(dev, &cerf_pcmcia_ops, CERF_SOCKET, 1); return ret; }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2010 WiYun Inc. * Author: luma([email protected]) * * For all entities this program is free software; you can redistribute * it and/or modify it under the terms of the 'WiEngine' license with * the additional provision that 'WiEngine' must be credited in a manner * that can be be observed by end users, for example, in the credits or during * start up. (please find WiEngine logo in sdk's logo folder) * * 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 "wyMenuItemSprite.h" #include <stdlib.h> wyMenuItemSprite::~wyMenuItemSprite() { wyObjectRelease(m_normalState); wyObjectRelease(m_selectedState); wyObjectRelease(m_disabledState); } wyMenuItemSprite* wyMenuItemSprite::make(wyTargetSelector* downSelector, wyTargetSelector* upSelector, wySprite* normal, wySprite* selected, wySprite* disabled) { wyMenuItemSprite* n = WYNEW wyMenuItemSprite(downSelector, upSelector, normal, selected, disabled); return (wyMenuItemSprite*)n->autoRelease(); } void wyMenuItemSprite::draw() { // if no draw flag is set, call wyNode::draw and it // will decide forward drawing to java layer or not if(m_noDraw) { wyNode::draw(); return; } if (m_enabled) { if (m_selected) { if(m_selectedState != NULL) m_selectedState->draw(); else m_normalState->draw(); } else m_normalState->draw(); } else { if (m_disabledState != NULL) m_disabledState->draw(); else m_normalState->draw(); } } void wyMenuItemSprite::adjustContentSize() { if (m_enabled) { if (m_selected) { if(m_selectedState != NULL) setContentSize(m_selectedState->getWidth(), m_selectedState->getHeight()); else setContentSize(m_normalState->getWidth(), m_normalState->getHeight()); } else setContentSize(m_normalState->getWidth(), m_normalState->getHeight()); } else { if (m_disabledState != NULL) setContentSize(m_disabledState->getWidth(), m_disabledState->getHeight()); else setContentSize(m_normalState->getWidth(), m_normalState->getHeight()); } } void wyMenuItemSprite::setSelected(bool selected) { wyMenuItem::setSelected(selected); adjustContentSize(); } void wyMenuItemSprite::setEnabled(bool enabled) { wyMenuItem::setEnabled(enabled); adjustContentSize(); } void wyMenuItemSprite::setAlpha(int alpha) { m_normalState->setAlpha(alpha); if(m_selectedState != NULL) m_selectedState->setAlpha(alpha); if(m_disabledState != NULL) m_disabledState->setAlpha(alpha); } void wyMenuItemSprite::setColor(wyColor3B color) { m_normalState->setColor(color); if(m_selectedState != NULL) m_selectedState->setColor(color); if(m_disabledState != NULL) m_disabledState->setColor(color); } void wyMenuItemSprite::setColor(wyColor4B color) { m_normalState->setColor(color); if(m_selectedState != NULL) m_selectedState->setColor(color); if(m_disabledState != NULL) m_disabledState->setColor(color); } void wyMenuItemSprite::setBlendFunc(wyBlendFunc func) { m_normalState->setBlendFunc(func); if(m_selectedState != NULL) m_selectedState->setBlendFunc(func); if(m_disabledState != NULL) m_disabledState->setBlendFunc(func); } void wyMenuItemSprite::setRotation(float rot) { wyMenuItem::setRotation(rot); m_normalState->setRotation(rot); if(m_selectedState != NULL) m_selectedState->setRotation(rot); if(m_disabledState != NULL) m_disabledState->setRotation(rot); } void wyMenuItemSprite::setScale(float scale) { wyMenuItem::setScale(scale); m_normalState->setScale(scale); if(m_selectedState != NULL) m_selectedState->setScale(scale); if(m_disabledState != NULL) m_disabledState->setScale(scale); } void wyMenuItemSprite::setScaleX(float scaleX) { wyMenuItem::setScaleX(scaleX); m_normalState->setScaleX(scaleX); if(m_selectedState != NULL) m_selectedState->setScaleX(scaleX); if(m_disabledState != NULL) m_disabledState->setScaleX(scaleX); } void wyMenuItemSprite::setScaleY(float scaleY) { wyMenuItem::setScaleY(scaleY); m_normalState->setScaleY(scaleY); if(m_selectedState != NULL) m_selectedState->setScaleY(scaleY); if(m_disabledState != NULL) m_disabledState->setScaleY(scaleY); } wyMenuItemSprite::wyMenuItemSprite(wyTargetSelector* downSelector, wyTargetSelector* upSelector, wySprite* normal, wySprite* selected, wySprite* disabled) : wyMenuItem(downSelector, upSelector), m_normalState(NULL), m_selectedState(NULL), m_disabledState(NULL) { setNormalSprite(normal); setSelectedSprite(selected); setDisabledSprite(disabled); setContentSize(normal->getWidth(), normal->getHeight()); } void wyMenuItemSprite::setNormalSprite(wySprite* normal) { wyObjectRetain(normal); wyObjectRelease(m_normalState); m_normalState = normal; } void wyMenuItemSprite::setSelectedSprite(wySprite* selected) { wyObjectRetain(selected); wyObjectRelease(m_selectedState); m_selectedState = selected; } void wyMenuItemSprite::setDisabledSprite(wySprite* disabled) { wyObjectRetain(disabled); wyObjectRelease(m_disabledState); m_disabledState = disabled; }
{ "pile_set_name": "Github" }
/** * @file */ /* Copyright (C) 2002-2020 UFO: Alien Invasion. 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. */ #pragma once #include "ui_nodes.h" #include "node/ui_node_abstractnode.h" struct value_s; struct uiBehaviour_t; struct uiNode_t; struct hashTable_s; /** * @brief node behaviour, how a node work * @sa virtualFunctions */ struct uiBehaviour_t { /* behaviour attributes */ const char* name; /**< name of the behaviour: string type of a node */ const char* extends; /**< name of the extends behaviour */ UINodePtr manager; /**< manager of the behaviour */ bool registration; /**< True if we can define the behavior with registration function */ bool isVirtual; /**< true, if the node doesn't have any position on the screen */ bool isFunction; /**< true, if the node is a function */ bool isAbstract; /**< true, if we can't instantiate the behaviour */ bool isInitialized; /**< cache if we already have initialized the node behaviour */ bool focusEnabled; /**< true if the node can win the focus (should be use when type TAB) */ bool drawItselfChild; /**< if true, the node draw function must draw child, the core code will not do it */ const value_t** localProperties; /**< list of properties of the node */ int propertyCount; /**< number of the properties into the propertiesList. Cache value to speedup search */ intptr_t extraDataSize; /**< Size of the extra data used (it come from "u" attribute) @note use intptr_t because we use the virtual inheritance function (see virtualFunctions) */ uiBehaviour_t* super; /**< link to the extended node */ void* lua_SWIG_typeinfo; /**< pointer to a swig_type_info structure, set during initialization */ hashTable_s* nodeMethods; /**< hash map for storing lua defined node functions */ #ifdef DEBUG int count; /**< number of node allocated */ #endif }; /** * @brief Signature of a function to bind a node method. */ typedef void (*uiNodeMethod_t)(uiNode_t* node, const struct uiCallContext_s* context); /** * @brief Register a property to a behaviour. * It should not be used in the code * @param behaviour Target behaviour * @param name Name of the property * @param type Type of the property * @param pos position of the attribute (which store property memory) into the node structure * @param size size of the attribute (which store property memory) into the node structure * @see UI_RegisterNodeProperty * @see UI_RegisterExtradataNodeProperty * @return A link to the node property */ const struct value_s* UI_RegisterNodePropertyPosSize_(uiBehaviour_t* behaviour, const char* name, int type, size_t pos, size_t size); /** * @brief Initialize a property * @param BEHAVIOUR behaviour Target behaviour * @param NAME Name of the property * @param TYPE Type of the property * @param OBJECTTYPE Object type containing the property * @param ATTRIBUTE Name of the attribute of the object containing data of the property */ #define UI_RegisterNodeProperty(BEHAVIOUR, NAME, TYPE, OBJECTTYPE, ATTRIBUTE) UI_RegisterNodePropertyPosSize_(BEHAVIOUR, NAME, TYPE, offsetof(OBJECTTYPE, ATTRIBUTE), MEMBER_SIZEOF(OBJECTTYPE, ATTRIBUTE)) /** * @brief Return the offset of an extradata node attribute * @param TYPE Extradata type * @param MEMBER Attribute name * @sa offsetof */ #define UI_EXTRADATA_OFFSETOF_(TYPE, MEMBER) ((size_t) &((TYPE *)(UI_EXTRADATA_POINTER(0, TYPE)))->MEMBER) /** * @brief Initialize a property from extradata of node * @param BEHAVIOUR behaviour Target behaviour * @param NAME Name of the property * @param TYPE Type of the property * @param EXTRADATATYPE Object type containing the property * @param ATTRIBUTE Name of the attribute of the object containing data of the property */ #define UI_RegisterExtradataNodeProperty(BEHAVIOUR, NAME, TYPE, EXTRADATATYPE, ATTRIBUTE) UI_RegisterNodePropertyPosSize_(BEHAVIOUR, NAME, TYPE, UI_EXTRADATA_OFFSETOF_(EXTRADATATYPE, ATTRIBUTE), MEMBER_SIZEOF(EXTRADATATYPE, ATTRIBUTE)) /** * @brief Initialize a property which override an inherited property. * It is yet only used for the documentation. * @param BEHAVIOUR behaviour Target behaviour * @param NAME Name of the property */ #define UI_RegisterOveridedNodeProperty(BEHAVIOUR, NAME) ; /** * @brief Register a node method to a behaviour. * @param behaviour Target behaviour * @param name Name of the property * @param function function to execute the node method * @return A link to the node property */ const struct value_s* UI_RegisterNodeMethod(uiBehaviour_t* behaviour, const char* name, uiNodeMethod_t function); /** * @brief Return a property from a node behaviour * @return A property, else nullptr if not found. */ const struct value_s* UI_GetPropertyFromBehaviour(const uiBehaviour_t* behaviour, const char* name) __attribute__ ((warn_unused_result)); /** * @brief Return a property or lua based method from a node, node behaviour or inherited behaviour. * @return A local property or lua method, else nullptr if not found. * @note Important: in case of a lua method, free the allocated .string value holding the method name!!! */ const value_t* UI_GetPropertyOrLuaMethod(const uiNode_t* node, const char* name, value_t *out); /** * @brief Initialize a node behaviour memory, after registration, and before using it. * @param behaviour Behaviour to initialize */ void UI_InitializeNodeBehaviour(uiBehaviour_t* behaviour); void UI_AddBehaviourMethod (uiBehaviour_t* behaviour, const char* name, LUA_METHOD fcn); bool UI_HasBehaviourMethod (uiBehaviour_t* behaviour, const char* name); bool UI_GetBehaviourMethod (const uiBehaviour_t* behaviour, const char* name, LUA_METHOD &fcn);
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!126 &1 NavMeshLayers: m_ObjectHideFlags: 0 Built-in Layer 0: name: Default cost: 1 editType: 2 Built-in Layer 1: name: Not Walkable cost: 1 editType: 0 Built-in Layer 2: name: Jump cost: 2 editType: 2 User Layer 0: name: cost: 1 editType: 3 User Layer 1: name: cost: 1 editType: 3 User Layer 2: name: cost: 1 editType: 3 User Layer 3: name: cost: 1 editType: 3 User Layer 4: name: cost: 1 editType: 3 User Layer 5: name: cost: 1 editType: 3 User Layer 6: name: cost: 1 editType: 3 User Layer 7: name: cost: 1 editType: 3 User Layer 8: name: cost: 1 editType: 3 User Layer 9: name: cost: 1 editType: 3 User Layer 10: name: cost: 1 editType: 3 User Layer 11: name: cost: 1 editType: 3 User Layer 12: name: cost: 1 editType: 3 User Layer 13: name: cost: 1 editType: 3 User Layer 14: name: cost: 1 editType: 3 User Layer 15: name: cost: 1 editType: 3 User Layer 16: name: cost: 1 editType: 3 User Layer 17: name: cost: 1 editType: 3 User Layer 18: name: cost: 1 editType: 3 User Layer 19: name: cost: 1 editType: 3 User Layer 20: name: cost: 1 editType: 3 User Layer 21: name: cost: 1 editType: 3 User Layer 22: name: cost: 1 editType: 3 User Layer 23: name: cost: 1 editType: 3 User Layer 24: name: cost: 1 editType: 3 User Layer 25: name: cost: 1 editType: 3 User Layer 26: name: cost: 1 editType: 3 User Layer 27: name: cost: 1 editType: 3 User Layer 28: name: cost: 1 editType: 3
{ "pile_set_name": "Github" }
//****************************************************************** // // Copyright 2014 Intel Mobile Communications GmbH 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. // 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /** * @file * * This file contains the declaration of classes and its members related to * ResourceResponse. */ #ifndef OC_RESOURCERESPONSE_H_ #define OC_RESOURCERESPONSE_H_ #include "OCApi.h" #include <IServerWrapper.h> #include <ocstack.h> #include <OCRepresentation.h> namespace OC { class InProcServerWrapper; /** * @brief OCResourceResponse provides APIs to set the response details */ class OCResourceResponse { public: typedef std::shared_ptr<OCResourceResponse> Ptr; OCResourceResponse(): m_newResourceUri{}, m_errorCode{}, m_headerOptions{}, m_interface{}, m_representation{}, m_requestHandle{0}, m_resourceHandle{nullptr}, m_responseResult{} { } #if defined(_MSC_VER) && (_MSC_VER < 1900) OCResourceResponse(OCResourceResponse&& o): m_newResourceUri(std::move(o.m_newResourceUri)), m_errorCode(o.m_errorCode), m_headerOptions(std::move(o.m_headerOptions)), m_interface(std::move(o.m_interface)), m_representation(std::move(o.m_representation)), m_requestHandle(std::move(o.m_requestHandle)), m_resourceHandle(std::move(o.m_resourceHandle)), m_responseResult(std::move(o.m_responseResult)) { } OCResourceResponse& operator=(OCResourceResponse&& o) { m_newResourceUri = std::move(o.m_newResourceUri); m_errorCode = o.m_errorCode; m_headerOptions = std::move(o.m_headerOptions); m_interface = std::move(o.m_interface); m_representation = std::move(o.m_representation); m_requestHandle = std::move(o.m_requestHandle); m_resourceHandle = std::move(o.m_resourceHandle); m_responseResult = std::move(o.m_responseResult); } #else OCResourceResponse(OCResourceResponse&&) = default; OCResourceResponse& operator=(OCResourceResponse&&) = default; #endif virtual ~OCResourceResponse(void) {} /** * This API sets the error code for this response * @param eCode error code to set */ void setErrorCode(const int eCode) { m_errorCode = eCode; } /** * gets new resource uri * @return std::string new resource uri */ std::string getNewResourceUri(void) { return m_newResourceUri; } /** * sets new resource uri * @param newResourceUri specifies the resource uri of the resource created */ void setNewResourceUri(const std::string newResourceUri) { m_newResourceUri = newResourceUri; } /** * This API allows to set headerOptions in the response * @param headerOptions HeaderOptions vector consisting of OCHeaderOption objects */ void setHeaderOptions(const HeaderOptions& headerOptions) { m_headerOptions = headerOptions; } /** * This API allows to set request handle * * @param requestHandle - OCRequestHandle type used to set the request handle */ void setRequestHandle(const OCRequestHandle& requestHandle) { m_requestHandle = requestHandle; } /** * This API allows to set the resource handle * * @param resourceHandle - OCResourceHandle type used to set the resource handle */ void setResourceHandle(const OCResourceHandle& resourceHandle) { m_resourceHandle = resourceHandle; } /** * This API allows to set the EntityHandler response result * * @param responseResult - OCEntityHandlerResult type to set the result value */ void setResponseResult(const OCEntityHandlerResult& responseResult) { m_responseResult = responseResult; } /** * API to set the entire resource attribute representation * @param rep reference to the resource's representation * @param interface specifies the interface */ void setResourceRepresentation(OCRepresentation& rep, std::string iface) { m_interface = iface; m_representation = rep; } /** * API to set the entire resource attribute representation * @param rep rvalue reference to the resource's representation * @param interface specifies the interface */ void setResourceRepresentation(OCRepresentation&& rep, std::string iface) { setResourceRepresentation(rep, iface); } /** * API to set the entire resource attribute representation * @param rep reference to the resource's representation */ void setResourceRepresentation(OCRepresentation& rep) { // Call the default m_interface = DEFAULT_INTERFACE; m_representation = rep; } /** * API to set the entire resource attribute representation * @param rep rvalue reference to the resource's representation */ void setResourceRepresentation(OCRepresentation&& rep) { // Call the above function setResourceRepresentation(rep); } private: std::string m_newResourceUri; int m_errorCode; HeaderOptions m_headerOptions; std::string m_interface; OCRepresentation m_representation; OCRequestHandle m_requestHandle; OCResourceHandle m_resourceHandle; OCEntityHandlerResult m_responseResult; private: friend class InProcServerWrapper; OCRepPayload* getPayload() const { MessageContainer inf; OCRepresentation first(m_representation); if(m_interface==LINK_INTERFACE) { first.setInterfaceType(InterfaceType::LinkParent); } else if(m_interface==BATCH_INTERFACE) { first.setInterfaceType(InterfaceType::BatchParent); } else { first.setInterfaceType(InterfaceType::DefaultParent); } inf.addRepresentation(first); for(const OCRepresentation& rep : m_representation.getChildren()) { OCRepresentation cur(rep); if(m_interface==LINK_INTERFACE) { cur.setInterfaceType(InterfaceType::LinkChild); } else if(m_interface==BATCH_INTERFACE) { cur.setInterfaceType(InterfaceType::BatchChild); } else { cur.setInterfaceType(InterfaceType::DefaultChild); } inf.addRepresentation(cur); } return inf.getPayload(); } public: /** * Get error code */ int getErrorCode() const { return m_errorCode; } /** * Get the Response Representation */ const OCRepresentation& getResourceRepresentation() const { return m_representation; } /** * This API allows to retrieve headerOptions from a response */ const HeaderOptions& getHeaderOptions() const { return m_headerOptions; } /** * This API retrieves the request handle * * @return OCRequestHandle value */ const OCRequestHandle& getRequestHandle() const { return m_requestHandle; } /** * This API retrieves the resource handle * * @return OCResourceHandle value */ const OCResourceHandle& getResourceHandle() const { return m_resourceHandle; } /** * This API retrieves the entity handle response result * * @return OCEntityHandler result value */ OCEntityHandlerResult getResponseResult() const { return m_responseResult; } }; } // namespace OC #endif // OC_RESOURCERESPONSE_H_
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples</title> <link href="layout.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../jquery.js"></script> <script language="javascript" type="text/javascript" src="../jquery.flot.js"></script> <script language="javascript" type="text/javascript" src="../jquery.flot.image.js"></script> </head> <body> <h1>Flot Examples</h1> <div id="placeholder" style="width:400px;height:400px;"></div> <p>The Cat's Eye Nebula (<a href="http://hubblesite.org/gallery/album/nebula/pr2004027a/">picture from Hubble</a>).</p> <p>With the image plugin, you can plot images. This is for example useful for getting ticks on complex prerendered visualizations. Instead of inputting data points, you put in the images and where their two opposite corners are supposed to be in plot space.</p> <p>Images represent a little further complication because you need to make sure they are loaded before you can use them (Flot skips incomplete images). The plugin comes with a couple of helpers for doing that.</p> <script type="text/javascript"> $(function () { var data = [ [ ["hs-2004-27-a-large_web.jpg", -10, -10, 10, 10] ] ]; var options = { series: { images: { show: true } }, xaxis: { min: -8, max: 4 }, yaxis: { min: -8, max: 4 } }; $.plot.image.loadDataImages(data, options, function () { $.plot($("#placeholder"), data, options); }); }); </script> </body> </html>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <launchConfiguration type="org.eclipse.pde.ui.RuntimeWorkbench"> <booleanAttribute key="append.args" value="true"/> <booleanAttribute key="askclear" value="true"/> <booleanAttribute key="automaticAdd" value="true"/> <booleanAttribute key="automaticValidate" value="false"/> <stringAttribute key="bad_container_name" value="/ghidra.xtext.sleigh/.launch/"/> <stringAttribute key="bootstrap" value=""/> <stringAttribute key="checked" value="[NONE]"/> <booleanAttribute key="clearConfig" value="false"/> <booleanAttribute key="clearws" value="false"/> <booleanAttribute key="clearwslog" value="false"/> <stringAttribute key="configLocation" value="${workspace_loc}/.metadata/.plugins/org.eclipse.pde.core/Launch Runtime Eclipse"/> <booleanAttribute key="default" value="true"/> <booleanAttribute key="includeOptional" value="true"/> <stringAttribute key="location" value="${workspace_loc}/../runtime-EclipseXtext"/> <listAttribute key="org.eclipse.debug.ui.favoriteGroups"> <listEntry value="org.eclipse.debug.ui.launchGroup.debug"/> <listEntry value="org.eclipse.debug.ui.launchGroup.run"/> </listAttribute> <stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/> <stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl}"/> <stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.pde.ui.workbenchClasspathProvider"/> <stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-Xms40m -Xmx512m"/> <stringAttribute key="pde.version" value="3.3"/> <stringAttribute key="product" value="org.eclipse.platform.ide"/> <booleanAttribute key="show_selected_only" value="false"/> <stringAttribute key="templateConfig" value="${target_home}/configuration/config.ini"/> <booleanAttribute key="tracing" value="false"/> <booleanAttribute key="useDefaultConfig" value="true"/> <booleanAttribute key="useDefaultConfigArea" value="true"/> <booleanAttribute key="useProduct" value="true"/> <booleanAttribute key="usefeatures" value="false"/> </launchConfiguration>
{ "pile_set_name": "Github" }
/* * Copyright 2017 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dkpro.core.io.text; import java.io.OutputStream; import org.apache.commons.io.IOUtils; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.descriptor.ConfigurationParameter; import org.apache.uima.fit.descriptor.MimeTypeCapability; import org.apache.uima.fit.descriptor.ResourceMetaData; import org.apache.uima.fit.descriptor.TypeCapability; import org.apache.uima.jcas.JCas; import org.dkpro.core.api.io.JCasFileWriter_ImplBase; import org.dkpro.core.api.parameter.ComponentParameters; import org.dkpro.core.api.parameter.MimeTypes; import eu.openminted.share.annotations.api.DocumentationResource; /** * UIMA CAS consumer writing the CAS document text as plain text file. */ @ResourceMetaData(name = "Text Writer") @DocumentationResource("${docbase}/format-reference.html#format-${command}") @MimeTypeCapability({MimeTypes.TEXT_PLAIN}) @TypeCapability( inputs = { "de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData"}) public class TextWriter extends JCasFileWriter_ImplBase { /** * Specify the suffix of output files. Default value <code>.txt</code>. If the suffix is not * needed, provide an empty string as value. */ public static final String PARAM_FILENAME_EXTENSION = ComponentParameters.PARAM_FILENAME_EXTENSION; @ConfigurationParameter(name = PARAM_FILENAME_EXTENSION, mandatory = true, defaultValue = ".txt") private String filenameSuffix; /** * Character encoding of the output data. */ public static final String PARAM_TARGET_ENCODING = "targetEncoding"; @ConfigurationParameter(name = PARAM_TARGET_ENCODING, mandatory = true, defaultValue = ComponentParameters.DEFAULT_ENCODING) private String targetEncoding; @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { try (OutputStream docOS = getOutputStream(aJCas, filenameSuffix)) { IOUtils.write(aJCas.getDocumentText(), docOS, targetEncoding); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } } }
{ "pile_set_name": "Github" }
// Copyright 2018 Gin Core Team. All rights reserved. // Use of this source code is governed by a MIT style // license that can be found in the LICENSE file. package binding import ( "bytes" "io" "net/http" "gopkg.in/yaml.v2" ) type yamlBinding struct{} func (yamlBinding) Name() string { return "yaml" } func (yamlBinding) Bind(req *http.Request, obj interface{}) error { return decodeYAML(req.Body, obj) } func (yamlBinding) BindBody(body []byte, obj interface{}) error { return decodeYAML(bytes.NewReader(body), obj) } func decodeYAML(r io.Reader, obj interface{}) error { decoder := yaml.NewDecoder(r) if err := decoder.Decode(obj); err != nil { return err } return validate(obj) }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2011 Erin Catto http://box2d.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 <Box2D/Common/b2Math.h> /// Color for debug drawing. Each value has the range [0,1]. struct b2Color { b2Color() {} b2Color(float32 r, float32 g, float32 b) : r(r), g(g), b(b) {} void Set(float32 ri, float32 gi, float32 bi) { r = ri; g = gi; b = bi; } float32 r, g, b; }; /// Implement and register this class with a b2World to provide debug drawing of physics /// entities in your game. class b2Draw { public: b2Draw(); virtual ~b2Draw() {} enum { e_shapeBit = 0x0001, ///< draw shapes e_jointBit = 0x0002, ///< draw joint connections e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes e_pairBit = 0x0008, ///< draw broad-phase pairs e_centerOfMassBit = 0x0010 ///< draw center of mass frame }; /// Set the drawing flags. void SetFlags(uint32 flags); /// Get the drawing flags. uint32 GetFlags() const; /// Append flags to the current flags. void AppendFlags(uint32 flags); /// Clear flags from the current flags. void ClearFlags(uint32 flags); /// Draw a closed polygon provided in CCW order. virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; /// Draw a solid closed polygon provided in CCW order. virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; /// Draw a circle. virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; /// Draw a solid circle. virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; /// Draw a line segment. virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; /// Draw a transform. Choose your own length scale. /// @param xf a transform. virtual void DrawTransform(const b2Transform& xf) = 0; protected: uint32 m_drawFlags; };
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Scheme LastUpgradeVersion = "0460" version = "1.3"> <BuildAction parallelizeBuildables = "YES" buildImplicitDependencies = "YES"> <BuildActionEntries> <BuildActionEntry buildForTesting = "YES" buildForRunning = "YES" buildForProfiling = "YES" buildForArchiving = "YES" buildForAnalyzing = "YES"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "57115A041777B30100429015" BuildableName = "Loader.app" BlueprintName = "Loader" ReferencedContainer = "container:Loader.xcodeproj"> </BuildableReference> </BuildActionEntry> </BuildActionEntries> </BuildAction> <TestAction selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES" buildConfiguration = "Debug"> <Testables> </Testables> <MacroExpansion> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "57115A041777B30100429015" BuildableName = "Loader.app" BlueprintName = "Loader" ReferencedContainer = "container:Loader.xcodeproj"> </BuildableReference> </MacroExpansion> </TestAction> <LaunchAction selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle = "0" useCustomWorkingDirectory = "NO" buildConfiguration = "Debug" ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" allowLocationSimulation = "YES"> <BuildableProductRunnable> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "57115A041777B30100429015" BuildableName = "Loader.app" BlueprintName = "Loader" ReferencedContainer = "container:Loader.xcodeproj"> </BuildableReference> </BuildableProductRunnable> <AdditionalOptions> </AdditionalOptions> </LaunchAction> <ProfileAction shouldUseLaunchSchemeArgsEnv = "YES" savedToolIdentifier = "" useCustomWorkingDirectory = "NO" buildConfiguration = "Release" debugDocumentVersioning = "YES"> <BuildableProductRunnable> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "57115A041777B30100429015" BuildableName = "Loader.app" BlueprintName = "Loader" ReferencedContainer = "container:Loader.xcodeproj"> </BuildableReference> </BuildableProductRunnable> </ProfileAction> <AnalyzeAction buildConfiguration = "Debug"> </AnalyzeAction> <ArchiveAction buildConfiguration = "Release" revealArchiveInOrganizer = "YES"> </ArchiveAction> </Scheme>
{ "pile_set_name": "Github" }
package com.martinrgb.animer.core.math.converter; public class AndroidSpringConverter extends AnSpringConverter { private boolean otherParaCalculation = false; public AndroidSpringConverter(double stiffness,double dampingratio) { super(); calculate(stiffness,dampingratio,1,0); } public AndroidSpringConverter(double stiffness,double dampingratio,double mass,double velocity) { super(); calculate(stiffness,dampingratio,mass,velocity); } private void calculate(double s,double d,double m,double v){ mStiffness = s; mDampingRatio = d; mMass = m; mVelocity = v; mDamping = this.computeDamping(mStiffness, mDampingRatio,mMass); mTension = mStiffness; mFriction = mDamping; if(otherParaCalculation){ mBouncyTension = this.bouncyTesnionConversion(mTension); mBouncyFriction = this.bouncyFrictionConversion(mFriction); mDuration = this.computeDuration(mTension, mFriction,mMass); mS = this.getParaS(mBouncyTension,0.5,200); mSpeed = this.computeSpeed(this.getParaS(mBouncyTension,0.5,200),0.,20.); mB = this.getParaB(mBouncyFriction,this.b3Nobounce(mBouncyTension), 0.01); mBounciness = 20*1.7*mB/0.8; } } }
{ "pile_set_name": "Github" }
class A { fun buzz() {} }
{ "pile_set_name": "Github" }
// stylelint-disable declaration-no-important, selector-no-qualifying-type // Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css // ========================================================================== // Print styles. // Inlined to avoid the additional HTTP request: // https://www.phpied.com/delay-loading-your-print-css/ // ========================================================================== @if $enable-print-styles { @media print { *, *::before, *::after { // Bootstrap specific; comment out `color` and `background` //color: $black !important; // Black prints faster text-shadow: none !important; //background: transparent !important; box-shadow: none !important; } a { &:not(.btn) { text-decoration: underline; } } // Bootstrap specific; comment the following selector out //a[href]::after { // content: " (" attr(href) ")"; //} abbr[title]::after { content: " (" attr(title) ")"; } // Bootstrap specific; comment the following selector out // // Don't show links that are fragment identifiers, // or use the `javascript:` pseudo protocol // //a[href^="#"]::after, //a[href^="javascript:"]::after { // content: ""; //} pre { white-space: pre-wrap !important; } pre, blockquote { border: $border-width solid $gray-500; // Bootstrap custom code; using `$border-width` instead of 1px page-break-inside: avoid; } // // Printing Tables: // http://css-discuss.incutio.com/wiki/Printing_Tables // thead { display: table-header-group; } tr, img { page-break-inside: avoid; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } // Bootstrap specific changes start // Specify a size and min-width to make printing closer across browsers. // We don't set margin here because it breaks `size` in Chrome. We also // don't use `!important` on `size` as it breaks in Chrome. @page { size: $print-page-size; } body { min-width: $print-body-min-width !important; } .container { min-width: $print-body-min-width !important; } // Bootstrap components .navbar { display: none; } .badge { border: $border-width solid $black; } .table { border-collapse: collapse !important; td, th { background-color: $white !important; } } .table-bordered { th, td { border: 1px solid $gray-300 !important; } } .table-dark { color: inherit; th, td, thead th, tbody + tbody { border-color: $table-border-color; } } .table .thead-dark th { color: inherit; border-color: $table-border-color; } // Bootstrap specific changes end } }
{ "pile_set_name": "Github" }
[package] name = "simple_image" version = "0.1.0" authors = ["Max Holder <[email protected]>"] [dependencies] image = "*"
{ "pile_set_name": "Github" }
{ "chat.chatting_with": "與<span id=\"chat-with-name\"></span>聊天", "chat.placeholder": "在這裡輸入聊天訊息,按返回鍵發送", "chat.scroll-up-alert": "You are looking at older messages, click here to go to most recent message.", "chat.send": "發送", "chat.no_active": "暫無聊天", "chat.user_typing": "%1 正在輸入……", "chat.user_has_messaged_you": "%1 向您發送了訊息。", "chat.see_all": "查看所有對話", "chat.mark_all_read": "將所有聊天標為已讀", "chat.no-messages": "請選擇接收人,以查看聊天訊息紀錄", "chat.no-users-in-room": "此聊天室中沒有使用者", "chat.recent-chats": "最近聊天", "chat.contacts": "聯絡人", "chat.message-history": "訊息紀錄", "chat.message-deleted": "訊息已刪除", "chat.options": "聊天設定", "chat.pop-out": "彈出聊天視窗", "chat.minimize": "最小化", "chat.maximize": "最大化", "chat.seven_days": "7天", "chat.thirty_days": "30天", "chat.three_months": "3個月", "chat.delete_message_confirm": "您確定刪除此訊息嗎?", "chat.retrieving-users": "搜尋使用者", "chat.manage-room": "管理聊天室", "chat.add-user-help": "在這裡搜尋更多使用者。選中之後加入到聊天中,新使用者在加入聊天之前看不到聊天訊息。只有聊天室所有者(<i class=\"fa fa-star text-warning\"></i>)可以從聊天室中移除使用者。", "chat.confirm-chat-with-dnd-user": "該使用者已將其狀態設置為 DnD(請勿打擾)。 您仍希望與其聊天嗎?", "chat.rename-room": "重新命名房間", "chat.rename-placeholder": "在這裡輸入房間名字", "chat.rename-help": "這裡設定的房間名字能夠被房間內所有人都看到。", "chat.leave": "離開聊天室", "chat.leave-prompt": "您確定要離開聊天室?", "chat.leave-help": "離開此聊天會將您在聊天中的未接收的訊息移除。您在重新加入之後不會看到任何聊天記錄", "chat.in-room": "在此房間", "chat.kick": "踢出", "chat.show-ip": "顯示 IP", "chat.owner": "房間所有者", "chat.system.user-join": "%1 加入了房間", "chat.system.user-leave": "%1 離開了房間", "chat.system.room-rename": "%2 更改房間名為:%1", "composer.compose": "撰寫", "composer.show_preview": "顯示預覽", "composer.hide_preview": "隱藏預覽", "composer.user_said_in": "%1 在 %2 中說:", "composer.user_said": "%1 說:", "composer.discard": "確定想要取消此貼文?", "composer.submit_and_lock": "提交並鎖定", "composer.toggle_dropdown": "標為 Dropdown", "composer.uploading": "正在上傳 %1", "composer.formatting.bold": "粗體", "composer.formatting.italic": "斜體", "composer.formatting.list": "清單", "composer.formatting.strikethrough": "刪除線", "composer.formatting.code": "程式碼", "composer.formatting.link": "連結", "composer.formatting.picture": "圖片", "composer.upload-picture": "上傳圖片", "composer.upload-file": "上傳檔案", "composer.zen_mode": "無干擾模式", "composer.select_category": "選擇一個版面", "composer.textarea.placeholder": "Enter your post content here, drag and drop images", "bootbox.ok": "確認", "bootbox.cancel": "取消", "bootbox.confirm": "確認", "cover.dragging_title": "設定封面照片位置", "cover.dragging_message": "拖拽封面照片到期望的位置,然後點擊“儲存”", "cover.saved": "封面照片和位置已儲存" }
{ "pile_set_name": "Github" }
/* Declarations for internal libc locale interfaces Copyright (C) 1995, 96, 97, 98, 99,2000,2001 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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 License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #ifndef _LOCALEINFO_H #define _LOCALEINFO_H 1 #include <stddef.h> #include <langinfo.h> #include <limits.h> #include <time.h> #include <stdint.h> #include <sys/types.h> /* This has to be changed whenever a new locale is defined. */ #define __LC_LAST 13 #include "loadinfo.h" /* For loaded_l10nfile definition. */ /* Magic number at the beginning of a locale data file for CATEGORY. */ #define LIMAGIC(category) ((unsigned int) (0x20000828 ^ (category))) /* Two special weight constants for the collation data. */ #define IGNORE_CHAR 2 /* We use a special value for the usage counter in `locale_data' to signal that this data must never be removed anymore. */ #define MAX_USAGE_COUNT (UINT_MAX - 1) #define UNDELETABLE UINT_MAX /* Structure describing locale data in core for a category. */ struct locale_data { const char *name; const char *filedata; /* Region mapping the file data. */ off_t filesize; /* Size of the file (and the region). */ int mmaped; /* If nonzero the data is mmaped. */ unsigned int usage_count; /* Counter for users. */ int use_translit; /* Nonzero if the mb*towv*() and wc*tomb() functions should use transliteration. */ const char *options; /* Extra options from the locale name, not used in the path to the locale data. */ unsigned int nstrings; /* Number of strings below. */ union locale_data_value { const uint32_t *wstr; const char *string; unsigned int word; } values __flexarr; /* Items, usually pointers into `filedata'. */ }; /* We know three kinds of collation sorting rules. */ enum coll_sort_rule { illegal_0__, sort_forward, sort_backward, illegal_3__, sort_position, sort_forward_position, sort_backward_position, sort_mask }; /* We can map the types of the entries into a few categories. */ enum value_type { none, string, stringarray, byte, bytearray, word, stringlist, wordarray, wstring, wstringarray, wstringlist }; /* Definitions for `era' information from LC_TIME. */ #define ERA_NAME_FORMAT_MEMBERS 4 #define ERA_M_NAME 0 #define ERA_M_FORMAT 1 #define ERA_W_NAME 2 #define ERA_W_FORMAT 3 /* Structure to access `era' information from LC_TIME. */ struct era_entry { uint32_t direction; /* Contains '+' or '-'. */ int32_t offset; int32_t start_date[3]; int32_t stop_date[3]; const char *era_name; const char *era_format; const wchar_t *era_wname; const wchar_t *era_wformat; int absolute_direction; /* absolute direction: +1 indicates that year number is higher in the future. (like A.D.) -1 indicates that year number is higher in the past. (like B.C.) */ }; /* LC_CTYPE specific: Hardwired indices for standard wide character translation mappings. */ enum { __TOW_toupper = 0, __TOW_tolower = 1 }; /* LC_CTYPE specific: Access a wide character class with a single character index. _ISCTYPE (c, desc) = iswctype (btowc (c), desc). c must be an `unsigned char'. desc must be a nonzero wctype_t. */ #define _ISCTYPE(c, desc) \ (((((const uint32_t *) (desc)) - 8)[(c) >> 5] >> ((c) & 0x1f)) & 1) /* For each category declare the variable for the current locale data. */ #define DEFINE_CATEGORY(category, category_name, items, a) \ extern struct locale_data *_nl_current_##category; #include "categories.def" #undef DEFINE_CATEGORY extern const char *const _nl_category_names[__LC_LAST]; extern const size_t _nl_category_name_sizes[__LC_LAST]; extern struct locale_data * *const _nl_current[__LC_LAST]; /* Extract the current CATEGORY locale's string for ITEM. */ #define _NL_CURRENT(category, item) \ (_nl_current_##category->values[_NL_ITEM_INDEX (item)].string) /* Extract the current CATEGORY locale's string for ITEM. */ #define _NL_CURRENT_WSTR(category, item) \ ((wchar_t *) (_nl_current_##category->values[_NL_ITEM_INDEX (item)].wstr)) /* Extract the current CATEGORY locale's word for ITEM. */ #define _NL_CURRENT_WORD(category, item) \ (_nl_current_##category->values[_NL_ITEM_INDEX (item)].word) /* This is used in lc-CATEGORY.c to define _nl_current_CATEGORY. */ #define _NL_CURRENT_DEFINE(category) \ extern struct locale_data _nl_C_##category; \ struct locale_data *_nl_current_##category = &_nl_C_##category /* Load the locale data for CATEGORY from the file specified by *NAME. If *NAME is "", use environment variables as specified by POSIX, and fill in *NAME with the actual name used. The directories listed in LOCALE_PATH are searched for the locale files. */ extern struct locale_data *_nl_find_locale (const char *locale_path, size_t locale_path_len, int category, const char **name); /* Try to load the file described by FILE. */ extern void _nl_load_locale (struct loaded_l10nfile *file, int category); /* Free all resource. */ extern void _nl_unload_locale (struct locale_data *locale); /* Free the locale and give back all memory if the usage count is one. */ extern void _nl_remove_locale (int locale, struct locale_data *data); /* Return `era' entry which corresponds to TP. Used in strftime. */ extern struct era_entry *_nl_get_era_entry (const struct tm *tp); /* Return `era' cnt'th entry . Used in strptime. */ extern struct era_entry *_nl_select_era_entry (int cnt); /* Return `alt_digit' which corresponds to NUMBER. Used in strftime. */ extern const char *_nl_get_alt_digit (unsigned int number); /* Similar, but now for wide characters. */ extern const wchar_t *_nl_get_walt_digit (unsigned int number); /* Parse string as alternative digit and return numeric value. */ extern int _nl_parse_alt_digit (const char **strp); /* Postload processing. */ extern void _nl_postload_ctype (void); extern void _nl_postload_time (void); #endif /* localeinfo.h */
{ "pile_set_name": "Github" }
var socks = require('sockx'); var url = require('url'); var net = require('net'); var extend = require('extend'); var LRU = require('lru-cache'); var EventEmitter = require('events').EventEmitter; var hparser = require('hparser'); var dispatch = require('./https'); var util = require('./util'); var rules = require('./rules'); var socketMgr = require('./socket-mgr'); var rulesUtil = require('./rules/util'); var ca = require('./https/ca'); var pluginMgr = require('./plugins'); var config = require('./config'); var hasCustomCerts = ca.hasCustomCerts; var existsCustomCert = ca.existsCustomCert; var IP_CACHE = new LRU({ max: 600 }); var LOCALHOST = '127.0.0.1'; var TUNNEL_HOST_RE = /^[^:\/]+\.[^:\/]+:\d+$/; var X_RE = /^x/; var STATUS_CODES = require('http').STATUS_CODES || {}; var getRawHeaderNames = hparser.getRawHeaderNames; var formatHeaders = hparser.formatHeaders; var getRawHeaders = hparser.getRawHeaders; function tunnelProxy(server, proxy) { proxy.getTunnelIp = function(id) { return IP_CACHE.get(id); }; server.on('connect', function(req, reqSocket) {//ws, wss, https proxy var headers = req.headers; var tunnelUrl = req.fullUrl = util.setProtocol(TUNNEL_HOST_RE.test(req.url) ? req.url : headers.host, true); var options; var parseUrl = function (_url, port) { _url = _url || tunnelUrl; options = req.options = url.parse(_url); options.port = options.port || port || 443; return options; }; parseUrl(); reqSocket.on('error', util.noop); tunnelUrl = req.fullUrl = 'tunnel://' + options.host; proxy.emit('_request', tunnelUrl); var resSocket, responsed, reqEmitter, data, rulesMgr, originPort; var inspect, reqData, resData, res, rollBackTunnel, buf; req.isTunnel = true; req.method = util.toUpperCase(req.method) || 'CONNECT'; var clientInfo = util.parseClientInfo(req); reqSocket.clientIp = req.clientIp = clientInfo[0] || util.getClientIp(req); reqSocket.clientPort = req.clientPort = clientInfo[1] || util.getClientPort(req); delete headers[config.CLIENT_PORT_HEAD]; req.reqId = reqSocket.reqId = util.getReqId(); reqSocket.headers = headers; req.isPluginReq = reqSocket.isPluginReq = util.checkPluginReqOnce(req, true); var hostname = options.hostname; var isICloundCKDB = hostname === 'p22-ckdatabase.icloud.com'; var isIPHost = !isICloundCKDB && net.isIP(hostname); var policy = headers[config.WHISTLE_POLICY_HEADER]; var useTunnelPolicy = policy == 'tunnel'; var isLocalUIUrl = !useTunnelPolicy && config.isLocalUIUrl(hostname); if (isLocalUIUrl ? isIPHost : util.isLocalHost(hostname)) { isLocalUIUrl = options.port == config.port || options.port == config.uiport; } var _rules = req.rules = reqSocket.rules = (isICloundCKDB || isLocalUIUrl) ? {} : rules.initRules(req); rules.resolveRulesFile(req, function() { var filter = req.filter; var disable = req.disable; var isDisabeIntercept = function() { return isICloundCKDB || useTunnelPolicy || disable.intercept || disable.https || disable.capture || req.isPluginReq; }; var isCustomIntercept = function() { return filter.https || filter.capture || filter.intercept || policy === 'intercept'; }; var isWebPort = options.port == 80 || options.port == 443 || isCustomIntercept(); var isEnableIntercept = function() { if (isCustomIntercept()) { return true; } if (!rulesUtil.properties.isEnableCapture()) { return existsCustomCert(hostname); } return true; }; var isIntercept = function() { if (isLocalUIUrl || (!isDisabeIntercept() && isEnableIntercept())) { return true; } if (!isIPHost || !hasCustomCerts()) { return false; } reqSocket.useProxifier = (config.proxifier2 || (config.proxifier && isWebPort)) && !disable.proxifier; return reqSocket.useProxifier; }; var plugin = !isIntercept() && pluginMgr.resolveWhistlePlugins(req); var handlePluginRules = function(_rulesMgr) { if (_rulesMgr) { rulesMgr = _rulesMgr; req.curUrl = tunnelUrl; util.mergeRules(req, rulesMgr.resolveRules(req)); plugin = pluginMgr.getPluginByRuleUrl(util.rule.getUrl(_rules.rule)); } filter = req.filter; disable = req.disable; if (headers[config.WEBUI_HEAD]) { delete headers[config.WEBUI_HEAD]; reqSocket.destroy(); return false; } return true; }; pluginMgr.getTunnelRules(req, function(_rulesMgr) { abortIfUnavailable(reqSocket); if (!handlePluginRules(_rulesMgr)) { return; } if (isIntercept()) { reqSocket.rulesHeaders = req.rulesHeaders; reqSocket.tunnelHost = options.host; reqSocket.enable = req.enable; reqSocket.disable = req.disable; reqSocket._curHostname = hostname; dispatch(reqSocket, function(chunk) { if (isLocalUIUrl || (isIPHost && util.isLocalAddress(hostname) && options.port == config.port)) { return reqSocket.destroy(); } buf = chunk; reqSocket.pause(); rollBackTunnel = true; plugin = pluginMgr.resolveWhistlePlugins(req); pluginMgr.getTunnelRules(req, function(_rulesMgr2) { if (handlePluginRules(_rulesMgr2)) { handleTunnel(); } }); }, !req.enable.socket && isWebPort); util.setEstablished(reqSocket); return; } handleTunnel(); function handleTunnel() { var reqRawHeaderNames = getRawHeaderNames(req.rawHeaders) || {}; var enable = req.enable; inspect = util.isInspect(enable) || util.isCustomParser(req); reqData = { ip: req.clientIp, port: req.clientPort, method: req.method, httpVersion: req.httpVersion || '1.1', headers: headers, rawHeaderNames: reqRawHeaderNames }; resData = {headers: {}}; reqEmitter = new EventEmitter(); data = { id: req.reqId, url: options.host, startTime: Date.now(), rules: _rules, req: reqData, res: resData, isHttps: true, inspect: inspect, rulesHeaders: req.rulesHeaders }; if (!req.isPluginReq && !config.rulesMode && (!filter.hide || disable.hide)) { data.abort = emitError; proxy.emit('request', reqEmitter, data); } util.parseRuleJson(_rules.reqHeaders, function(reqHeaders) { var customXFF; if (reqHeaders) { reqHeaders = util.lowerCaseify(reqHeaders, reqRawHeaderNames); customXFF = reqHeaders[config.CLIENT_IP_HEAD]; delete reqHeaders[config.CLIENT_IP_HEAD]; extend(headers, reqHeaders); } if (disable.clientIp || disable.clientIP) { delete headers[config.CLIENT_IP_HEAD]; } else { var forwardedFor = util.getMatcherValue(_rules.forwardedFor); if (net.isIP(forwardedFor)) { headers[config.CLIENT_IP_HEAD] = forwardedFor; } else if (net.isIP(customXFF)) { headers[config.CLIENT_IP_HEAD] = customXFF; } else if (util.isLocalAddress(req.clientIp)) { delete headers[config.CLIENT_IP_HEAD]; } else { headers[config.CLIENT_IP_HEAD] = req.clientIp; } } var delReqHeaders = util.parseDeleteProperties(req).reqHeaders; Object.keys(delReqHeaders).forEach(function(name) { delete headers[name]; }); pluginMgr.postStats(req); if (enable.abort || filter.abort || disable.tunnel) { return reqSocket.destroy(); } var statusCode = util.getStatusCodeFromRule(_rules); if (statusCode) { if (statusCode == 200) { resSocket = util.getEmptyRes(); var reqDelay = util.getMatcherValue(_rules.reqDelay); data.requestTime = data.dnsTime = Date.now(); if (reqDelay > 0) { setTimeout(handleConnect, reqDelay); } else { handleConnect(); } return; } return sendEstablished(statusCode); } pluginMgr.loadPlugin(plugin, function(err, ports) { if (err) { return sendEstablished(500); } var tunnelPort = ports && (ports.tunnelPort || ports.port); var proxyUrl; if(tunnelPort) { proxyUrl = 'proxy://127.0.0.1:' + tunnelPort; reqSocket.customParser = req.customParser = util.getParserStatus(req); pluginMgr.addRuleHeaders(req, _rules); headers[config.PLUGIN_HOOK_NAME_HEADER] = config.PLUGIN_HOOKS.TUNNEL; socketMgr.setPending(req); data.reqPlugin = 1; } var realUrl = _rules.rule && _rules.rule.url; if (realUrl) { var isHttp; if (/^https?:/.test(realUrl)) { isHttp = realUrl[4] === ':'; realUrl = 'tunnel' + realUrl.substring(realUrl.indexOf(':')); } if (/^tunnel:\/\//.test(realUrl) && realUrl != tunnelUrl) { tunnelUrl = realUrl; data.realUrl = realUrl.replace('tunnel://', ''); parseUrl(tunnelUrl, isHttp ? 80 : 443); } } originPort = options.port; if (_rules.ua) { var ua = util.getMatcherValue(_rules.ua); headers['user-agent'] = ua; } rules.getProxy(tunnelUrl, proxyUrl ? null : req, function(err, hostIp, hostPort) { var proxyRule = _rules.proxy || ''; if (!proxyUrl) { proxyUrl = proxyRule ? util.rule.getMatcher(proxyRule) : null; } var isXProxy; if (proxyUrl) { isXProxy = X_RE.test(proxyUrl); var isSocks = proxyRule.isSocks; var isHttpsProxy = proxyRule.isHttps; var _url = 'http:' + util.removeProtocol(proxyUrl); data.proxy = true; getServerIp(_url, function(ip) { options = parseUrl(_url, isSocks ? 1080 : (isHttpsProxy ? 443 : 80)); var isProxyPort = options.port == config.port; if (isProxyPort && util.isLocalAddress(ip)) { return emitError(new Error('Self loop (' + ip + ':' + config.port + ')')); } var handleProxy = function(proxySocket, _res) { resSocket = proxySocket; res = _res; // 通知插件连接建立成功的回调 handleConnect(); abortIfUnavailable(resSocket); }; var dstOptions = url.parse(tunnelUrl); dstOptions.proxyHost = ip; dstOptions.proxyPort = parseInt(options.port, 10); dstOptions.port = dstOptions.port || 443; resData.port = dstOptions.proxyPort; dstOptions.host = dstOptions.hostname; util.setClientId(headers, req.enable, req.disable, req.clientIp, proxyRule.isInternal); var _headers = extend({}, headers); _headers.host = dstOptions.hostname + ':' + (dstOptions.port || 443); if (disable.proxyUA) { delete _headers['user-agent']; } dstOptions.headers = formatHeaders(_headers, reqRawHeaderNames); if (isSocks) { dstOptions.proxyPort = options.port || 1080; dstOptions.localDNS = false; dstOptions.auths = config.getAuths(options); } else { dstOptions.proxyPort = options.port || 80; dstOptions.proxyAuth = options.auth; if (isProxyPort) { _headers[config.WEBUI_HEAD] = 1; } } var netMgr = isSocks ? socks : config; var reqDelay = util.getMatcherValue(_rules.reqDelay); util.setProxyHost(req, dstOptions, true); if (isHttpsProxy) { dstOptions.proxyServername = options.hostname; } var connectProxy = function() { if (responsed) { return; } if (req.isPluginReq) { var host = ip + ':' + dstOptions.proxyPort; if (req._phost && req._phost.host) { IP_CACHE.set(req.isPluginReq, req._phost.host + ', ' + host); } else { IP_CACHE.set(req.isPluginReq, host); } } else if (req._phost) { resData.phost = req._phost.host; } resData.port = dstOptions.port; try { var s = netMgr.connect(dstOptions, handleProxy); s.on('error', function(err) { if (isXProxy) { resData.phost = undefined; tunnel(); } else { emitError(err); } }); } catch (e) { emitError(e); } }; if (reqDelay > 0) { setTimeout(connectProxy, reqDelay); } else { connectProxy(); } }); } else { tunnel(hostIp, hostPort); } }); }); }); } var retryConnect; var retryXHost = 0; function tunnel(hostIp, hostPort) { getServerIp(tunnelUrl, function(ip, port) { if (port) { req.hostIp = resData.ip = util.getHostIp(ip, port); resData.port = port; } else { req.hostIp = resData.ip = ip; // 不要赋值给port,否则重试时getServerIp会有端口 resData.port = port || originPort; } if (responsed) { return; } if (req.isPluginReq) { IP_CACHE.set(req.isPluginReq, req.hostIp); } resSocket = net.connect(resData.port, ip, handleConnect); if (retryConnect) { abortIfUnavailable(resSocket); } else { retryConnect = function() { if (retryXHost < 2 && _rules.host && X_RE.test(_rules.host.matcher)) { ++retryXHost; retryConnect = false; if (retryXHost > 1) { req.curUrl = tunnelUrl; rules.lookupHost(req, function(_err, _ip) { if (_err) { return emitError(_err); } tunnel(_ip, originPort); }); return; } } tunnel(ip, port); }; var retried; resSocket.on('error', function() { if (!retried) { retried = true; this.destroy && this.destroy(); !responsed && retryConnect && retryConnect(); } }); } }, hostIp, hostPort); } function handleConnect() { if (retryConnect) { resSocket.removeListener('error', retryConnect); abortIfUnavailable(resSocket); retryConnect = null; } reqSocket.inspectFrames = useTunnelPolicy || inspect; reqSocket.fullUrl = tunnelUrl; reqSocket.enable = req.enable; reqSocket.disable = req.disable; reqSocket.filter = req.filter; reqSocket.hostIp = req.hostIp; reqSocket.method = req.method; reqSocket.headerRulesMgr = req.headerRulesMgr; reqSocket.clientPort = req.clientPort; reqSocket.globalValue = req.globalValue; resSocket.statusCode = resData.statusCode; if (buf) { reqSocket.unshift(buf); buf = null; } pluginMgr.resolvePipePlugin(reqSocket, function() { data.pipe = reqSocket._pipeRule; if (reqSocket._pipePluginPorts) { reqSocket.inspectFrames = data.inspect = true; reqSocket.customParser = false; } socketMgr.handleConnect(reqSocket, resSocket); var resDelay = util.getMatcherValue(_rules.resDelay); if (resDelay > 0) { setTimeout(sendEstablished, resDelay); } else { sendEstablished(); } }); } function getServerIp(url, callback, hostIp, hostPort) { var hostHandler = function(err, ip, port, host) { if (host) { _rules.host = host; } data.requestTime = data.dnsTime = Date.now(); req.hostIp = resData.ip = ip || LOCALHOST; reqEmitter.emit('send', data); err ? emitError(err) : callback(ip, port); }; if (hostIp) { hostHandler(null, hostIp, hostPort); } else { req.curUrl = url; rules.resolveHost(req, hostHandler, rulesMgr, req.rulesFileMgr, req.headerRulesMgr); } } function abortIfUnavailable(socket) { util.onSocketEnd(socket, emitError); } function sendEstablished(code) { if (res) { code = res.statusCode; if (!res.headers['proxy-agent']) { res.headers['proxy-agent'] = config.name; res.rawHeaders = res.rawHeaders || []; res.rawHeaders.push('proxy-agent', 'Proxy-Agent'); } } else { code = code || 200; res = { statusCode: code, headers: { 'proxy-agent': config.name }, rawHeaders: ['proxy-agent', 'Proxy-Agent'] }; } var resHeaders = res.headers; pluginMgr.getResRules(req, res, function() { var reqRules = req.rules; util.parseRuleJson(rollBackTunnel ? null : reqRules.resHeaders, function(newResHeaders) { if (rollBackTunnel) { reqSocket.resume(); } else { var rawHeaderNames = getRawHeaderNames(res.rawHeaders) || {}; if (newResHeaders) { util.lowerCaseify(newResHeaders, rawHeaderNames); extend(resHeaders, newResHeaders); } var responseFor = util.getMatcherValue(reqRules.responseFor); if (responseFor) { resHeaders['x-whistle-response-for'] = responseFor; } util.setResponseFor(reqRules, resHeaders, req, req.hostIp); var delResHeaders = util.parseDeleteProperties(req).resHeaders; Object.keys(delResHeaders).forEach(function(name) { delete resHeaders[name]; }); var message = code == 200 ? 'Connection Established' : (STATUS_CODES[code] || 'unknown'); var statusLine = ['HTTP/1.1', code, message].join(' '); var rawData = [statusLine, getRawHeaders(formatHeaders(resHeaders, rawHeaderNames))].join('\r\n') + '\r\n\r\n'; if (code && code != 200) { reqSocket.end(rawData); } else { reqSocket.write(rawData); } } if (reqEmitter) { responsed = true; data.responseTime = data.endTime = Date.now(); resData.rawHeaderNames = rawHeaderNames; resData.statusCode = code || 200; resData.headers = resHeaders; reqEmitter.emit('response', data); reqEmitter.emit('end', data); } pluginMgr.postStats(req, res); }); }); return reqSocket; } var reqDestroyed, resDestroyed; function emitError(err) { if (!reqDestroyed && !responsed) { reqDestroyed = true; reqSocket.destroy(); } if (resSocket && !resDestroyed) { resDestroyed = true; resSocket.destroy(); } if (responsed) { return; } responsed = true; if (!reqEmitter) { return; } data.responseTime = data.endTime = Date.now(); if (!resData.ip) { req.hostIp = resData.ip = LOCALHOST; } if (!err && !resData.statusCode) { err = new Error('Aborted'); data.reqError = true; resData.statusCode ='aborted'; reqData.body = util.getErrorStack(err); reqEmitter.emit('abort', data); } else { data.resError = true; resData.statusCode = resData.statusCode || 502; resData.body = err ? util.getErrorStack(err) : 'Aborted'; util.emitError(reqEmitter, data); } resData.headers = {'x-server':'whistle' }; pluginMgr.postStats(req, resData); } }); }); }); return server; } module.exports = tunnelProxy;
{ "pile_set_name": "Github" }
define(function(require) { var Protoplast = require('protoplast'), BaseSectionViewPresenter = require('theme/aw-bubble/presenter/base-section-view-presenter'), PreviewController = require('plugin/preview/controller/preview-controller'); var PreviewViewPresenter = BaseSectionViewPresenter.extend({ settings: { inject: 'settings' }, previewController: { inject: PreviewController }, init: function() { BaseSectionViewPresenter.init.call(this); Protoplast.utils.bindProperty(this, 'settings.pdfjs_viewer', this, 'view.usePDFJSViewer'); }, _scriptChanged: function() { this.previewController.getPdf(function(result) { this.view.pdf = result; }.bind(this)); } }); return PreviewViewPresenter; });
{ "pile_set_name": "Github" }
{ "title": "Right-to-left Styling", "url": "https://myurl.com/", "description": "An extensive guide on how to style for RTL in CSS", "feed": { "subtitle": "An extensive guide on how to style for RTL in CSS", "filename": "feed.xml", "path": "/feed/feed.xml", "url": "https://myurl.com/feed/feed.xml", "id": "https://myurl.com/" }, "author": { "name": "Ahmad Shadeed", "email": "[email protected]" } }
{ "pile_set_name": "Github" }
/** * @file * This file is a posix wrapper for lwip/sockets.h. */ /* * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * This file is part of the lwIP TCP/IP stack. * */ #include "lwip/sockets.h"
{ "pile_set_name": "Github" }
package windows import ( "os" "runtime" "syscall" "testing" "github.com/pkg/errors" "github.com/stretchr/testify/assert" ) func TestGetProcessImageFileName(t *testing.T) { h, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(syscall.Getpid())) if err != nil { t.Fatal(err) } filename, err := GetProcessImageFileName(h) if err != nil { t.Fatal(err) } t.Logf("GetProcessImageFileName: %v", filename) } func TestGetProcessMemoryInfo(t *testing.T) { h, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(syscall.Getpid())) if err != nil { t.Fatal(err) } counters, err := GetProcessMemoryInfo(h) if err != nil { t.Fatal(err) } t.Logf("GetProcessMemoryInfo: ProcessMemoryCountersEx=%+v", counters) } func TestGetLogicalDriveStrings(t *testing.T) { drives, err := GetLogicalDriveStrings() if err != nil { t.Fatal(err) } t.Logf("GetLogicalDriveStrings: %v", drives) } func TestGetDriveType(t *testing.T) { drives, err := GetLogicalDriveStrings() if err != nil { t.Fatal(err) } for _, drive := range drives { dt, err := GetDriveType(drive) if err != nil { t.Fatal(err) } t.Logf("GetDriveType: drive=%v, type=%v", drive, dt) } } func TestGetSystemTimes(t *testing.T) { idle, kernel, user, err := GetSystemTimes() if err != nil { t.Fatal(err) } t.Logf("GetSystemTimes: idle=%v, kernel=%v, user=%v", idle, kernel, user) } func TestGlobalMemoryStatusEx(t *testing.T) { mem, err := GlobalMemoryStatusEx() if err != nil { t.Fatal(err) } t.Logf("GlobalMemoryStatusEx: %+v", mem) } func TestEnumProcesses(t *testing.T) { pids, err := EnumProcesses() if err != nil { t.Fatal(err) } t.Logf("EnumProcesses: %v", pids) } func TestGetDiskFreeSpaceEx(t *testing.T) { drives, err := GetLogicalDriveStrings() if err != nil { t.Fatal(err) } for _, drive := range drives { dt, err := GetDriveType(drive) if err != nil { t.Fatal(err) } // Ignore CDROM drives. They return an error if the drive is emtpy. if dt != DRIVE_CDROM { free, total, totalFree, err := GetDiskFreeSpaceEx(drive) if err != nil { t.Fatal(err) } t.Logf("GetDiskFreeSpaceEx: %v, %v, %v", free, total, totalFree) } } } func TestGetWindowsVersion(t *testing.T) { ver := GetWindowsVersion() assert.True(t, ver.Major >= 5) t.Logf("GetWindowsVersion: %+v", ver) } func TestCreateToolhelp32Snapshot(t *testing.T) { handle, err := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) if err != nil { t.Fatal(err) } defer syscall.CloseHandle(syscall.Handle(handle)) // Iterate over the snapshots until our PID is found. pid := uint32(syscall.Getpid()) for { process, err := Process32Next(handle) if errors.Cause(err) == syscall.ERROR_NO_MORE_FILES { break } if err != nil { t.Fatal(err) } t.Logf("CreateToolhelp32Snapshot: ProcessEntry32=%v", process) if process.ProcessID == pid { assert.EqualValues(t, syscall.Getppid(), process.ParentProcessID) return } } assert.Fail(t, "Snapshot not found for PID=%v", pid) } func TestNtQuerySystemProcessorPerformanceInformation(t *testing.T) { cpus, err := NtQuerySystemProcessorPerformanceInformation() if err != nil { t.Fatal(err) } assert.Len(t, cpus, runtime.NumCPU()) for i, cpu := range cpus { assert.NotZero(t, cpu.IdleTime) assert.NotZero(t, cpu.KernelTime) assert.NotZero(t, cpu.UserTime) t.Logf("CPU=%v SystemProcessorPerformanceInformation=%v", i, cpu) } } func TestNtQueryProcessBasicInformation(t *testing.T) { h, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(syscall.Getpid())) if err != nil { t.Fatal(err) } info, err := NtQueryProcessBasicInformation(h) if err != nil { t.Fatal(err) } assert.EqualValues(t, os.Getpid(), info.UniqueProcessID) assert.EqualValues(t, os.Getppid(), info.InheritedFromUniqueProcessID) t.Logf("NtQueryProcessBasicInformation: %+v", info) }
{ "pile_set_name": "Github" }
[@genType.import ("./hookExample", "default")] [@react.component] external make: (~show: bool, ~_Message: string=?) => React.element = "make"; [@genType.import "./hookExample"] [@react.component] external make2: (~show: bool, ~_Message: string=?) => React.element = "default";
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: c50d77affeb31e14c9c062c282f13fc8 NativeFormatImporter: externalObjects: {} mainObjectFileID: 0 userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
module['exports'] = function(colors) { return function(letter, i, exploded) { if (letter === ' ') return letter; switch (i%3) { case 0: return colors.red(letter); case 1: return colors.white(letter); case 2: return colors.blue(letter); } }; };
{ "pile_set_name": "Github" }
import { html, css } from 'lit-element/lit-element.js'; /** * Adds basic properties to all chart elements. * @polymer * @mixinFunction */ export const ChartPropertyMixin = function(superClass) { return class extends superClass { static get properties() { return { chart: Object, data: Object, options: Object }; } constructor() { super(); this.__hasData = false; } static get styles() { return css` :host { display: inline-block; position: relative; } #canvas { width: 100% !important; height: 100% !important; } `; } render() { return html` <div> <canvas id="canvas"></canvas> </div> `; } shouldUpdate(changes) { if (changes.has('data') || changes.has('options')) { this._configurationChanged(this.data, this.options); } if (changes.has('chart')) { this.dispatchEvent(new CustomEvent('chart-changed', { detail: this.chart, bubbles: true, composed: true })); return false; } return true; } updated() { if (this.__hasData && this.isConnected) { this._queue(); } } _configurationChanged(data) { if (!data) return; if ((this.__type === 'bubble' || data.labels) && data.datasets) { this.__hasData = true; } else { this.__hasData = false; } } } };
{ "pile_set_name": "Github" }
# This is the official list of go-github authors for copyright purposes. # # This does not necessarily list everyone who has contributed code, since in # some cases, their employer may be the copyright holder. To see the full list # of contributors, see the revision history in source control or # https://github.com/google/go-github/graphs/contributors. # # Authors who wish to be recognized in this file should add themselves (or # their employer, as appropriate). 178inaba <[email protected]> 413x <[email protected]> Abhinav Gupta <[email protected]> adrienzieba <[email protected]> Ahmed Hagy <[email protected]> Aidan Steele <[email protected]> Ainsley Chong <[email protected]> Akeda Bagus <[email protected]> Akhil Mohan <[email protected]> Alec Thomas <[email protected]> Aleks Clark <[email protected]> Alex Bramley <[email protected]> Alex Orr <[email protected]> Alexander Harkness <[email protected]> Allen Sun <[email protected]> Amey Sakhadeo <[email protected]> Anders Janmyr <[email protected]> Andreas Garnæs <https://github.com/andreas> Andrew Ryabchun <[email protected]> Andy Grunwald <[email protected]> Andy Hume <[email protected]> Andy Lindeman <[email protected]> anjanashenoy <[email protected]> Anshuman Bhartiya <[email protected]> Antoine <[email protected]> Antoine Pelisse <[email protected]> Anubha Kushwaha <[email protected]> appilon <[email protected]> Aravind <[email protected]> Arda Kuyumcu <[email protected]> Arıl Bozoluk <[email protected]> Austin Dizzy <[email protected]> Ben Batha <[email protected]> Benjamen Keroack <[email protected]> Beshr Kayali <[email protected]> Beyang Liu <[email protected]> Billy Lynch <[email protected]> Björn Häuser <[email protected]> Brad Harris <[email protected]> Brad Moylan <[email protected]> Bradley Falzon <[email protected]> Brandon Cook <[email protected]> Brian Egizi <[email protected]> Bryan Boreham <[email protected]> Cami Diez <[email protected]> Carl Johnson <[email protected]> Carlos Alexandro Becker <[email protected]> Carlos Tadeu Panato Junior <[email protected]> chandresh-pancholi <[email protected]> Charles Fenwick Elliott <[email protected]> Charlie Yan <[email protected]> Chris King <[email protected]> Chris Raborg <[email protected]> Chris Roche <[email protected]> Chris Schaefer <[email protected]> chrisforrette <[email protected]> Christian Muehlhaeuser <[email protected]> Christoph Sassenberg <[email protected]> Colin Misare <github.com/cmisare> Craig Peterson <[email protected]> Cristian Maglie <[email protected]> Daehyeok Mun <[email protected]> Daniel Leavitt <[email protected]> Daniel Nilsson <[email protected]> Daoq <[email protected]> Dave Du Cros <[email protected]> Dave Henderson <[email protected]> Dave Protasowski <[email protected]> David Deng <[email protected]> David Jannotta <[email protected]> David Ji <github.com/davidji99> David Lopez Reyes <[email protected]> Davide Zipeto <[email protected]> Dennis Webb <[email protected]> Dhi Aurrahman <[email protected]> Diego Lapiduz <[email protected]> Dmitri Shuralyov <[email protected]> dmnlk <[email protected]> Don Petersen <[email protected]> Doug Turner <[email protected]> Drew Fradette <[email protected]> Eivind <[email protected]> Eli Uriegas <[email protected]> Elliott Beach <[email protected]> Emerson Wood <[email protected]> eperm <[email protected]> Erick Fejta <[email protected]> erwinvaneyk <[email protected]> Evan Elias <[email protected]> Fabrice <[email protected]> Felix Geisendörfer <[email protected]> Filippo Valsorda <[email protected]> Florian Forster <[email protected]> Francesc Gil <[email protected]> Francis <[email protected]> Francisco Guimarães <[email protected]> Fredrik Jönsson <[email protected]> Garrett Squire <[email protected]> George Kontridze <[email protected]> Georgy Buranov <[email protected]> Glen Mailer <[email protected]> Gnahz <[email protected]> Google Inc. Grachev Mikhail <[email protected]> griffin_stewie <[email protected]> Guillaume Jacquet <[email protected]> Guz Alexander <[email protected]> Guðmundur Bjarni Ólafsson <[email protected]> Hanno Hecker <[email protected]> Hari haran <[email protected]> haya14busa <[email protected]> haya14busa <[email protected]> Huy Tr <[email protected]> huydx <[email protected]> i2bskn <[email protected]> Ioannis Georgoulas <[email protected]> Isao Jonas <[email protected]> isqua <[email protected]> Jameel Haffejee <[email protected]> James Cockbain <[email protected]> Jan Kosecki <[email protected]> Javier Campanini <[email protected]> Jens Rantil <[email protected]> Jeremy Morris <[email protected]> Jesse Newland <[email protected]> Jihoon Chung <[email protected]> Jimmi Dyson <[email protected]> Joan Saum <[email protected]> Joe Tsai <[email protected]> John Barton <[email protected]> John Engelman <[email protected]> Jordan Brockopp <[email protected]> Jordan Sussman <[email protected]> Joshua Bezaleel Abednego <[email protected]> JP Phillips <[email protected]> jpbelanger-mtl <[email protected]> Juan Basso <[email protected]> Julien Garcia Gonzalez <[email protected]> Julien Rostand <[email protected]> Junya Kono <[email protected]> Justin Abrahms <[email protected]> Jusung Lee <[email protected]> jzhoucliqr <[email protected]> kadern0 <[email protected]> Katrina Owen <[email protected]> Kautilya Tripathi <[email protected]> Keita Urashima <[email protected]> Kevin Burke <[email protected]> Konrad Malawski <[email protected]> Kookheon Kwon <[email protected]> Krzysztof Kowalczyk <[email protected]> Kshitij Saraogi <[email protected]> kyokomi <[email protected]> Laurent Verdoïa <[email protected]> Liam Galvin <[email protected]> Lovro Mažgon <[email protected]> Lucas Alcantara <[email protected]> Luke Evers <[email protected]> Luke Kysow <[email protected]> Luke Roberts <[email protected]> Luke Young <[email protected]> lynn [they] <[email protected]> Maksim Zhylinski <[email protected]> Mark Tareshawty <[email protected]> Martin-Louis Bright <[email protected]> Martins Sipenko <[email protected]> Marwan Sulaiman <[email protected]> Masayuki Izumi <[email protected]> Mat Geist <[email protected]> Matt <[email protected]> Matt Brender <[email protected]> Matt Gaunt <[email protected]> Matt Landis <[email protected]> Maxime Bury <[email protected]> Michael Spiegel <[email protected]> Michael Tiller <[email protected]> Michał Glapa <[email protected]> Nadav Kaner <[email protected]> Nathan VanBenschoten <[email protected]> Navaneeth Suresh <[email protected]> Neil O'Toole <[email protected]> Nick Miyake <[email protected]> Nick Spragg <[email protected]> Nikhita Raghunath <[email protected]> Noah Zoschke <[email protected]> ns-cweber <[email protected]> Ole Orhagen <[email protected]> Oleg Kovalov <[email protected]> Ondřej Kupka <[email protected]> Palash Nigam <[email protected]> Panagiotis Moustafellos <[email protected]> Parham Alvani <[email protected]> Parker Moore <[email protected]> parkhyukjun89 <[email protected]> Patrick DeVivo <[email protected]> Patrick Marabeas <[email protected]> Pavel Shtanko <[email protected]> Pete Wagner <[email protected]> Petr Shevtsov <[email protected]> Pierre Carrier <[email protected]> Piotr Zurek <[email protected]> Qais Patankar <[email protected]> Quang Le Hong <[email protected]> Quentin Leffray <[email protected]> Quinn Slack <[email protected]> Rackspace US, Inc. Radek Simko <[email protected]> Radliński Ignacy <[email protected]> Rajat Jindal <[email protected]> Rajendra arora <[email protected]> Ranbir Singh <[email protected]> Ravi Shekhar Jethani <[email protected]> RaviTeja Pothana <[email protected]> rc1140 <[email protected]> Red Hat, Inc. Ricco Førgaard <[email protected]> Rob Figueiredo <[email protected]> Rohit Upadhyay <[email protected]> Ronak Jain <[email protected]> Ruben Vereecken <[email protected]> Ryan Leung <[email protected]> Ryan Lower <[email protected]> Ryo Nakao <[email protected]> Safwan Olaimat <[email protected]> Sahil Dua <[email protected]> saisi <[email protected]> Sam Minnée <[email protected]> Sandeep Sukhani <[email protected]> Sander Knape <[email protected]> Sander van Harmelen <[email protected]> Sanket Payghan <[email protected]> Sarasa Kisaragi <[email protected]> Sean Wang <[email protected]> Sebastian Mandrean <[email protected]> Sebastian Mæland Pedersen <[email protected]> Sergey Romanov <[email protected]> Sergio Garcia <[email protected]> Sevki <[email protected]> Shagun Khemka <[email protected]> shakeelrao <[email protected]> Shawn Catanzarite <[email protected]> Shawn Smith <[email protected]> Shibasis Patel <[email protected]> Shrikrishna Singh <[email protected]> sona-tar <[email protected]> SoundCloud, Ltd. Sridhar Mocherla <[email protected]> SriVignessh Pss <[email protected]> Stefan Sedich <[email protected]> Stian Eikeland <[email protected]> Suhaib Mujahid <[email protected]> Szymon Kodrebski <[email protected]> Takayuki Watanabe <[email protected]> Taketoshi Fujiwara <[email protected]> Tasya Aditya Rukmana <[email protected]> Thomas Bruyelle <[email protected]> Timothée Peignier <[email protected]> tkhandel <[email protected]> Trey Tacon <[email protected]> ttacon <[email protected]> Vaibhav Singh <[email protected]> Varadarajan Aravamudhan <[email protected]> Victor Castell <[email protected]> Victor Vrantchan <[email protected]> vikkyomkar <[email protected]> Vlad Ungureanu <[email protected]> Wasim Thabraze <[email protected]> Will Maier <[email protected]> Willem D'Haeseleer <[email protected]> William Bailey <[email protected]> William Cooke <[email protected]> xibz <[email protected]> Yann Malet <[email protected]> Yannick Utard <[email protected]> Yicheng Qin <[email protected]> Yosuke Akatsuka <[email protected]> Yumikiyo Osanai <[email protected]> Zach Latta <[email protected]>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:info="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/kg_common_background" android:fillViewport="true" android:scrollbars="none" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <LinearLayout android:id="@+id/kg_layout_bind_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <include layout="@layout/kg_layout_account_security_head" /> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/kg_common_background" android:gravity="center_vertical" android:paddingLeft="10dp" android:text="@string/kg_login_security" android:textColor="#666666" android:textSize="16sp" /> <com.kugou.game.sdk.ui.widget.UserInfoView android:id="@+id/kg_item_security_phone" android:layout_width="match_parent" android:layout_height="80dp" info:item_divider_visible="true" info:item_title="@string/kg_security_phone" info:item_title_detail="@string/kg_security_phone_tip" /> <com.kugou.game.sdk.ui.widget.UserInfoView android:id="@+id/kg_item_security_email" android:layout_width="match_parent" android:layout_height="80dp" info:item_divider_visible="true" info:item_title="@string/kg_security_email" info:item_title_detail="@string/kg_security_email_tip" /> <com.kugou.game.sdk.ui.widget.UserInfoView android:id="@+id/kg_item_security_question" android:layout_width="match_parent" android:layout_height="80dp" info:item_divider_visible="true" info:item_title="@string/kg_security_question" info:item_title_detail="@string/kg_security_question_tip" /> <com.kugou.game.sdk.ui.widget.UserInfoView android:id="@+id/kg_item_modify_psd" android:layout_width="match_parent" android:layout_height="80dp" info:item_divider_visible="true" info:item_title="@string/kg_modify_psd" /> <TextView android:layout_width="match_parent" android:layout_height="50dp" android:background="@color/kg_common_background" android:gravity="center_vertical" android:paddingLeft="10dp" android:text="@string/kg_pay_security" android:textColor="#666666" android:textSize="16sp" /> <com.kugou.game.sdk.ui.widget.UserInfoView android:id="@+id/kg_item_pay_psd" android:layout_width="match_parent" android:layout_height="80dp" android:layout_marginBottom="5dp" info:item_divider_visible="true" info:item_title="@string/kg_security_pay_psd" info:item_title_detail="@string/kg_security_pay_psd_tip" /> </LinearLayout> <com.kugou.game.sdk.ui.widget.TipsLayout android:id="@+id/kg_loading" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" android:visibility="visible" /> </LinearLayout> </ScrollView>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!--ShapeButton--> <declare-styleable name="ShapeTextView"> <!--Button圆角--> <attr name="shapeRadius" format="dimension"></attr> <!--边框宽度--> <attr name="shapeStrokeWidth" format="dimension"></attr> <!--边框颜色--> <attr name="shapeStrokeColor" format="color"></attr> <!--背景颜色--> <attr name="shapeBackgroundColor" format="color"></attr> <!--背景按下的颜色--> <attr name="shapeBackgroundSelectorColor" format="color"></attr> </declare-styleable> </resources>
{ "pile_set_name": "Github" }
open Revery_Core; open TestFramework; describe("Environment", ({test, _}) => { test("executingDirectory", _ => test( "validate we can load a file adjacent to the executable", ({expect, _}) => { expect.bool( Sys.file_exists(Environment.executingDirectory ++ "test-asset.txt"), ). toBeTrue() }) ); test("userLocale", ({expect, _}) => { expect.equal(~equals=(!=), Environment.userLocale, "") }); });
{ "pile_set_name": "Github" }
/* * * Copyright 2017 gRPC authors. * * 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 backoff implement the backoff strategy for gRPC. // // This is kept in internal until the gRPC project decides whether or not to // allow alternative backoff strategies. package backoff import ( "time" "google.golang.org/grpc/internal/grpcrand" ) // Strategy defines the methodology for backing off after a grpc connection // failure. // type Strategy interface { // Backoff returns the amount of time to wait before the next retry given // the number of consecutive failures. Backoff(retries int) time.Duration } const ( // baseDelay is the amount of time to wait before retrying after the first // failure. baseDelay = 1.0 * time.Second // factor is applied to the backoff after each retry. factor = 1.6 // jitter provides a range to randomize backoff delays. jitter = 0.2 ) // Exponential implements exponential backoff algorithm as defined in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. type Exponential struct { // MaxDelay is the upper bound of backoff delay. MaxDelay time.Duration } // Backoff returns the amount of time to wait before the next retry given the // number of retries. func (bc Exponential) Backoff(retries int) time.Duration { if retries == 0 { return baseDelay } backoff, max := float64(baseDelay), float64(bc.MaxDelay) for backoff < max && retries > 0 { backoff *= factor retries-- } if backoff > max { backoff = max } // Randomize backoff delays so that if a cluster of requests start at // the same time, they won't operate in lockstep. backoff *= 1 + jitter*(grpcrand.Float64()*2-1) if backoff < 0 { return 0 } return time.Duration(backoff) }
{ "pile_set_name": "Github" }
/* Copyright (c) 2013 yvt This file is part of OpenSpades. OpenSpades 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. OpenSpades 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 OpenSpades. If not, see <http://www.gnu.org/licenses/>. */ uniform sampler2D blurTexture1; uniform sampler2D dustTexture; uniform sampler2D inputTexture; uniform sampler2D noiseTexture; varying vec2 texCoord; varying vec2 dustTexCoord; varying vec4 noiseTexCoord; void main() { // dust filter texture vec3 dust1 = texture2D(dustTexture, dustTexCoord).xyz; // linearize dust1 *= dust1; // blurred texture (already linearized?) vec3 blur1 = texture2D(blurTexture1, texCoord).xyz; vec3 sum = dust1 * blur1; vec3 final = texture2D(inputTexture, texCoord).xyz; #if !LINEAR_FRAMEBUFFER final *= final; #endif final *= 0.95; final += sum * 2.0; // add grain float grain = texture2D(noiseTexture, noiseTexCoord.xy).x; grain += texture2D(noiseTexture, noiseTexCoord.zw).x; grain = fract(grain) - 0.5; final += grain * 0.003; // non-linearize #if !LINEAR_FRAMEBUFFER final = sqrt(max(final, 0.)); #else final = max(final, 0.); #endif gl_FragColor = vec4(final, 1.); }
{ "pile_set_name": "Github" }
#!/usr/bin/env bash # 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. # The following environment variables must be set, ordinarily by `docker run -e` arguments: envvars=( REMAP_PATH ) for v in $envvars do if [[ -z $$v ]]; then echo "$v is unset"; exit 1; fi done [ ! -z $PORT ] || PORT=80 [ ! -z $HTTPS_PORT ] || HTTPS_PORT=443 [ ! -z $CACHE_BYTES ] || CACHE_BYTES=100000000 # 100mb start() { service grove start exec tail -f /var/log/grove/error.log } init() { cat > "/etc/grove/grove.cfg" <<- ENDOFMESSAGE { "rfc_compliant": false, "port": $PORT, "https_port": $HTTPS_PORT, "cache_size_bytes": $CACHE_BYTES, "remap_rules_file": "/etc/grove/remap.json", "concurrent_rule_requests": 100, "connection_close": false, "interface_name": "bond0", "cert_file": "/etc/grove/cert.pem", "key_file": "/etc/grove/key.pem", "log_location_error": "/var/log/grove/error.log", "log_location_warning": "/var/log/grove/error.log", "log_location_info": "null", "log_location_debug": "null", "log_location_event": "/opt/trafficserver/var/log/trafficserver/custom_ats_2.log", "parent_request_timeout_ms": 10000, "parent_request_keep_alive_ms": 10000, "parent_request_max_idle_connections": 10000, "parent_request_idle_connection_timeout_ms": 10000, "server_read_timeout_ms": 5000, "server_write_timeout_ms": 5000, "server_idle_timeout_ms": 5000 } ENDOFMESSAGE # TODO add Traffic Ops uri+user+pass+hostname as an option, rather than remap file if [[ ! -z $REMAP_PATH ]]; then cp $REMAP_PATH /etc/grove/remap.json fi mkdir -p /opt/trafficserver/var/log/trafficserver mkdir -p /var/log/grove/ touch /var/log/grove/error.log openssl req -newkey rsa:2048 -nodes -keyout /etc/grove/key.pem -x509 -days 3650 -out /etc/grove/cert.pem -subj "/C=US/ST=Colorado/L=Denver/O=MyCompany/CN=cdn.example.net" # TODO add server to Traffic Ops, with env vars echo "INITIALIZED=1" >> /etc/environment } source /etc/environment if [ -z "$INITIALIZED" ]; then init; fi start
{ "pile_set_name": "Github" }
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.box = "ubuntu/trusty64" config.vm.provision "shell", inline: <<-SHELL apt-get -y update # Basic essential toolkit apt-get -y install wget apt-get -y install build-essential apt-get -y install python-dev apt-get -y install python-pip easy_install -U pip echo "[DroneKit]: Installing JDK 7" if [[ -z `which 'java'` ]]; then apt-get -y install openjdk-7-jre-headless if grep -v JAVA_HOME "/etc/environment"; then echo "JAVA_HOME='/usr/lib/jvm/java-7-openjdk-amd64/'" >> /etc/environment fi else echo "[DroneKit]: Already installed JDK 7" fi source /etc/environment echo "[DroneKit]: Installing gradle" if [[ -z `which 'gradle'` ]]; then add-apt-repository ppa:cwchien/gradle apt-get -y update apt-get -y install gradle-2.2.1 else echo "[DroneKit]: Already installed gradle" fi echo "[DroneKit]: Android SDK" if [[ -z `which 'ubuntu-sdk'` ]]; then wget http://dl.google.com/android/android-sdk_r24.1.2-linux.tgz tar -zxvf android-sdk_r24.1.2-linux.tgz export ANDROID_HOME=$HOME/android-sdk-linux echo "`PATH DEFAULT=${PATH}:/home/vagrant/android-sdk-linux/tools`" >> ~/.bashrc echo "`PATH DEFAULT=${PATH}:/home/vagrant/android-sdk-linux/platform-tools`" >> ~/.bashrc cd $ANDROID_HOME #./tools/android update -s --no-gui ( sleep 5 && while [ 1 ]; do sleep 1; echo y; done ) | ./tools/android update sdk --no-ui --filter platform-tool,android-21 cd /home/vagrant else echo "[DroneKit]: Already installed Android SDK" fi echo "[DroneKit]: Sphinx" pip install sphinx pip install sphinx_3dr_theme pip install -U sphinx_3dr_theme cd /vagrant echo "[DroneKit]: Java Docs" # The javadocs will be generated in the '<top_directory>/ClientLib/mobile/build/docs/javadoc' directory. ./gradlew :ClientLib:mobile:clean :ClientLib:mobile:androidJavadocs #echo "[DroneKit]: Sphinx Docs " cd /vagrant/doc make clean make html SHELL end
{ "pile_set_name": "Github" }
# Resistor Color Duo If you want to build something using a Raspberry Pi, you'll probably use _resistors_. For this exercise, you need to know two things about them: * Each resistor has a resistance value. * Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read. To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values. Each band has a position and a numeric value. For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15. In this exercise you are going to create a helpful program so that you don't have to remember the values of the bands. The program will take color names as input and output a two digit number, even if the input is more than two colors! The band colors are encoded as follows: - Black: 0 - Brown: 1 - Red: 2 - Orange: 3 - Yellow: 4 - Green: 5 - Blue: 6 - Violet: 7 - Grey: 8 - White: 9 From the example above: brown-green should return 15 brown-green-violet should return 15 too, ignoring the third color. ## Setup Go through the setup instructions for Kotlin to install the necessary dependencies: [https://exercism.io/tracks/kotlin/installation](https://exercism.io/tracks/kotlin/installation) ## Making the test suite pass Execute the tests with: ```bash $ ./gradlew test ``` > Use `gradlew.bat` if you're on Windows In the test suites all tests but the first have been skipped. Once you get a test passing, you can enable the next one by removing the `@Ignore` annotation. ## Source Maud de Vries, Erik Schierboom [https://github.com/exercism/problem-specifications/issues/1464](https://github.com/exercism/problem-specifications/issues/1464) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise.
{ "pile_set_name": "Github" }
group("cpu") { deps = [ "//src/cpu/colun", "//src/cpu/control_tester", "//src/cpu/hamaji", "//src/cpu/inosendo", "//src/cpu/kantoku", "//src/cpu/mayah", "//src/cpu/munetoshi", "//src/cpu/peria", "//src/cpu/ryumas", "//src/cpu/sample", "//src/cpu/sample_beam", "//src/cpu/sample_rensa", "//src/cpu/sample_suicide", "//src/cpu/takapt", "//src/cpu/test_lockit", "//src/cpu/tzik", "//src/cpu/yamaguchi", "//src/cpu/yuricat", ] }
{ "pile_set_name": "Github" }
/** * @callback Phaser.Types.Cameras.Scene2D.CameraPanCallback * @since 3.5.0 * * @param {Phaser.Cameras.Scene2D.Camera} camera - The camera on which the effect is running. * @param {number} progress - The progress of the effect. A value between 0 and 1. * @param {number} x - The Camera's new scrollX coordinate. * @param {number} y - The Camera's new scrollY coordinate. */
{ "pile_set_name": "Github" }
/* * * Copyright (c) 2013,2019 AT&T Knowledge Ventures * SPDX-License-Identifier: MIT */ package com.att.research.xacml.std.pip; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import com.att.research.xacml.api.Attribute; import com.att.research.xacml.api.AttributeValue; import com.att.research.xacml.api.Status; import com.att.research.xacml.api.pip.PIPException; import com.att.research.xacml.api.pip.PIPRequest; import com.att.research.xacml.api.pip.PIPResponse; import com.att.research.xacml.std.StdAttribute; import com.att.research.xacml.std.StdMutableAttribute; import com.att.research.xacml.std.StdStatus; import com.att.research.xacml.util.Wrapper; /** * Immutable implementation of the {@link com.att.research.xacml.api.pip.PIPResponse} interface. * * @author Christopher A. Rath * @version $Revision$ */ public class StdPIPResponse extends Wrapper<PIPResponse> implements PIPResponse { public static final PIPResponse PIP_RESPONSE_EMPTY = new StdPIPResponse(StdStatus.STATUS_OK); /** * Creates a new immutable <code>StdPIPResponse</code> that wraps the given {@link com.att.research.xacml.api.pip.PIPResponse}. * * @param wrappedObjectIn the <code>PIPResponse</code> to wrap. */ public StdPIPResponse(PIPResponse wrappedObjectIn) { super(wrappedObjectIn); } /** * Creates a new <code>StdPIPResponse</code> with the given {@link com.att.research.xacml.api.Status}. * * @param status the <code>Status</code> for the new <code>StdPIPResponse</code> */ public StdPIPResponse(Status status) { this(new StdMutablePIPResponse(status)); } /** * Creates a new <code>StdPIPResponse</code> with an OK {@link com.att.research.xacml.api.Status} and a * single {@link com.att.research.xacml.api.Attribute}. * * @param attribute the <code>Attribute</code> for the new <code>StdPIPResponse</code>. */ public StdPIPResponse(Attribute attribute) { this(new StdMutablePIPResponse(attribute)); } /** * Creates a new <code>StdPIPResponse</code> with an OK {@link com.att.research.xacml.api.Status} and a copy * of the given <code>Collection</code> of {@link com.att.research.xacml.api.Attribute}s. * * @param attributes the <code>Attribute</code>s for the new <code>StdPIPResponse</code>. */ public StdPIPResponse(Collection<Attribute> attributes) { this(new StdMutablePIPResponse(attributes)); } @Override public Status getStatus() { return this.getWrappedObject().getStatus(); } @Override public Collection<Attribute> getAttributes() { return this.getWrappedObject().getAttributes(); } /** * Determines if the given {@link com.att.research.xacml.api.pip.PIPRequest} matches the given {@link com.att.research.xacml.api.Attribute} by * comparing the category, attribute id, and if not null in the <code>PIPRequest</code>, the issuer. * * @param pipRequest the <code>PIPRequest</code> to compare against * @param attribute the <code>Attribute</code> to compare to * @return true if the <code>Attribute</code> matches the <code>PIPRequest</code> else false */ public static boolean matches(PIPRequest pipRequest, Attribute attribute) { if (!pipRequest.getCategory().equals(attribute.getCategory())) { return false; } if (!pipRequest.getAttributeId().equals(attribute.getAttributeId())) { return false; } if (pipRequest.getIssuer() != null && !pipRequest.getIssuer().equals(attribute.getIssuer())) { return false; } return true; } /** * Gets the subset of the {@link com.att.research.xacml.api.AttributeValue}s from the given <code>Collection</code> whose data type * matches the data type in the given {@link com.att.research.xacml.api.pip.PIPRequest}. * * @param pipRequest the <code>PIPRequest</code> to compare against * @param listAttributeValues the <code>Collection</code> of <code>AttributeValue</code>s to select from * @return a <code>Collection</code> of matching <code>AttributeValue</code>s or null if there are no matches */ public static Collection<AttributeValue<?>> matchingValues(PIPRequest pipRequest, Collection<AttributeValue<?>> listAttributeValues) { if (listAttributeValues.size() == 0) { return listAttributeValues; } /* * See if all of the values match the requested data type */ boolean allMatch = true; for (Iterator<AttributeValue<?>> iterAttributeValues = listAttributeValues.iterator() ; allMatch && iterAttributeValues.hasNext() ; ) { AttributeValue<?> attributeValue = iterAttributeValues.next(); allMatch = attributeValue.getDataTypeId().equals(pipRequest.getDataTypeId()); } if (allMatch) { return listAttributeValues; } /* * If there was only one, return a null list */ if (listAttributeValues.size() == 1) { return null; } List<AttributeValue<?>> listAttributeValuesMatching = new ArrayList<AttributeValue<?>>(); for (Iterator<AttributeValue<?>> iterAttributeValues = listAttributeValues.iterator() ; iterAttributeValues.hasNext() ;) { AttributeValue<?> attributeValue = iterAttributeValues.next(); if (attributeValue.getDataTypeId().equals(pipRequest.getDataTypeId())) { listAttributeValuesMatching.add(attributeValue); } } if (listAttributeValuesMatching.isEmpty()) { return null; } else { return listAttributeValuesMatching; } } /** * Returns a {@link com.att.research.xacml.api.pip.PIPResponse} that only contains the {@link com.att.research.xacml.api.Attribute}s * that match the given {@link com.att.research.xacml.api.pip.PIPRequest} with {@link com.att.research.xacml.api.AttributeValue}s that * match the requested data type. * * @param pipRequest * @param pipResponse * @return PIPResponse * @throws PIPException */ public static PIPResponse getMatchingResponse(PIPRequest pipRequest, PIPResponse pipResponse) throws PIPException { /* * Error responses should not contain any attributes, so just return the error response as is. Likewise for empty responses */ if (!pipResponse.getStatus().isOk() || pipResponse.getAttributes().isEmpty()) { return pipResponse; } /* * See if the response is simple */ if (pipResponse.isSimple()) { /* * Get the one Attribute and verify that it matches the request, and that the data type of its values matches the request */ Attribute attributeResponse = pipResponse.getAttributes().iterator().next(); if (matches(pipRequest, attributeResponse)) { Collection<AttributeValue<?>> attributeValues = attributeResponse.getValues(); if (attributeValues == null || attributeValues.isEmpty()) { return pipResponse; } else { AttributeValue<?> attributeValueResponse = attributeResponse.getValues().iterator().next(); if (attributeValueResponse.getDataTypeId().equals(pipRequest.getDataTypeId())) { return pipResponse; } else { return PIP_RESPONSE_EMPTY; } } } else { return PIP_RESPONSE_EMPTY; } } else { /* * Iterate over the Attributes and just get the ones that match and collapse any matching AttributeValues */ StdMutableAttribute attributeMatch = null; Iterator<Attribute> iterAttributesResponse = pipResponse.getAttributes().iterator(); while (iterAttributesResponse.hasNext()) { Attribute attributeResponse = iterAttributesResponse.next(); if (matches(pipRequest, attributeResponse)) { /* * Get subset of the matching attribute values */ Collection<AttributeValue<?>> listAttributeValuesMatch = matchingValues(pipRequest, attributeResponse.getValues()); if (listAttributeValuesMatch != null && listAttributeValuesMatch.size() > 0) { if (attributeMatch == null) { attributeMatch = new StdMutableAttribute(pipRequest.getCategory(), pipRequest.getAttributeId(), listAttributeValuesMatch, pipRequest.getIssuer(), false); } else { attributeMatch.addValues(listAttributeValuesMatch); } } } } if (attributeMatch == null) { return PIP_RESPONSE_EMPTY; } else { return new StdPIPResponse(attributeMatch); } } } /** * Splits an Attribute that may contain multiple data types into a list of Attributes, each with only one data type * @param attribute * @return */ private static List<Attribute> simplifyAttribute(Attribute attribute) { List<Attribute> listAttributes = new ArrayList<>(); if (attribute.getValues() == null || attribute.getValues().size() <= 1) { listAttributes.add(attribute); } else { for (AttributeValue<?> attributeValue : attribute.getValues()) { listAttributes.add(new StdAttribute(attribute.getCategory(), attribute.getAttributeId(), attributeValue, attribute.getIssuer(), attribute.getIncludeInResults())); } } return listAttributes; } /** * Takes a list of simple Attributes and collapses attributes with the same category, id, value data type, and issuer into * a single Attribute and returns the list of collapsed Attributes. * * @param listAttributes * @return */ private static Collection<? extends Attribute> collapseAttributes(List<Attribute> listAttributes) { if (listAttributes.size() <= 0) { return listAttributes; } Map<PIPRequest, StdMutableAttribute> map = new HashMap<>(); for (Attribute attribute : listAttributes) { PIPRequest pipRequest = new StdPIPRequest(attribute); if (map.containsKey(pipRequest)) { StdMutableAttribute mutableAttribute = map.get(pipRequest); mutableAttribute.addValues(attribute.getValues()); } else { map.put(pipRequest, new StdMutableAttribute(attribute)); } } if (map.size() == 0) { return null; } else { return map.values(); } } /** * Takes a {@link com.att.research.xacml.api.pip.PIPResponse} that may contain {@link com.att.research.xacml.api.Attribute}s, with multiple * identifiers, each of which may contain multiple {@link com.att.research.xacml.api.AttributeValue}s with different data types and creates a collection of * simple <code>PIPResponse</code>s that contain a single <code>Attribute</code> with <code>AttributeValue</code>s of one data type. * * @param pipResponse the <code>PIPResponse</code> to split * @return a <code>Collection</code> of simple <code>PIPResponse</code>s * @throws PIPException if there is an error splitting the response */ public static Map<PIPRequest,PIPResponse> splitResponse(PIPResponse pipResponse) throws PIPException { Map<PIPRequest,PIPResponse> map = new HashMap<>(); if (!pipResponse.getStatus().isOk() || pipResponse.isSimple()) { map.put(new StdPIPRequest(pipResponse.getAttributes().iterator().next()), pipResponse); } else { List<Attribute> listAllAttributesSimple = new ArrayList<>(); for (Iterator<Attribute> iterAttributes = pipResponse.getAttributes().iterator() ; iterAttributes.hasNext() ; ) { Attribute attribute = iterAttributes.next(); List<Attribute> listAttributesSplit = simplifyAttribute(attribute); if (listAttributesSplit != null && listAttributesSplit.size() > 0) { listAllAttributesSimple.addAll(listAttributesSplit); } } if (listAllAttributesSimple.size() > 0) { Collection<? extends Attribute> listAttributesCollapsed = collapseAttributes(listAllAttributesSimple); for (Attribute attributeCollapsed : listAttributesCollapsed) { map.put(new StdPIPRequest(attributeCollapsed), new StdPIPResponse(attributeCollapsed)); } } } return map; } @Override public boolean isSimple() { return this.getWrappedObject().isSimple(); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("{"); boolean needsComma = false; if (this.getStatus() != null) { stringBuilder.append(this.getStatus().toString()); needsComma = true; } if (! this.getAttributes().isEmpty()) { if (needsComma) { stringBuilder.append(","); } needsComma = false; } stringBuilder.append("["); for (Attribute attribute : this.getAttributes()) { if (needsComma) { stringBuilder.append(","); } stringBuilder.append(attribute.toString()); needsComma = true; } stringBuilder.append("]"); stringBuilder.append('}'); return stringBuilder.toString(); } }
{ "pile_set_name": "Github" }
package io.onedev.server.web.page.project.blob.render.renderers.symbollink; import org.apache.wicket.Component; import io.onedev.server.web.PrioritizedComponentRenderer; import io.onedev.server.web.page.project.blob.render.BlobRenderContext; import io.onedev.server.web.page.project.blob.render.BlobRendererContribution; import io.onedev.server.web.page.project.blob.render.BlobRenderContext.Mode; public class SymbolLinkRendererProvider implements BlobRendererContribution { private static final long serialVersionUID = 1L; @Override public PrioritizedComponentRenderer getRenderer(BlobRenderContext context) { if (context.getMode() == Mode.VIEW && context.getBlobIdent().isSymbolLink()) { return new PrioritizedComponentRenderer() { private static final long serialVersionUID = 1L; @Override public Component render(String componentId) { return new SymbolLinkPanel(componentId, context); } @Override public int getPriority() { return 0; } }; } else { return null; } } }
{ "pile_set_name": "Github" }
#ifndef __AMF_H__ #define __AMF_H__ /* * Copyright (C) 2005-2008 Team XBMC * http://www.xbmc.org * Copyright (C) 2008-2009 Andrej Stepanchuk * Copyright (C) 2009-2010 Howard Chu * * This file is part of librtmp. * * librtmp 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, * or (at your option) any later version. * * librtmp 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 Lesser General Public License * along with librtmp see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/lgpl.html */ #include <stdint.h> #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif #ifdef __cplusplus extern "C" { #endif typedef enum { AMF_NUMBER = 0, AMF_BOOLEAN, AMF_STRING, AMF_OBJECT, AMF_MOVIECLIP, /* reserved, not used */ AMF_NULL, AMF_UNDEFINED, AMF_REFERENCE, AMF_ECMA_ARRAY, AMF_OBJECT_END, AMF_STRICT_ARRAY, AMF_DATE, AMF_LONG_STRING, AMF_UNSUPPORTED, AMF_RECORDSET, /* reserved, not used */ AMF_XML_DOC, AMF_TYPED_OBJECT, AMF_AVMPLUS, /* switch to AMF3 */ AMF_INVALID = 0xff } AMFDataType; typedef enum { AMF3_UNDEFINED = 0, AMF3_NULL, AMF3_FALSE, AMF3_TRUE, AMF3_INTEGER, AMF3_DOUBLE, AMF3_STRING, AMF3_XML_DOC, AMF3_DATE, AMF3_ARRAY, AMF3_OBJECT, AMF3_XML, AMF3_BYTE_ARRAY } AMF3DataType; typedef struct AVal { char *av_val; int av_len; } AVal; #define AVC(str) {str,sizeof(str)-1} #define AVMATCH(a1,a2) ((a1)->av_len == (a2)->av_len && !memcmp((a1)->av_val,(a2)->av_val,(a1)->av_len)) struct AMFObjectProperty; typedef struct AMFObject { int o_num; struct AMFObjectProperty *o_props; } AMFObject; typedef struct AMFObjectProperty { AVal p_name; AMFDataType p_type; union { double p_number; AVal p_aval; AMFObject p_object; } p_vu; int16_t p_UTCoffset; } AMFObjectProperty; char *AMF_EncodeString(char *output, char *outend, const AVal * str); char *AMF_EncodeNumber(char *output, char *outend, double dVal); char *AMF_EncodeInt16(char *output, char *outend, short nVal); char *AMF_EncodeInt24(char *output, char *outend, int nVal); char *AMF_EncodeInt32(char *output, char *outend, int nVal); char *AMF_EncodeBoolean(char *output, char *outend, int bVal); /* Shortcuts for AMFProp_Encode */ char *AMF_EncodeNamedString(char *output, char *outend, const AVal * name, const AVal * value); char *AMF_EncodeNamedNumber(char *output, char *outend, const AVal * name, double dVal); char *AMF_EncodeNamedBoolean(char *output, char *outend, const AVal * name, int bVal); unsigned short AMF_DecodeInt16(const char *data); unsigned int AMF_DecodeInt24(const char *data); unsigned int AMF_DecodeInt32(const char *data); void AMF_DecodeString(const char *data, AVal * str); void AMF_DecodeLongString(const char *data, AVal * str); int AMF_DecodeBoolean(const char *data); double AMF_DecodeNumber(const char *data); char *AMF_Encode(AMFObject * obj, char *pBuffer, char *pBufEnd); char *AMF_EncodeEcmaArray(AMFObject *obj, char *pBuffer, char *pBufEnd); char *AMF_EncodeArray(AMFObject *obj, char *pBuffer, char *pBufEnd); int AMF_Decode(AMFObject * obj, const char *pBuffer, int nSize, int bDecodeName); int AMF_DecodeArray(AMFObject * obj, const char *pBuffer, int nSize, int nArrayLen, int bDecodeName); int AMF3_Decode(AMFObject * obj, const char *pBuffer, int nSize, int bDecodeName); void AMF_Dump(AMFObject * obj); void AMF_Reset(AMFObject * obj); void AMF_AddProp(AMFObject * obj, const AMFObjectProperty * prop); int AMF_CountProp(AMFObject * obj); AMFObjectProperty *AMF_GetProp(AMFObject * obj, const AVal * name, int nIndex); AMFDataType AMFProp_GetType(AMFObjectProperty * prop); void AMFProp_SetNumber(AMFObjectProperty * prop, double dval); void AMFProp_SetBoolean(AMFObjectProperty * prop, int bflag); void AMFProp_SetString(AMFObjectProperty * prop, AVal * str); void AMFProp_SetObject(AMFObjectProperty * prop, AMFObject * obj); void AMFProp_GetName(AMFObjectProperty * prop, AVal * name); void AMFProp_SetName(AMFObjectProperty * prop, AVal * name); double AMFProp_GetNumber(AMFObjectProperty * prop); int AMFProp_GetBoolean(AMFObjectProperty * prop); void AMFProp_GetString(AMFObjectProperty * prop, AVal * str); void AMFProp_GetObject(AMFObjectProperty * prop, AMFObject * obj); int AMFProp_IsValid(AMFObjectProperty * prop); char *AMFProp_Encode(AMFObjectProperty * prop, char *pBuffer, char *pBufEnd); int AMF3Prop_Decode(AMFObjectProperty * prop, const char *pBuffer, int nSize, int bDecodeName); int AMFProp_Decode(AMFObjectProperty * prop, const char *pBuffer, int nSize, int bDecodeName); void AMFProp_Dump(AMFObjectProperty * prop); void AMFProp_Reset(AMFObjectProperty * prop); typedef struct AMF3ClassDef { AVal cd_name; char cd_externalizable; char cd_dynamic; int cd_num; AVal *cd_props; } AMF3ClassDef; void AMF3CD_AddProp(AMF3ClassDef * cd, AVal * prop); AVal *AMF3CD_GetProp(AMF3ClassDef * cd, int idx); #ifdef __cplusplus } #endif #endif /* __AMF_H__ */
{ "pile_set_name": "Github" }
__author__ = "bt3" This is the classic "you have 8 balls/coins, which are the same weight, except for one which is slightly heavier than the others. You also have an old-style balance. What is the fewest number of weighings to find the heavy coin/ball? Answer: 2! You need to use every information available: Weight 3 x 3 balls/coins. If they weight the same: weight the 2 balls/coins left outside. Else, measure 2 of the 3 heavier balls/coins.
{ "pile_set_name": "Github" }
tests/qapi-schema/escape-too-big.json:3:14: For now, \u escape only supports non-zero values up to \u007f
{ "pile_set_name": "Github" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: | If Result.type is break and Result.target is in the current label set, return (normal, Result.value, empty) es5id: 12.11_A1_T3 description: Using case with null, NaN, Infinity ---*/ function SwitchTest(value){ var result = 0; switch(value) { case 0: result += 2; case 1: result += 4; break; case 2: result += 8; case 3: result += 16; default: result += 32; break; case null: result += 64; case NaN: result += 128; break; case Infinity: result += 256; case 2+3: result += 512; break; case undefined: result += 1024; } return result; } if(!(SwitchTest(0) === 6)){ $ERROR("#1: SwitchTest(0) === 6. Actual: SwitchTest(0) ==="+ SwitchTest(0) ); } if(!(SwitchTest(1) === 4)){ $ERROR("#2: SwitchTest(1) === 4. Actual: SwitchTest(1) ==="+ SwitchTest(1) ); } if(!(SwitchTest(2) === 56)){ $ERROR("#3: SwitchTest(2) === 56. Actual: SwitchTest(2) ==="+ SwitchTest(2) ); } if(!(SwitchTest(3) === 48)){ $ERROR("#4: SwitchTest(3) === 48. Actual: SwitchTest(3) ==="+ SwitchTest(3) ); } if(!(SwitchTest(4) === 32)){ $ERROR("#5: SwitchTest(4) === 32. Actual: SwitchTest(4) ==="+ SwitchTest(4) ); } if(!(SwitchTest(5) === 512)){ $ERROR("#5: SwitchTest(5) === 512. Actual: SwitchTest(5) ==="+ SwitchTest(5) ); } if(!(SwitchTest(true) === 32)){ $ERROR("#6: SwitchTest(true) === 32. Actual: SwitchTest(true) ==="+ SwitchTest(true) ); } if(!(SwitchTest(false) === 32)){ $ERROR("#7: SwitchTest(false) === 32. Actual: SwitchTest(false) ==="+ SwitchTest(false) ); } if(!(SwitchTest(null) === 192)){ $ERROR("#8: SwitchTest(null) === 192. Actual: SwitchTest(null) ==="+ SwitchTest(null) ); } if(!(SwitchTest(void 0) === 1024)){ $ERROR("#9: SwitchTest(void 0) === 1024. Actual: SwitchTest(void 0) ==="+ SwitchTest(void 0) ); } if(!(SwitchTest(NaN) === 32)){ $ERROR("#10: SwitchTest(NaN) === 32. Actual: SwitchTest(NaN) ==="+ SwitchTest(NaN) ); } if(!(SwitchTest(Infinity) === 768)){ $ERROR("#10: SwitchTest(NaN) === 768. Actual: SwitchTest(NaN) ==="+ SwitchTest(NaN) ); }
{ "pile_set_name": "Github" }
# These are supported funding model platforms github: markbates patreon: buffalo
{ "pile_set_name": "Github" }
""" Rbna yezedak Correctness w ye2lel men falsatk isa """ import os import torchfile import pickle import numpy as np import pdb import matplotlib.pyplot as plt import tensorflow as tf torch_output = torchfile.load('../out_networks_layers/dict_out.t7') with open('../out_networks_layers/out_linknet_layers.pkl', 'rb') as ff: our_output = pickle.load(ff) print(type(our_output)) print(len(our_output)) #xpl= tf.placeholder(tf.float32, our_output[39].shape) #pp= tf.pad(xpl, tf.constant([[0,0],[1,1],[1,1],[0,0]]), "CONSTANT") #pp=tf.nn.max_pool(pp, ksize=(1,3,3,1), strides=(1,2,2,1), padding='VALID') #pp=tf.image.resize_images(pp, [32,64]) #pp=tf.nn.conv2d() #session=tf.Session() #out_temp= session.run(pp, feed_dict={xpl:our_output[2]}) #out_temp2= torch_output[b'network/conv1_x/pool1'] pdb.set_trace() #plt.figure(1);plt.imshow(our_output[0][0,:,:,0]); #plt.figure(2);plt.imshow(torch_output[b'x'][0,0,:,:]);plt.show() # #plt.figure(1);plt.imshow(our_output[1][0,:,:,0]); #plt.figure(2);plt.imshow(torch_output[b'network/conv1_x/conv1'][0,0,:,:]);plt.show() # #plt.figure(1);plt.imshow(our_output[3][0,:,:,0]); #plt.figure(2);plt.imshow(torch_output[b'network/conv2_x/conv2_1/conv_1'][0,0,:,:]);plt.show() # #plt.figure(1);plt.imshow(our_output[9][0,:,:,0]); #plt.figure(2);plt.imshow(torch_output[b'network/conv2_x/conv2_2/conv_2'][0,0,:,:]);plt.show() #plt.figure(1);plt.imshow(our_output[11][0,:,:,0]); #plt.figure(2);plt.imshow(torch_output[b'network/conv3_x/conv3_1/shortcut_conv'][0,0,:,:]);plt.show() plt.figure(1);plt.imshow(our_output[37][0,:,:,0]); plt.figure(2);plt.imshow(torch_output[b'network/conv5_x/conv5_2/bn_2'][0,0,:,:]);plt.show() plt.figure(1);plt.imshow(our_output[-1][0,:,:,0]); plt.figure(2);plt.imshow(torch_output[b'network/output_block/deconv_out_2'][0,0,:,:]);plt.show() print(len(torch_output.items()))
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/utils/crypto/KeyWrapAlgorithm.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/utils/EnumParseOverflowContainer.h> #include <aws/core/Globals.h> using namespace Aws::Utils; namespace Aws { namespace Utils { namespace Crypto { namespace KeyWrapAlgorithmMapper { static const int keyWrapAlgorithm_KMS_HASH = HashingUtils::HashString("kms"); static const int keyWrapAlgorithm_KMS_CONTEXT_HASH = HashingUtils::HashString("kms+context"); static const int keyWrapAlgorithm_KeyWrap_HASH = HashingUtils::HashString("AESWrap"); static const int keyWrapAlgorithm_AES_GCM_HASH = HashingUtils::HashString("AES/GCM"); KeyWrapAlgorithm GetKeyWrapAlgorithmForName(const Aws::String& name) { int hashcode = HashingUtils::HashString(name.c_str()); if (hashcode == keyWrapAlgorithm_KMS_HASH) { return KeyWrapAlgorithm::KMS; } else if (hashcode == keyWrapAlgorithm_KMS_CONTEXT_HASH) { return KeyWrapAlgorithm::KMS_CONTEXT; } else if (hashcode == keyWrapAlgorithm_KeyWrap_HASH) { return KeyWrapAlgorithm::AES_KEY_WRAP; } else if (hashcode == keyWrapAlgorithm_AES_GCM_HASH) { return KeyWrapAlgorithm::AES_GCM; } assert(0); return KeyWrapAlgorithm::NONE; } Aws::String GetNameForKeyWrapAlgorithm(KeyWrapAlgorithm enumValue) { switch (enumValue) { case KeyWrapAlgorithm::KMS: return "kms"; case KeyWrapAlgorithm::KMS_CONTEXT: return "kms+context"; case KeyWrapAlgorithm::AES_KEY_WRAP: return "AESWrap"; case KeyWrapAlgorithm::AES_GCM: return "AES/GCM"; default: assert(0); } return ""; } }//namespace KeyWrapAlgorithmMapper }//namespace Crypto }//namespace Utils }//namespace Aws
{ "pile_set_name": "Github" }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Llilum.K64F { using System; using Microsoft.Zelig.Runtime; using Chipset = Microsoft.CortexM4OnMBED; using ChipsetAbstration = Microsoft.DeviceModels.Chipset.CortexM3; public sealed class SpiProviderUwp : Microsoft.Zelig.Runtime.SpiProviderUwp { private static readonly string[] m_spiDevices = { "SPI0", "SPI1", "SPI2" }; public static readonly SpiChannelInfoUwp SPI0 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI0, }; public static readonly SpiChannelInfoUwp SPI1 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI1, }; public static readonly SpiChannelInfoUwp SPI2 = new SpiChannelInfoUwp() { ChipSelectLines = 1, MinFreq = 1000, MaxFreq = 30000000, Supports16 = true, ChannelInfoKernel = SpiProvider.SPI2, }; public override SpiChannelInfoUwp GetSpiChannelInfo(string busId) { switch (busId) { case "SPI0": return SPI0; case "SPI1": return SPI1; case "SPI2": return SPI2; default: return null; } } public override string[] GetSpiChannels() { return m_spiDevices; } } }
{ "pile_set_name": "Github" }
/* $OpenBSD$ */ /* * Copyright (c) 2007 Nicholas Marriott <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/types.h> #include <stdlib.h> #include "tmux.h" /* * Change session name. */ enum cmd_retval cmd_rename_session_exec(struct cmd *, struct cmd_q *); const struct cmd_entry cmd_rename_session_entry = { .name = "rename-session", .alias = "rename", .args = { "t:", 1, 1 }, .usage = CMD_TARGET_SESSION_USAGE " new-name", .tflag = CMD_SESSION, .flags = 0, .exec = cmd_rename_session_exec }; enum cmd_retval cmd_rename_session_exec(struct cmd *self, struct cmd_q *cmdq) { struct args *args = self->args; struct session *s = cmdq->state.tflag.s; const char *newname; newname = args->argv[0]; if (!session_check_name(newname)) { cmdq_error(cmdq, "bad session name: %s", newname); return (CMD_RETURN_ERROR); } if (session_find(newname) != NULL) { cmdq_error(cmdq, "duplicate session: %s", newname); return (CMD_RETURN_ERROR); } RB_REMOVE(sessions, &sessions, s); free(s->name); s->name = xstrdup(newname); RB_INSERT(sessions, &sessions, s); server_status_session(s); notify_session_renamed(s); return (CMD_RETURN_NORMAL); }
{ "pile_set_name": "Github" }