repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
LastStar/mongoid
spec/functional/mongoid/callback_spec.rb
<filename>spec/functional/mongoid/callback_spec.rb<gh_stars>1-10 require "spec_helper" describe Mongoid::Callbacks do before do ValidationCallback.delete_all ParentDoc.delete_all end context "callback on valid?" do it 'should go in all validation callback in good order' do shin = ValidationCallback.new shin.valid? shin.history.should == [:before_validation, :validate, :after_validation] end end context "when creating child documents in callbacks" do let(:parent) do ParentDoc.new end before do parent.save end it "does not duplicate the child documents" do parent.child_docs.create(:position => 1) ParentDoc.find(parent.id).child_docs.size.should == 1 end end context "when callbacks cancel persistence" do let(:address) do Address.new(:street => "123 Sesame") end context "when creating a document" do let(:person) do Person.new(:mode => :prevent_save, :title => "Associate", :addresses => [ address ]) end it "fails to save" do person.should be_valid person.save.should == false end it "is a new record" do person.should be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do person.should be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are left dirty" do address.should be_changed expect { person.save }.not_to change { address.changed? } end end context "when updating a document" do let(:person) do Person.create.tap { |person| person.attributes = { :mode => :prevent_save, :title => "Associate", :addresses => [ address ] } } end after do Person.delete_all end it "#save returns false" do person.should be_valid person.save.should == false end it "is a not a new record" do person.should_not be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do person.should be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are not left dirty" do address.should be_changed expect { person.save }.to change { address.changed? } end end end end
mdlewisfb/OpenCellular
firmware/ec/inc/subsystem/gpp/ebmp.h
<filename>firmware/ec/inc/subsystem/gpp/ebmp.h /** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #ifndef EBMP_H_ #define EBMP_H_ #include "inc/subsystem/gpp/gpp.h" /***************************************************************************** * MACRO DEFINITIONS *****************************************************************************/ #define EBMP_TASK_STACK_SIZE 1024 #define EBMP_TASK_PRIORITY 2 /***************************************************************************** * STRUCT/ENUM DEFINITIONS *****************************************************************************/ /* * GPP states are define here. Where we define various states GPP or AP can be in. * S0_SC[059] and S5[09] are the inputs * T0: AP SOC under Reset. (0,0) * T1: AP starts the booting. (0,0) * T2: AP starts DDR init. (0,1) * T3: PCIe and SPC init. (1,1) * T4: Normal Ubuntu Boot: PE2 -> 1 Recovery Boot: PE2 -> 0. (1,0) * T5: mSATA boot progress(0,0) * T6: OC_Watchdog deamon started successfully.(0,1) * T7: OC_Watchdog deamon process responds to EC via OC-Middleware.(1,1) */ typedef enum { STATE_INVALID = -1, STATE_T0 = 0, STATE_T1, STATE_T2, STATE_T3, STATE_T4, STATE_T5, STATE_T6, STATE_T7, STATE_UPGRADE } apStates; typedef enum { AP_RESET = 0, AP_BOOT_PROGRESS_MONITOR_1 = 1, AP_BOOT_PROGRESS_MONITOR_2 = 2 } apBootMonitor; /***************************************************************************** * FUNCTION DECLARATIONS *****************************************************************************/ void ebmp_init(Gpp_gpioCfg *driver); #endif /* EBMP_H_ */
yijunyu/demo-fast
datasets/linux-4.11-rc3/include/net/sctp/ulpevent.h
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2001, 2004 * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2001 Intel Corp. * Copyright (c) 2001 Nokia, Inc. * Copyright (c) 2001 <NAME> * * These are the definitions needed for the sctp_ulpevent type. The * sctp_ulpevent type is used to carry information from the state machine * upwards to the ULP. * * This file is part of the SCTP kernel implementation * * This SCTP implementation 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, or (at your option) * any later version. * * This SCTP implementation 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 GNU CC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <<EMAIL>> * * Written or modified by: * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> * <NAME> <<EMAIL>> */ #ifndef __sctp_ulpevent_h__ #define __sctp_ulpevent_h__ /* A structure to carry information to the ULP (e.g. Sockets API) */ /* Warning: This sits inside an skb.cb[] area. Be very careful of * growing this structure as it is at the maximum limit now. */ struct sctp_ulpevent { struct sctp_association *asoc; struct sctp_chunk *chunk; unsigned int rmem_len; __u32 ppid; __u32 tsn; __u32 cumtsn; __u16 stream; __u16 ssn; __u16 flags; __u16 msg_flags; }; /* Retrieve the skb this event sits inside of. */ static inline struct sk_buff *sctp_event2skb(const struct sctp_ulpevent *ev) { return container_of((void *)ev, struct sk_buff, cb); } /* Retrieve & cast the event sitting inside the skb. */ static inline struct sctp_ulpevent *sctp_skb2event(struct sk_buff *skb) { return (struct sctp_ulpevent *)skb->cb; } void sctp_ulpevent_free(struct sctp_ulpevent *); int sctp_ulpevent_is_notification(const struct sctp_ulpevent *); unsigned int sctp_queue_purge_ulpevents(struct sk_buff_head *list); struct sctp_ulpevent *sctp_ulpevent_make_assoc_change( const struct sctp_association *asoc, __u16 flags, __u16 state, __u16 error, __u16 outbound, __u16 inbound, struct sctp_chunk *chunk, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_peer_addr_change( const struct sctp_association *asoc, const struct sockaddr_storage *aaddr, int flags, int state, int error, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_remote_error( const struct sctp_association *asoc, struct sctp_chunk *chunk, __u16 flags, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_send_failed( const struct sctp_association *asoc, struct sctp_chunk *chunk, __u16 flags, __u32 error, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_shutdown_event( const struct sctp_association *asoc, __u16 flags, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_pdapi( const struct sctp_association *asoc, __u32 indication, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_adaptation_indication( const struct sctp_association *asoc, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_rcvmsg(struct sctp_association *asoc, struct sctp_chunk *chunk, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_authkey( const struct sctp_association *asoc, __u16 key_id, __u32 indication, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_sender_dry_event( const struct sctp_association *asoc, gfp_t gfp); struct sctp_ulpevent *sctp_ulpevent_make_stream_reset_event( const struct sctp_association *asoc, __u16 flags, __u16 stream_num, __u16 *stream_list, gfp_t gfp); void sctp_ulpevent_read_sndrcvinfo(const struct sctp_ulpevent *event, struct msghdr *); void sctp_ulpevent_read_rcvinfo(const struct sctp_ulpevent *event, struct msghdr *); void sctp_ulpevent_read_nxtinfo(const struct sctp_ulpevent *event, struct msghdr *, struct sock *sk); __u16 sctp_ulpevent_get_notification_type(const struct sctp_ulpevent *event); /* Is this event type enabled? */ static inline int sctp_ulpevent_type_enabled(__u16 sn_type, struct sctp_event_subscribe *mask) { char *amask = (char *) mask; return amask[sn_type - SCTP_SN_TYPE_BASE]; } /* Given an event subscription, is this event enabled? */ static inline int sctp_ulpevent_is_enabled(const struct sctp_ulpevent *event, struct sctp_event_subscribe *mask) { __u16 sn_type; int enabled = 1; if (sctp_ulpevent_is_notification(event)) { sn_type = sctp_ulpevent_get_notification_type(event); enabled = sctp_ulpevent_type_enabled(sn_type, mask); } return enabled; } #endif /* __sctp_ulpevent_h__ */
LukasZahradnik/PyNeurologic
neuralogic/grammar/NeuralogicParser.py
<gh_stars>10-100 # Generated from /home/lukas/Workspace/prcvut/pyneuralogic/neuralogic/grammar/Neuralogic.g4 by ANTLR 4.8 # encoding: utf-8 from antlr4 import * from io import StringIO import sys if sys.version_info[1] > 5: from typing import TextIO else: from typing.io import TextIO def serializedATN(): with StringIO() as buf: buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\34") buf.write("\u0114\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7") buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16") buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23\t\23") buf.write("\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31") buf.write("\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36") buf.write("\4\37\t\37\3\2\7\2@\n\2\f\2\16\2C\13\2\3\3\3\3\3\3\3\3") buf.write("\3\3\3\3\3\3\3\3\3\3\5\3N\n\3\3\4\3\4\3\4\3\4\6\4T\n\4") buf.write("\r\4\16\4U\3\4\6\4Y\n\4\r\4\16\4Z\5\4]\n\4\3\5\3\5\6\5") buf.write("a\n\5\r\5\16\5b\3\5\3\5\3\6\3\6\3\7\3\7\3\7\3\7\3\7\6") buf.write("\7n\n\7\r\7\16\7o\3\7\3\7\3\7\6\7u\n\7\r\7\16\7v\5\7y") buf.write("\n\7\3\b\3\b\3\b\3\t\5\t\177\n\t\3\t\5\t\u0082\n\t\3\t") buf.write("\3\t\5\t\u0086\n\t\3\n\3\n\3\n\3\n\7\n\u008c\n\n\f\n\16") buf.write("\n\u008f\13\n\5\n\u0091\n\n\3\n\3\n\3\13\3\13\5\13\u0097") buf.write("\n\13\3\f\3\f\3\r\3\r\3\16\5\16\u009e\n\16\3\16\5\16\u00a1") buf.write("\n\16\3\16\3\16\3\16\5\16\u00a6\n\16\3\17\3\17\3\17\7") buf.write("\17\u00ab\n\17\f\17\16\17\u00ae\13\17\3\20\3\20\3\20\3") buf.write("\20\5\20\u00b4\n\20\3\20\5\20\u00b7\n\20\3\21\3\21\3\21") buf.write("\3\21\7\21\u00bd\n\21\f\21\16\21\u00c0\13\21\5\21\u00c2") buf.write("\n\21\3\21\3\21\3\22\3\22\3\22\3\22\3\22\5\22\u00cb\n") buf.write("\22\3\22\3\22\5\22\u00cf\n\22\3\23\3\23\3\23\3\24\3\24") buf.write("\3\24\3\25\3\25\3\25\3\25\3\26\3\26\3\27\3\27\3\27\5\27") buf.write("\u00e0\n\27\3\27\3\27\5\27\u00e4\n\27\3\30\3\30\3\30\3") buf.write("\30\3\31\3\31\3\32\3\32\3\32\3\32\5\32\u00f0\n\32\3\33") buf.write("\3\33\3\34\3\34\3\34\3\34\7\34\u00f8\n\34\f\34\16\34\u00fb") buf.write("\13\34\3\34\3\34\3\35\3\35\6\35\u0101\n\35\r\35\16\35") buf.write("\u0102\3\35\3\35\3\36\3\36\3\36\3\36\7\36\u010b\n\36\f") buf.write("\36\16\36\u010e\13\36\3\36\3\36\3\37\3\37\3\37\2\2 \2") buf.write('\4\6\b\n\f\16\20\22\24\26\30\32\34\36 "$&(*,.\60\62\64') buf.write("\668:<\2\4\3\2\5\7\3\2\5\6\2\u011c\2A\3\2\2\2\4M\3\2\2") buf.write("\2\6\\\3\2\2\2\b`\3\2\2\2\nf\3\2\2\2\fx\3\2\2\2\16z\3") buf.write("\2\2\2\20~\3\2\2\2\22\u0087\3\2\2\2\24\u0096\3\2\2\2\26") buf.write("\u0098\3\2\2\2\30\u009a\3\2\2\2\32\u009d\3\2\2\2\34\u00a7") buf.write('\3\2\2\2\36\u00af\3\2\2\2 \u00b8\3\2\2\2"\u00c5\3\2\2') buf.write("\2$\u00d0\3\2\2\2&\u00d3\3\2\2\2(\u00d6\3\2\2\2*\u00da") buf.write("\3\2\2\2,\u00df\3\2\2\2.\u00e5\3\2\2\2\60\u00e9\3\2\2") buf.write("\2\62\u00ef\3\2\2\2\64\u00f1\3\2\2\2\66\u00f3\3\2\2\2") buf.write("8\u00fe\3\2\2\2:\u0106\3\2\2\2<\u0111\3\2\2\2>@\5\4\3") buf.write("\2?>\3\2\2\2@C\3\2\2\2A?\3\2\2\2AB\3\2\2\2B\3\3\2\2\2") buf.write('CA\3\2\2\2DN\5"\22\2EN\5\16\b\2FG\5\34\17\2GH\7\3\2\2') buf.write("HN\3\2\2\2IN\5&\24\2JN\5$\23\2KN\5(\25\2LN\5*\26\2MD\3") buf.write("\2\2\2ME\3\2\2\2MF\3\2\2\2MI\3\2\2\2MJ\3\2\2\2MK\3\2\2") buf.write("\2ML\3\2\2\2N\5\3\2\2\2OP\5\n\6\2PQ\7\b\2\2QR\5\b\5\2") buf.write("RT\3\2\2\2SO\3\2\2\2TU\3\2\2\2US\3\2\2\2UV\3\2\2\2V]\3") buf.write("\2\2\2WY\5\b\5\2XW\3\2\2\2YZ\3\2\2\2ZX\3\2\2\2Z[\3\2\2") buf.write('\2[]\3\2\2\2\\S\3\2\2\2\\X\3\2\2\2]\7\3\2\2\2^a\5"\22') buf.write("\2_a\5\34\17\2`^\3\2\2\2`_\3\2\2\2ab\3\2\2\2b`\3\2\2\2") buf.write("bc\3\2\2\2cd\3\2\2\2de\7\3\2\2e\t\3\2\2\2fg\5\34\17\2") buf.write("g\13\3\2\2\2hi\5\20\t\2ij\7\b\2\2jk\5\34\17\2kl\7\3\2") buf.write("\2ln\3\2\2\2mh\3\2\2\2no\3\2\2\2om\3\2\2\2op\3\2\2\2p") buf.write("y\3\2\2\2qr\5\34\17\2rs\7\3\2\2su\3\2\2\2tq\3\2\2\2uv") buf.write("\3\2\2\2vt\3\2\2\2vw\3\2\2\2wy\3\2\2\2xm\3\2\2\2xt\3\2") buf.write("\2\2y\r\3\2\2\2z{\5\20\t\2{|\7\3\2\2|\17\3\2\2\2}\177") buf.write("\5,\27\2~}\3\2\2\2~\177\3\2\2\2\177\u0081\3\2\2\2\u0080") buf.write("\u0082\5<\37\2\u0081\u0080\3\2\2\2\u0081\u0082\3\2\2\2") buf.write("\u0082\u0083\3\2\2\2\u0083\u0085\5\32\16\2\u0084\u0086") buf.write("\5\22\n\2\u0085\u0084\3\2\2\2\u0085\u0086\3\2\2\2\u0086") buf.write("\21\3\2\2\2\u0087\u0090\7\20\2\2\u0088\u008d\5\24\13\2") buf.write("\u0089\u008a\7\22\2\2\u008a\u008c\5\24\13\2\u008b\u0089") buf.write("\3\2\2\2\u008c\u008f\3\2\2\2\u008d\u008b\3\2\2\2\u008d") buf.write("\u008e\3\2\2\2\u008e\u0091\3\2\2\2\u008f\u008d\3\2\2\2") buf.write("\u0090\u0088\3\2\2\2\u0090\u0091\3\2\2\2\u0091\u0092\3") buf.write("\2\2\2\u0092\u0093\7\21\2\2\u0093\23\3\2\2\2\u0094\u0097") buf.write("\5\30\r\2\u0095\u0097\5\26\f\2\u0096\u0094\3\2\2\2\u0096") buf.write("\u0095\3\2\2\2\u0097\25\3\2\2\2\u0098\u0099\7\4\2\2\u0099") buf.write("\27\3\2\2\2\u009a\u009b\t\2\2\2\u009b\31\3\2\2\2\u009c") buf.write("\u009e\7\31\2\2\u009d\u009c\3\2\2\2\u009d\u009e\3\2\2") buf.write("\2\u009e\u00a0\3\2\2\2\u009f\u00a1\7\30\2\2\u00a0\u009f") buf.write("\3\2\2\2\u00a0\u00a1\3\2\2\2\u00a1\u00a2\3\2\2\2\u00a2") buf.write("\u00a5\7\7\2\2\u00a3\u00a4\7\23\2\2\u00a4\u00a6\7\5\2") buf.write("\2\u00a5\u00a3\3\2\2\2\u00a5\u00a6\3\2\2\2\u00a6\33\3") buf.write("\2\2\2\u00a7\u00ac\5\20\t\2\u00a8\u00a9\7\22\2\2\u00a9") buf.write("\u00ab\5\20\t\2\u00aa\u00a8\3\2\2\2\u00ab\u00ae\3\2\2") buf.write("\2\u00ac\u00aa\3\2\2\2\u00ac\u00ad\3\2\2\2\u00ad\35\3") buf.write("\2\2\2\u00ae\u00ac\3\2\2\2\u00af\u00b0\7\7\2\2\u00b0\u00b6") buf.write("\7\t\2\2\u00b1\u00b7\5\62\32\2\u00b2\u00b4\7\26\2\2\u00b3") buf.write("\u00b2\3\2\2\2\u00b3\u00b4\3\2\2\2\u00b4\u00b5\3\2\2\2") buf.write("\u00b5\u00b7\7\7\2\2\u00b6\u00b1\3\2\2\2\u00b6\u00b3\3") buf.write("\2\2\2\u00b7\37\3\2\2\2\u00b8\u00c1\7\16\2\2\u00b9\u00be") buf.write("\5\36\20\2\u00ba\u00bb\7\22\2\2\u00bb\u00bd\5\36\20\2") buf.write("\u00bc\u00ba\3\2\2\2\u00bd\u00c0\3\2\2\2\u00be\u00bc\3") buf.write("\2\2\2\u00be\u00bf\3\2\2\2\u00bf\u00c2\3\2\2\2\u00c0\u00be") buf.write("\3\2\2\2\u00c1\u00b9\3\2\2\2\u00c1\u00c2\3\2\2\2\u00c2") buf.write("\u00c3\3\2\2\2\u00c3\u00c4\7\17\2\2\u00c4!\3\2\2\2\u00c5") buf.write("\u00c6\5\20\t\2\u00c6\u00c7\7\b\2\2\u00c7\u00ca\5\34\17") buf.write("\2\u00c8\u00c9\7\22\2\2\u00c9\u00cb\5\60\31\2\u00ca\u00c8") buf.write("\3\2\2\2\u00ca\u00cb\3\2\2\2\u00cb\u00cc\3\2\2\2\u00cc") buf.write("\u00ce\7\3\2\2\u00cd\u00cf\5 \21\2\u00ce\u00cd\3\2\2\2") buf.write("\u00ce\u00cf\3\2\2\2\u00cf#\3\2\2\2\u00d0\u00d1\5\32\16") buf.write("\2\u00d1\u00d2\5,\27\2\u00d2%\3\2\2\2\u00d3\u00d4\5\32") buf.write("\16\2\u00d4\u00d5\5 \21\2\u00d5'\3\2\2\2\u00d6\u00d7") buf.write("\7\26\2\2\u00d7\u00d8\7\7\2\2\u00d8\u00d9\5 \21\2\u00d9") buf.write(")\3\2\2\2\u00da\u00db\5 \21\2\u00db+\3\2\2\2\u00dc\u00dd") buf.write("\7\26\2\2\u00dd\u00de\7\7\2\2\u00de\u00e0\7\t\2\2\u00df") buf.write("\u00dc\3\2\2\2\u00df\u00e0\3\2\2\2\u00e0\u00e3\3\2\2\2") buf.write("\u00e1\u00e4\5.\30\2\u00e2\u00e4\5\62\32\2\u00e3\u00e1") buf.write("\3\2\2\2\u00e3\u00e2\3\2\2\2\u00e4-\3\2\2\2\u00e5\u00e6") buf.write("\7\f\2\2\u00e6\u00e7\5\62\32\2\u00e7\u00e8\7\r\2\2\u00e8") buf.write("/\3\2\2\2\u00e9\u00ea\5,\27\2\u00ea\61\3\2\2\2\u00eb\u00f0") buf.write("\5\64\33\2\u00ec\u00f0\5\66\34\2\u00ed\u00f0\58\35\2\u00ee") buf.write("\u00f0\5:\36\2\u00ef\u00eb\3\2\2\2\u00ef\u00ec\3\2\2\2") buf.write("\u00ef\u00ed\3\2\2\2\u00ef\u00ee\3\2\2\2\u00f0\63\3\2") buf.write("\2\2\u00f1\u00f2\t\3\2\2\u00f2\65\3\2\2\2\u00f3\u00f4") buf.write("\7\16\2\2\u00f4\u00f9\5\64\33\2\u00f5\u00f6\7\22\2\2\u00f6") buf.write("\u00f8\5\64\33\2\u00f7\u00f5\3\2\2\2\u00f8\u00fb\3\2\2") buf.write("\2\u00f9\u00f7\3\2\2\2\u00f9\u00fa\3\2\2\2\u00fa\u00fc") buf.write("\3\2\2\2\u00fb\u00f9\3\2\2\2\u00fc\u00fd\7\17\2\2\u00fd") buf.write("\67\3\2\2\2\u00fe\u0100\7\16\2\2\u00ff\u0101\5\66\34\2") buf.write("\u0100\u00ff\3\2\2\2\u0101\u0102\3\2\2\2\u0102\u0100\3") buf.write("\2\2\2\u0102\u0103\3\2\2\2\u0103\u0104\3\2\2\2\u0104\u0105") buf.write("\7\17\2\2\u01059\3\2\2\2\u0106\u0107\7\n\2\2\u0107\u010c") buf.write("\5\64\33\2\u0108\u0109\7\22\2\2\u0109\u010b\5\64\33\2") buf.write("\u010a\u0108\3\2\2\2\u010b\u010e\3\2\2\2\u010c\u010a\3") buf.write("\2\2\2\u010c\u010d\3\2\2\2\u010d\u010f\3\2\2\2\u010e\u010c") buf.write("\3\2\2\2\u010f\u0110\7\13\2\2\u0110;\3\2\2\2\u0111\u0112") buf.write('\7\27\2\2\u0112=\3\2\2\2"AMUZ\\`bovx~\u0081\u0085\u008d') buf.write("\u0090\u0096\u009d\u00a0\u00a5\u00ac\u00b3\u00b6\u00be") buf.write("\u00c1\u00ca\u00ce\u00df\u00e3\u00ef\u00f9\u0102\u010c") return buf.getvalue() class NeuralogicParser(Parser): grammarFileName = "Neuralogic.g4" atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [DFA(ds, i) for i, ds in enumerate(atn.decisionToState)] sharedContextCache = PredictionContextCache() literalNames = [ "<INVALID>", "'.'", "<INVALID>", "<INVALID>", "<INVALID>", "<INVALID>", "':-'", "'='", "'{'", "'}'", "'<'", "'>'", "'['", "']'", "'('", "')'", "','", "'/'", "'^'", "'true'", "'$'", "'~'", "'@'", "'*'", ] symbolicNames = [ "<INVALID>", "<INVALID>", "VARIABLE", "INT", "FLOAT", "ATOMIC_NAME", "IMPLIED_BY", "ASSIGN", "LCURL", "RCURL", "LANGLE", "RANGLE", "LBRACKET", "RBRACKET", "LPAREN", "RPAREN", "COMMA", "SLASH", "CARET", "TRUE", "DOLLAR", "NEGATION", "SPECIAL", "PRIVATE", "WS", "COMMENT", "MULTILINE_COMMENT", ] RULE_templateFile = 0 RULE_templateLine = 1 RULE_examplesFile = 2 RULE_liftedExample = 3 RULE_label = 4 RULE_queriesFile = 5 RULE_fact = 6 RULE_atom = 7 RULE_termList = 8 RULE_term = 9 RULE_variable = 10 RULE_constant = 11 RULE_predicate = 12 RULE_conjunction = 13 RULE_metadataVal = 14 RULE_metadataList = 15 RULE_lrnnRule = 16 RULE_predicateOffset = 17 RULE_predicateMetadata = 18 RULE_weightMetadata = 19 RULE_templateMetadata = 20 RULE_weight = 21 RULE_fixedValue = 22 RULE_offset = 23 RULE_value = 24 RULE_number = 25 RULE_vector = 26 RULE_matrix = 27 RULE_dimensions = 28 RULE_negation = 29 ruleNames = [ "templateFile", "templateLine", "examplesFile", "liftedExample", "label", "queriesFile", "fact", "atom", "termList", "term", "variable", "constant", "predicate", "conjunction", "metadataVal", "metadataList", "lrnnRule", "predicateOffset", "predicateMetadata", "weightMetadata", "templateMetadata", "weight", "fixedValue", "offset", "value", "number", "vector", "matrix", "dimensions", "negation", ] EOF = Token.EOF T__0 = 1 VARIABLE = 2 INT = 3 FLOAT = 4 ATOMIC_NAME = 5 IMPLIED_BY = 6 ASSIGN = 7 LCURL = 8 RCURL = 9 LANGLE = 10 RANGLE = 11 LBRACKET = 12 RBRACKET = 13 LPAREN = 14 RPAREN = 15 COMMA = 16 SLASH = 17 CARET = 18 TRUE = 19 DOLLAR = 20 NEGATION = 21 SPECIAL = 22 PRIVATE = 23 WS = 24 COMMENT = 25 MULTILINE_COMMENT = 26 def __init__(self, input: TokenStream, output: TextIO = sys.stdout): super().__init__(input, output) self.checkVersion("4.8") self._interp = ParserATNSimulator( self, self.atn, self.decisionsToDFA, self.sharedContextCache ) self._predicates = None class TemplateFileContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def templateLine(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.TemplateLineContext) else: return self.getTypedRuleContext(NeuralogicParser.TemplateLineContext, i) def getRuleIndex(self): return NeuralogicParser.RULE_templateFile def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterTemplateFile"): listener.enterTemplateFile(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitTemplateFile"): listener.exitTemplateFile(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitTemplateFile"): return visitor.visitTemplateFile(self) else: return visitor.visitChildren(self) def templateFile(self): localctx = NeuralogicParser.TemplateFileContext(self, self._ctx, self.state) self.enterRule(localctx, 0, self.RULE_templateFile) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 63 self._errHandler.sync(self) _la = self._input.LA(1) while ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0: self.state = 60 self.templateLine() self.state = 65 self._errHandler.sync(self) _la = self._input.LA(1) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TemplateLineContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def lrnnRule(self): return self.getTypedRuleContext(NeuralogicParser.LrnnRuleContext, 0) def fact(self): return self.getTypedRuleContext(NeuralogicParser.FactContext, 0) def conjunction(self): return self.getTypedRuleContext(NeuralogicParser.ConjunctionContext, 0) def predicateMetadata(self): return self.getTypedRuleContext( NeuralogicParser.PredicateMetadataContext, 0 ) def predicateOffset(self): return self.getTypedRuleContext(NeuralogicParser.PredicateOffsetContext, 0) def weightMetadata(self): return self.getTypedRuleContext(NeuralogicParser.WeightMetadataContext, 0) def templateMetadata(self): return self.getTypedRuleContext(NeuralogicParser.TemplateMetadataContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_templateLine def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterTemplateLine"): listener.enterTemplateLine(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitTemplateLine"): listener.exitTemplateLine(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitTemplateLine"): return visitor.visitTemplateLine(self) else: return visitor.visitChildren(self) def templateLine(self): localctx = NeuralogicParser.TemplateLineContext(self, self._ctx, self.state) self.enterRule(localctx, 2, self.RULE_templateLine) try: self.state = 75 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 1, self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 66 self.lrnnRule() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 67 self.fact() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 68 self.conjunction() self.state = 69 self.match(NeuralogicParser.T__0) pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 71 self.predicateMetadata() pass elif la_ == 5: self.enterOuterAlt(localctx, 5) self.state = 72 self.predicateOffset() pass elif la_ == 6: self.enterOuterAlt(localctx, 6) self.state = 73 self.weightMetadata() pass elif la_ == 7: self.enterOuterAlt(localctx, 7) self.state = 74 self.templateMetadata() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ExamplesFileContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def label(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.LabelContext) else: return self.getTypedRuleContext(NeuralogicParser.LabelContext, i) def IMPLIED_BY(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.IMPLIED_BY) else: return self.getToken(NeuralogicParser.IMPLIED_BY, i) def liftedExample(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.LiftedExampleContext) else: return self.getTypedRuleContext( NeuralogicParser.LiftedExampleContext, i ) def getRuleIndex(self): return NeuralogicParser.RULE_examplesFile def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterExamplesFile"): listener.enterExamplesFile(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitExamplesFile"): listener.exitExamplesFile(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitExamplesFile"): return visitor.visitExamplesFile(self) else: return visitor.visitChildren(self) def examplesFile(self): localctx = NeuralogicParser.ExamplesFileContext(self, self._ctx, self.state) self.enterRule(localctx, 4, self.RULE_examplesFile) self._la = 0 # Token type try: self.state = 90 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 4, self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 81 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 77 self.label() self.state = 78 self.match(NeuralogicParser.IMPLIED_BY) self.state = 79 self.liftedExample() self.state = 83 self._errHandler.sync(self) _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0 ) ): break pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 86 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 85 self.liftedExample() self.state = 88 self._errHandler.sync(self) _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0 ) ): break pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LiftedExampleContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def lrnnRule(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.LrnnRuleContext) else: return self.getTypedRuleContext(NeuralogicParser.LrnnRuleContext, i) def conjunction(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.ConjunctionContext) else: return self.getTypedRuleContext(NeuralogicParser.ConjunctionContext, i) def getRuleIndex(self): return NeuralogicParser.RULE_liftedExample def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterLiftedExample"): listener.enterLiftedExample(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitLiftedExample"): listener.exitLiftedExample(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitLiftedExample"): return visitor.visitLiftedExample(self) else: return visitor.visitChildren(self) def liftedExample(self): localctx = NeuralogicParser.LiftedExampleContext(self, self._ctx, self.state) self.enterRule(localctx, 6, self.RULE_liftedExample) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 94 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 94 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 5, self._ctx) if la_ == 1: self.state = 92 self.lrnnRule() pass elif la_ == 2: self.state = 93 self.conjunction() pass self.state = 96 self._errHandler.sync(self) _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0 ) ): break self.state = 98 self.match(NeuralogicParser.T__0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LabelContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def conjunction(self): return self.getTypedRuleContext(NeuralogicParser.ConjunctionContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_label def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterLabel"): listener.enterLabel(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitLabel"): listener.exitLabel(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitLabel"): return visitor.visitLabel(self) else: return visitor.visitChildren(self) def label(self): localctx = NeuralogicParser.LabelContext(self, self._ctx, self.state) self.enterRule(localctx, 8, self.RULE_label) try: self.enterOuterAlt(localctx, 1) self.state = 100 self.conjunction() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class QueriesFileContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def atom(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.AtomContext) else: return self.getTypedRuleContext(NeuralogicParser.AtomContext, i) def IMPLIED_BY(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.IMPLIED_BY) else: return self.getToken(NeuralogicParser.IMPLIED_BY, i) def conjunction(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.ConjunctionContext) else: return self.getTypedRuleContext(NeuralogicParser.ConjunctionContext, i) def getRuleIndex(self): return NeuralogicParser.RULE_queriesFile def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterQueriesFile"): listener.enterQueriesFile(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitQueriesFile"): listener.exitQueriesFile(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitQueriesFile"): return visitor.visitQueriesFile(self) else: return visitor.visitChildren(self) def queriesFile(self): localctx = NeuralogicParser.QueriesFileContext(self, self._ctx, self.state) self.enterRule(localctx, 10, self.RULE_queriesFile) self._la = 0 # Token type try: self.state = 118 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 9, self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 107 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 102 self.atom() self.state = 103 self.match(NeuralogicParser.IMPLIED_BY) self.state = 104 self.conjunction() self.state = 105 self.match(NeuralogicParser.T__0) self.state = 109 self._errHandler.sync(self) _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0 ) ): break pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 114 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 111 self.conjunction() self.state = 112 self.match(NeuralogicParser.T__0) self.state = 116 self._errHandler.sync(self) _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) | (1 << NeuralogicParser.NEGATION) | (1 << NeuralogicParser.SPECIAL) | (1 << NeuralogicParser.PRIVATE) ) ) != 0 ) ): break pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FactContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def atom(self): return self.getTypedRuleContext(NeuralogicParser.AtomContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_fact def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterFact"): listener.enterFact(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitFact"): listener.exitFact(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitFact"): return visitor.visitFact(self) else: return visitor.visitChildren(self) def fact(self): localctx = NeuralogicParser.FactContext(self, self._ctx, self.state) self.enterRule(localctx, 12, self.RULE_fact) try: self.enterOuterAlt(localctx, 1) self.state = 120 self.atom() self.state = 121 self.match(NeuralogicParser.T__0) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class AtomContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def predicate(self): return self.getTypedRuleContext(NeuralogicParser.PredicateContext, 0) def weight(self): return self.getTypedRuleContext(NeuralogicParser.WeightContext, 0) def negation(self): return self.getTypedRuleContext(NeuralogicParser.NegationContext, 0) def termList(self): return self.getTypedRuleContext(NeuralogicParser.TermListContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_atom def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterAtom"): listener.enterAtom(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitAtom"): listener.exitAtom(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitAtom"): return visitor.visitAtom(self) else: return visitor.visitChildren(self) def atom(self): localctx = NeuralogicParser.AtomContext(self, self._ctx, self.state) self.enterRule(localctx, 14, self.RULE_atom) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 124 self._errHandler.sync(self) _la = self._input.LA(1) if ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.LCURL) | (1 << NeuralogicParser.LANGLE) | (1 << NeuralogicParser.LBRACKET) | (1 << NeuralogicParser.DOLLAR) ) ) != 0: self.state = 123 self.weight() self.state = 127 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.NEGATION: self.state = 126 self.negation() self.state = 129 self.predicate() self.state = 131 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.LPAREN: self.state = 130 self.termList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TermListContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LPAREN(self): return self.getToken(NeuralogicParser.LPAREN, 0) def RPAREN(self): return self.getToken(NeuralogicParser.RPAREN, 0) def term(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.TermContext) else: return self.getTypedRuleContext(NeuralogicParser.TermContext, i) def COMMA(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.COMMA) else: return self.getToken(NeuralogicParser.COMMA, i) def getRuleIndex(self): return NeuralogicParser.RULE_termList def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterTermList"): listener.enterTermList(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitTermList"): listener.exitTermList(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitTermList"): return visitor.visitTermList(self) else: return visitor.visitChildren(self) def termList(self): localctx = NeuralogicParser.TermListContext(self, self._ctx, self.state) self.enterRule(localctx, 16, self.RULE_termList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 133 self.match(NeuralogicParser.LPAREN) self.state = 142 self._errHandler.sync(self) _la = self._input.LA(1) if ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.VARIABLE) | (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) ) ) != 0: self.state = 134 self.term() self.state = 139 self._errHandler.sync(self) _la = self._input.LA(1) while _la == NeuralogicParser.COMMA: self.state = 135 self.match(NeuralogicParser.COMMA) self.state = 136 self.term() self.state = 141 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 144 self.match(NeuralogicParser.RPAREN) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TermContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def constant(self): return self.getTypedRuleContext(NeuralogicParser.ConstantContext, 0) def variable(self): return self.getTypedRuleContext(NeuralogicParser.VariableContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_term def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterTerm"): listener.enterTerm(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitTerm"): listener.exitTerm(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitTerm"): return visitor.visitTerm(self) else: return visitor.visitChildren(self) def term(self): localctx = NeuralogicParser.TermContext(self, self._ctx, self.state) self.enterRule(localctx, 18, self.RULE_term) try: self.state = 148 self._errHandler.sync(self) token = self._input.LA(1) if token in [ NeuralogicParser.INT, NeuralogicParser.FLOAT, NeuralogicParser.ATOMIC_NAME, ]: self.enterOuterAlt(localctx, 1) self.state = 146 self.constant() pass elif token in [NeuralogicParser.VARIABLE]: self.enterOuterAlt(localctx, 2) self.state = 147 self.variable() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VariableContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def VARIABLE(self): return self.getToken(NeuralogicParser.VARIABLE, 0) def getRuleIndex(self): return NeuralogicParser.RULE_variable def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterVariable"): listener.enterVariable(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitVariable"): listener.exitVariable(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitVariable"): return visitor.visitVariable(self) else: return visitor.visitChildren(self) def variable(self): localctx = NeuralogicParser.VariableContext(self, self._ctx, self.state) self.enterRule(localctx, 20, self.RULE_variable) try: self.enterOuterAlt(localctx, 1) self.state = 150 self.match(NeuralogicParser.VARIABLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ConstantContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def ATOMIC_NAME(self): return self.getToken(NeuralogicParser.ATOMIC_NAME, 0) def INT(self): return self.getToken(NeuralogicParser.INT, 0) def FLOAT(self): return self.getToken(NeuralogicParser.FLOAT, 0) def getRuleIndex(self): return NeuralogicParser.RULE_constant def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterConstant"): listener.enterConstant(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitConstant"): listener.exitConstant(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitConstant"): return visitor.visitConstant(self) else: return visitor.visitChildren(self) def constant(self): localctx = NeuralogicParser.ConstantContext(self, self._ctx, self.state) self.enterRule(localctx, 22, self.RULE_constant) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 152 _la = self._input.LA(1) if not ( ( ((_la) & ~0x3F) == 0 and ( (1 << _la) & ( (1 << NeuralogicParser.INT) | (1 << NeuralogicParser.FLOAT) | (1 << NeuralogicParser.ATOMIC_NAME) ) ) != 0 ) ): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PredicateContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def ATOMIC_NAME(self): return self.getToken(NeuralogicParser.ATOMIC_NAME, 0) def PRIVATE(self): return self.getToken(NeuralogicParser.PRIVATE, 0) def SPECIAL(self): return self.getToken(NeuralogicParser.SPECIAL, 0) def SLASH(self): return self.getToken(NeuralogicParser.SLASH, 0) def INT(self): return self.getToken(NeuralogicParser.INT, 0) def getRuleIndex(self): return NeuralogicParser.RULE_predicate def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterPredicate"): listener.enterPredicate(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitPredicate"): listener.exitPredicate(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitPredicate"): return visitor.visitPredicate(self) else: return visitor.visitChildren(self) def predicate(self): localctx = NeuralogicParser.PredicateContext(self, self._ctx, self.state) self.enterRule(localctx, 24, self.RULE_predicate) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 155 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.PRIVATE: self.state = 154 self.match(NeuralogicParser.PRIVATE) self.state = 158 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.SPECIAL: self.state = 157 self.match(NeuralogicParser.SPECIAL) self.state = 160 self.match(NeuralogicParser.ATOMIC_NAME) self.state = 163 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.SLASH: self.state = 161 self.match(NeuralogicParser.SLASH) self.state = 162 self.match(NeuralogicParser.INT) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ConjunctionContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def atom(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.AtomContext) else: return self.getTypedRuleContext(NeuralogicParser.AtomContext, i) def COMMA(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.COMMA) else: return self.getToken(NeuralogicParser.COMMA, i) def getRuleIndex(self): return NeuralogicParser.RULE_conjunction def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterConjunction"): listener.enterConjunction(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitConjunction"): listener.exitConjunction(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitConjunction"): return visitor.visitConjunction(self) else: return visitor.visitChildren(self) def conjunction(self): localctx = NeuralogicParser.ConjunctionContext(self, self._ctx, self.state) self.enterRule(localctx, 26, self.RULE_conjunction) try: self.enterOuterAlt(localctx, 1) self.state = 165 self.atom() self.state = 170 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input, 19, self._ctx) while _alt != 2 and _alt != ATN.INVALID_ALT_NUMBER: if _alt == 1: self.state = 166 self.match(NeuralogicParser.COMMA) self.state = 167 self.atom() self.state = 172 self._errHandler.sync(self) _alt = self._interp.adaptivePredict(self._input, 19, self._ctx) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MetadataValContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def ATOMIC_NAME(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.ATOMIC_NAME) else: return self.getToken(NeuralogicParser.ATOMIC_NAME, i) def ASSIGN(self): return self.getToken(NeuralogicParser.ASSIGN, 0) def value(self): return self.getTypedRuleContext(NeuralogicParser.ValueContext, 0) def DOLLAR(self): return self.getToken(NeuralogicParser.DOLLAR, 0) def getRuleIndex(self): return NeuralogicParser.RULE_metadataVal def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterMetadataVal"): listener.enterMetadataVal(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitMetadataVal"): listener.exitMetadataVal(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitMetadataVal"): return visitor.visitMetadataVal(self) else: return visitor.visitChildren(self) def metadataVal(self): localctx = NeuralogicParser.MetadataValContext(self, self._ctx, self.state) self.enterRule(localctx, 28, self.RULE_metadataVal) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 173 self.match(NeuralogicParser.ATOMIC_NAME) self.state = 174 self.match(NeuralogicParser.ASSIGN) self.state = 180 self._errHandler.sync(self) token = self._input.LA(1) if token in [ NeuralogicParser.INT, NeuralogicParser.FLOAT, NeuralogicParser.LCURL, NeuralogicParser.LBRACKET, ]: self.state = 175 self.value() pass elif token in [NeuralogicParser.ATOMIC_NAME, NeuralogicParser.DOLLAR]: self.state = 177 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.DOLLAR: self.state = 176 self.match(NeuralogicParser.DOLLAR) self.state = 179 self.match(NeuralogicParser.ATOMIC_NAME) pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MetadataListContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LBRACKET(self): return self.getToken(NeuralogicParser.LBRACKET, 0) def RBRACKET(self): return self.getToken(NeuralogicParser.RBRACKET, 0) def metadataVal(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.MetadataValContext) else: return self.getTypedRuleContext(NeuralogicParser.MetadataValContext, i) def COMMA(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.COMMA) else: return self.getToken(NeuralogicParser.COMMA, i) def getRuleIndex(self): return NeuralogicParser.RULE_metadataList def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterMetadataList"): listener.enterMetadataList(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitMetadataList"): listener.exitMetadataList(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitMetadataList"): return visitor.visitMetadataList(self) else: return visitor.visitChildren(self) def metadataList(self): localctx = NeuralogicParser.MetadataListContext(self, self._ctx, self.state) self.enterRule(localctx, 30, self.RULE_metadataList) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 182 self.match(NeuralogicParser.LBRACKET) self.state = 191 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.ATOMIC_NAME: self.state = 183 self.metadataVal() self.state = 188 self._errHandler.sync(self) _la = self._input.LA(1) while _la == NeuralogicParser.COMMA: self.state = 184 self.match(NeuralogicParser.COMMA) self.state = 185 self.metadataVal() self.state = 190 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 193 self.match(NeuralogicParser.RBRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class LrnnRuleContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def atom(self): return self.getTypedRuleContext(NeuralogicParser.AtomContext, 0) def IMPLIED_BY(self): return self.getToken(NeuralogicParser.IMPLIED_BY, 0) def conjunction(self): return self.getTypedRuleContext(NeuralogicParser.ConjunctionContext, 0) def COMMA(self): return self.getToken(NeuralogicParser.COMMA, 0) def offset(self): return self.getTypedRuleContext(NeuralogicParser.OffsetContext, 0) def metadataList(self): return self.getTypedRuleContext(NeuralogicParser.MetadataListContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_lrnnRule def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterLrnnRule"): listener.enterLrnnRule(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitLrnnRule"): listener.exitLrnnRule(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitLrnnRule"): return visitor.visitLrnnRule(self) else: return visitor.visitChildren(self) def lrnnRule(self): localctx = NeuralogicParser.LrnnRuleContext(self, self._ctx, self.state) self.enterRule(localctx, 32, self.RULE_lrnnRule) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 195 self.atom() self.state = 196 self.match(NeuralogicParser.IMPLIED_BY) self.state = 197 self.conjunction() self.state = 200 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.COMMA: self.state = 198 self.match(NeuralogicParser.COMMA) self.state = 199 self.offset() self.state = 202 self.match(NeuralogicParser.T__0) self.state = 204 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 25, self._ctx) if la_ == 1: self.state = 203 self.metadataList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PredicateOffsetContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def predicate(self): return self.getTypedRuleContext(NeuralogicParser.PredicateContext, 0) def weight(self): return self.getTypedRuleContext(NeuralogicParser.WeightContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_predicateOffset def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterPredicateOffset"): listener.enterPredicateOffset(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitPredicateOffset"): listener.exitPredicateOffset(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitPredicateOffset"): return visitor.visitPredicateOffset(self) else: return visitor.visitChildren(self) def predicateOffset(self): localctx = NeuralogicParser.PredicateOffsetContext(self, self._ctx, self.state) self.enterRule(localctx, 34, self.RULE_predicateOffset) try: self.enterOuterAlt(localctx, 1) self.state = 206 self.predicate() self.state = 207 self.weight() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class PredicateMetadataContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def predicate(self): return self.getTypedRuleContext(NeuralogicParser.PredicateContext, 0) def metadataList(self): return self.getTypedRuleContext(NeuralogicParser.MetadataListContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_predicateMetadata def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterPredicateMetadata"): listener.enterPredicateMetadata(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitPredicateMetadata"): listener.exitPredicateMetadata(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitPredicateMetadata"): return visitor.visitPredicateMetadata(self) else: return visitor.visitChildren(self) def predicateMetadata(self): localctx = NeuralogicParser.PredicateMetadataContext( self, self._ctx, self.state ) self.enterRule(localctx, 36, self.RULE_predicateMetadata) try: self.enterOuterAlt(localctx, 1) self.state = 209 self.predicate() self.state = 210 self.metadataList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class WeightMetadataContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def DOLLAR(self): return self.getToken(NeuralogicParser.DOLLAR, 0) def ATOMIC_NAME(self): return self.getToken(NeuralogicParser.ATOMIC_NAME, 0) def metadataList(self): return self.getTypedRuleContext(NeuralogicParser.MetadataListContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_weightMetadata def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterWeightMetadata"): listener.enterWeightMetadata(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitWeightMetadata"): listener.exitWeightMetadata(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitWeightMetadata"): return visitor.visitWeightMetadata(self) else: return visitor.visitChildren(self) def weightMetadata(self): localctx = NeuralogicParser.WeightMetadataContext(self, self._ctx, self.state) self.enterRule(localctx, 38, self.RULE_weightMetadata) try: self.enterOuterAlt(localctx, 1) self.state = 212 self.match(NeuralogicParser.DOLLAR) self.state = 213 self.match(NeuralogicParser.ATOMIC_NAME) self.state = 214 self.metadataList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class TemplateMetadataContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def metadataList(self): return self.getTypedRuleContext(NeuralogicParser.MetadataListContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_templateMetadata def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterTemplateMetadata"): listener.enterTemplateMetadata(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitTemplateMetadata"): listener.exitTemplateMetadata(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitTemplateMetadata"): return visitor.visitTemplateMetadata(self) else: return visitor.visitChildren(self) def templateMetadata(self): localctx = NeuralogicParser.TemplateMetadataContext(self, self._ctx, self.state) self.enterRule(localctx, 40, self.RULE_templateMetadata) try: self.enterOuterAlt(localctx, 1) self.state = 216 self.metadataList() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class WeightContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def fixedValue(self): return self.getTypedRuleContext(NeuralogicParser.FixedValueContext, 0) def value(self): return self.getTypedRuleContext(NeuralogicParser.ValueContext, 0) def DOLLAR(self): return self.getToken(NeuralogicParser.DOLLAR, 0) def ATOMIC_NAME(self): return self.getToken(NeuralogicParser.ATOMIC_NAME, 0) def ASSIGN(self): return self.getToken(NeuralogicParser.ASSIGN, 0) def getRuleIndex(self): return NeuralogicParser.RULE_weight def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterWeight"): listener.enterWeight(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitWeight"): listener.exitWeight(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitWeight"): return visitor.visitWeight(self) else: return visitor.visitChildren(self) def weight(self): localctx = NeuralogicParser.WeightContext(self, self._ctx, self.state) self.enterRule(localctx, 42, self.RULE_weight) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 221 self._errHandler.sync(self) _la = self._input.LA(1) if _la == NeuralogicParser.DOLLAR: self.state = 218 self.match(NeuralogicParser.DOLLAR) self.state = 219 self.match(NeuralogicParser.ATOMIC_NAME) self.state = 220 self.match(NeuralogicParser.ASSIGN) self.state = 225 self._errHandler.sync(self) token = self._input.LA(1) if token in [NeuralogicParser.LANGLE]: self.state = 223 self.fixedValue() pass elif token in [ NeuralogicParser.INT, NeuralogicParser.FLOAT, NeuralogicParser.LCURL, NeuralogicParser.LBRACKET, ]: self.state = 224 self.value() pass else: raise NoViableAltException(self) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class FixedValueContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LANGLE(self): return self.getToken(NeuralogicParser.LANGLE, 0) def value(self): return self.getTypedRuleContext(NeuralogicParser.ValueContext, 0) def RANGLE(self): return self.getToken(NeuralogicParser.RANGLE, 0) def getRuleIndex(self): return NeuralogicParser.RULE_fixedValue def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterFixedValue"): listener.enterFixedValue(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitFixedValue"): listener.exitFixedValue(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitFixedValue"): return visitor.visitFixedValue(self) else: return visitor.visitChildren(self) def fixedValue(self): localctx = NeuralogicParser.FixedValueContext(self, self._ctx, self.state) self.enterRule(localctx, 44, self.RULE_fixedValue) try: self.enterOuterAlt(localctx, 1) self.state = 227 self.match(NeuralogicParser.LANGLE) self.state = 228 self.value() self.state = 229 self.match(NeuralogicParser.RANGLE) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class OffsetContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def weight(self): return self.getTypedRuleContext(NeuralogicParser.WeightContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_offset def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterOffset"): listener.enterOffset(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitOffset"): listener.exitOffset(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitOffset"): return visitor.visitOffset(self) else: return visitor.visitChildren(self) def offset(self): localctx = NeuralogicParser.OffsetContext(self, self._ctx, self.state) self.enterRule(localctx, 46, self.RULE_offset) try: self.enterOuterAlt(localctx, 1) self.state = 231 self.weight() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class ValueContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def number(self): return self.getTypedRuleContext(NeuralogicParser.NumberContext, 0) def vector(self): return self.getTypedRuleContext(NeuralogicParser.VectorContext, 0) def matrix(self): return self.getTypedRuleContext(NeuralogicParser.MatrixContext, 0) def dimensions(self): return self.getTypedRuleContext(NeuralogicParser.DimensionsContext, 0) def getRuleIndex(self): return NeuralogicParser.RULE_value def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterValue"): listener.enterValue(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitValue"): listener.exitValue(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitValue"): return visitor.visitValue(self) else: return visitor.visitChildren(self) def value(self): localctx = NeuralogicParser.ValueContext(self, self._ctx, self.state) self.enterRule(localctx, 48, self.RULE_value) try: self.state = 237 self._errHandler.sync(self) la_ = self._interp.adaptivePredict(self._input, 28, self._ctx) if la_ == 1: self.enterOuterAlt(localctx, 1) self.state = 233 self.number() pass elif la_ == 2: self.enterOuterAlt(localctx, 2) self.state = 234 self.vector() pass elif la_ == 3: self.enterOuterAlt(localctx, 3) self.state = 235 self.matrix() pass elif la_ == 4: self.enterOuterAlt(localctx, 4) self.state = 236 self.dimensions() pass except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class NumberContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def INT(self): return self.getToken(NeuralogicParser.INT, 0) def FLOAT(self): return self.getToken(NeuralogicParser.FLOAT, 0) def getRuleIndex(self): return NeuralogicParser.RULE_number def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterNumber"): listener.enterNumber(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitNumber"): listener.exitNumber(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitNumber"): return visitor.visitNumber(self) else: return visitor.visitChildren(self) def number(self): localctx = NeuralogicParser.NumberContext(self, self._ctx, self.state) self.enterRule(localctx, 50, self.RULE_number) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 239 _la = self._input.LA(1) if not (_la == NeuralogicParser.INT or _la == NeuralogicParser.FLOAT): self._errHandler.recoverInline(self) else: self._errHandler.reportMatch(self) self.consume() except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class VectorContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LBRACKET(self): return self.getToken(NeuralogicParser.LBRACKET, 0) def number(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.NumberContext) else: return self.getTypedRuleContext(NeuralogicParser.NumberContext, i) def RBRACKET(self): return self.getToken(NeuralogicParser.RBRACKET, 0) def COMMA(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.COMMA) else: return self.getToken(NeuralogicParser.COMMA, i) def getRuleIndex(self): return NeuralogicParser.RULE_vector def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterVector"): listener.enterVector(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitVector"): listener.exitVector(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitVector"): return visitor.visitVector(self) else: return visitor.visitChildren(self) def vector(self): localctx = NeuralogicParser.VectorContext(self, self._ctx, self.state) self.enterRule(localctx, 52, self.RULE_vector) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 241 self.match(NeuralogicParser.LBRACKET) self.state = 242 self.number() self.state = 247 self._errHandler.sync(self) _la = self._input.LA(1) while _la == NeuralogicParser.COMMA: self.state = 243 self.match(NeuralogicParser.COMMA) self.state = 244 self.number() self.state = 249 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 250 self.match(NeuralogicParser.RBRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class MatrixContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LBRACKET(self): return self.getToken(NeuralogicParser.LBRACKET, 0) def RBRACKET(self): return self.getToken(NeuralogicParser.RBRACKET, 0) def vector(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.VectorContext) else: return self.getTypedRuleContext(NeuralogicParser.VectorContext, i) def getRuleIndex(self): return NeuralogicParser.RULE_matrix def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterMatrix"): listener.enterMatrix(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitMatrix"): listener.exitMatrix(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitMatrix"): return visitor.visitMatrix(self) else: return visitor.visitChildren(self) def matrix(self): localctx = NeuralogicParser.MatrixContext(self, self._ctx, self.state) self.enterRule(localctx, 54, self.RULE_matrix) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 252 self.match(NeuralogicParser.LBRACKET) self.state = 254 self._errHandler.sync(self) _la = self._input.LA(1) while True: self.state = 253 self.vector() self.state = 256 self._errHandler.sync(self) _la = self._input.LA(1) if not (_la == NeuralogicParser.LBRACKET): break self.state = 258 self.match(NeuralogicParser.RBRACKET) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class DimensionsContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def LCURL(self): return self.getToken(NeuralogicParser.LCURL, 0) def number(self, i: int = None): if i is None: return self.getTypedRuleContexts(NeuralogicParser.NumberContext) else: return self.getTypedRuleContext(NeuralogicParser.NumberContext, i) def RCURL(self): return self.getToken(NeuralogicParser.RCURL, 0) def COMMA(self, i: int = None): if i is None: return self.getTokens(NeuralogicParser.COMMA) else: return self.getToken(NeuralogicParser.COMMA, i) def getRuleIndex(self): return NeuralogicParser.RULE_dimensions def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterDimensions"): listener.enterDimensions(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitDimensions"): listener.exitDimensions(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitDimensions"): return visitor.visitDimensions(self) else: return visitor.visitChildren(self) def dimensions(self): localctx = NeuralogicParser.DimensionsContext(self, self._ctx, self.state) self.enterRule(localctx, 56, self.RULE_dimensions) self._la = 0 # Token type try: self.enterOuterAlt(localctx, 1) self.state = 260 self.match(NeuralogicParser.LCURL) self.state = 261 self.number() self.state = 266 self._errHandler.sync(self) _la = self._input.LA(1) while _la == NeuralogicParser.COMMA: self.state = 262 self.match(NeuralogicParser.COMMA) self.state = 263 self.number() self.state = 268 self._errHandler.sync(self) _la = self._input.LA(1) self.state = 269 self.match(NeuralogicParser.RCURL) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx class NegationContext(ParserRuleContext): def __init__( self, parser, parent: ParserRuleContext = None, invokingState: int = -1 ): super().__init__(parent, invokingState) self.parser = parser def NEGATION(self): return self.getToken(NeuralogicParser.NEGATION, 0) def getRuleIndex(self): return NeuralogicParser.RULE_negation def enterRule(self, listener: ParseTreeListener): if hasattr(listener, "enterNegation"): listener.enterNegation(self) def exitRule(self, listener: ParseTreeListener): if hasattr(listener, "exitNegation"): listener.exitNegation(self) def accept(self, visitor: ParseTreeVisitor): if hasattr(visitor, "visitNegation"): return visitor.visitNegation(self) else: return visitor.visitChildren(self) def negation(self): localctx = NeuralogicParser.NegationContext(self, self._ctx, self.state) self.enterRule(localctx, 58, self.RULE_negation) try: self.enterOuterAlt(localctx, 1) self.state = 271 self.match(NeuralogicParser.NEGATION) except RecognitionException as re: localctx.exception = re self._errHandler.reportError(self, re) self._errHandler.recover(self, re) finally: self.exitRule() return localctx
mavaddat/yori
ypm/download.c
/** * @file ypm/download.c * * Yori shell package manager download packages for later/offline installation * * Copyright (c) 2018-2021 <NAME> * * 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 <yoripch.h> #include <yorilib.h> #include <yoripkg.h> #include "ypm.h" /** Help text to display to the user. */ const CHAR strYpmDownloadHelpText[] = "\n" "Download packages for later or offline installation.\n" "\n" "YPM [-license]\n" "YPM -download <source> <target>\n" "\n" " <source> Specifies a URL root to download from\n" " <target> Specifies a directory to download to\n"; /** Help text to display to the user. */ const CHAR strYpmDownloadDailyHelpText[] = "\n" "Download latest daily packages for later or offline installation.\n" "\n" "YPM [-license]\n" "YPM -download-daily <target>\n" "\n" " <target> Specifies a directory to download to\n"; /** Help text to display to the user. */ const CHAR strYpmDownloadStableHelpText[] = "\n" "Download latest stable packages for later or offline installation.\n" "\n" "YPM [-license]\n" "YPM -download-stable <target>\n" "\n" " <target> Specifies a directory to download to\n"; /** Display usage text to the user. */ BOOL YpmDownloadHelp(VOID) { YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Ypm %i.%02i\n"), YORI_VER_MAJOR, YORI_VER_MINOR); #if YORI_BUILD_ID YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T(" Build %i\n"), YORI_BUILD_ID); #endif YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%hs"), strYpmDownloadHelpText); return TRUE; } /** Display usage text to the user. */ BOOL YpmDownloadDailyHelp(VOID) { YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Ypm %i.%02i\n"), YORI_VER_MAJOR, YORI_VER_MINOR); #if YORI_BUILD_ID YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T(" Build %i\n"), YORI_BUILD_ID); #endif YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%hs"), strYpmDownloadDailyHelpText); return TRUE; } /** Display usage text to the user. */ BOOL YpmDownloadStableHelp(VOID) { YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Ypm %i.%02i\n"), YORI_VER_MAJOR, YORI_VER_MINOR); #if YORI_BUILD_ID YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T(" Build %i\n"), YORI_BUILD_ID); #endif YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%hs"), strYpmDownloadStableHelpText); return TRUE; } /** Download packages for later or offline installation. @param ArgC The number of arguments. @param ArgV An array of arguments. @return Exit code of the process. */ DWORD YpmDownload( __in DWORD ArgC, __in YORI_STRING ArgV[] ) { BOOL ArgumentUnderstood; DWORD i; DWORD StartArg = 0; YORI_STRING Arg; PYORI_STRING SourcePath = NULL; PYORI_STRING FilePath = NULL; if (ArgC < 3) { YpmDownloadHelp(); return EXIT_FAILURE; } SourcePath = &ArgV[1]; FilePath = &ArgV[2]; for (i = 3; i < ArgC; i++) { ArgumentUnderstood = FALSE; ASSERT(YoriLibIsStringNullTerminated(&ArgV[i])); if (YoriLibIsCommandLineOption(&ArgV[i], &Arg)) { if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("?")) == 0) { YpmDownloadHelp(); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("license")) == 0) { YoriLibDisplayMitLicense(_T("2017-2021")); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("-")) == 0) { ArgumentUnderstood = TRUE; StartArg = i + 1; break; } } else { ArgumentUnderstood = TRUE; StartArg = i; break; } if (!ArgumentUnderstood) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Argument not understood, ignored: %y\n"), &ArgV[i]); } } YoriPkgDownloadRemotePackages(SourcePath, FilePath); return EXIT_SUCCESS; } /** Download the latest daily packages for later or offline installation. @param ArgC The number of arguments. @param ArgV An array of arguments. @return Exit code of the process. */ DWORD YpmDownloadDaily( __in DWORD ArgC, __in YORI_STRING ArgV[] ) { BOOL ArgumentUnderstood; DWORD i; DWORD StartArg = 0; YORI_STRING Arg; YORI_STRING SourcePath; PYORI_STRING FilePath = NULL; if (ArgC < 2) { YpmDownloadDailyHelp(); return EXIT_FAILURE; } FilePath = &ArgV[1]; YoriLibConstantString(&SourcePath, _T("http://www.malsmith.net/download/?obj=yori/latest-daily/")); for (i = 2; i < ArgC; i++) { ArgumentUnderstood = FALSE; ASSERT(YoriLibIsStringNullTerminated(&ArgV[i])); if (YoriLibIsCommandLineOption(&ArgV[i], &Arg)) { if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("?")) == 0) { YpmDownloadDailyHelp(); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("license")) == 0) { YoriLibDisplayMitLicense(_T("2017-2021")); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("-")) == 0) { ArgumentUnderstood = TRUE; StartArg = i + 1; break; } } else { ArgumentUnderstood = TRUE; StartArg = i; break; } if (!ArgumentUnderstood) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Argument not understood, ignored: %y\n"), &ArgV[i]); } } YoriPkgDownloadRemotePackages(&SourcePath, FilePath); return EXIT_SUCCESS; } /** Download the latest stable packages for later or offline installation. @param ArgC The number of arguments. @param ArgV An array of arguments. @return Exit code of the process. */ DWORD YpmDownloadStable( __in DWORD ArgC, __in YORI_STRING ArgV[] ) { BOOL ArgumentUnderstood; DWORD i; DWORD StartArg = 0; YORI_STRING Arg; YORI_STRING SourcePath; PYORI_STRING FilePath = NULL; if (ArgC < 2) { YpmDownloadStableHelp(); return EXIT_FAILURE; } FilePath = &ArgV[1]; YoriLibConstantString(&SourcePath, _T("http://www.malsmith.net/download/?obj=yori/latest-stable/")); for (i = 2; i < ArgC; i++) { ArgumentUnderstood = FALSE; ASSERT(YoriLibIsStringNullTerminated(&ArgV[i])); if (YoriLibIsCommandLineOption(&ArgV[i], &Arg)) { if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("?")) == 0) { YpmDownloadStableHelp(); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("license")) == 0) { YoriLibDisplayMitLicense(_T("2017-2021")); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("-")) == 0) { ArgumentUnderstood = TRUE; StartArg = i + 1; break; } } else { ArgumentUnderstood = TRUE; StartArg = i; break; } if (!ArgumentUnderstood) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Argument not understood, ignored: %y\n"), &ArgV[i]); } } YoriPkgDownloadRemotePackages(&SourcePath, FilePath); return EXIT_SUCCESS; } // vim:sw=4:ts=4:et:
Tomay0/PixelProtect
src/main/java/nz/tomay0/PixelProtect/command/AbstractCommand.java
package nz.tomay0.PixelProtect.command; import net.milkbowl.vault.economy.Economy; import nz.tomay0.PixelProtect.dynmap.DynmapHandler; import nz.tomay0.PixelProtect.PixelProtectPlugin; import nz.tomay0.PixelProtect.playerstate.PlayerStateHandler; import nz.tomay0.PixelProtect.protection.ProtectionHandler; import org.bukkit.command.CommandSender; /** * An abstract protection command */ public abstract class AbstractCommand { private PixelProtectPlugin plugin; /** * Create new abstract command with a protection handler * * @param plugin plugin */ public AbstractCommand(PixelProtectPlugin plugin) { this.plugin = plugin; } /** * Get the protection handler * * @return */ protected ProtectionHandler getProtections() { return plugin.getProtections(); } /** * Get the confirmation handler * * @return */ protected PlayerStateHandler getPlayerStateHandler() { return plugin.getPlayerStateHandler(); } /** * Get the economy */ protected Economy getEconomy() { return plugin.getEconomy(); } /** * Get the plugin * * @return */ protected PixelProtectPlugin getPlugin() { return plugin; } /** * Get command label. * * @return string */ public abstract String getCommand(); /** * Return if the command can be used by console. * * @return */ public abstract boolean getConsole(); /** * Get a short description of the command, used for the /pr help menu * * @return */ public abstract String getDescription(); /** * Get permissions required to execute the command * * @return */ public String getPermission() { return null; } /** * When you type the command * * @param sender sender, either a player or the console * @param args arguments, first should always be the command label */ public abstract void onCommand(CommandSender sender, String[] args); }
klahnakoski/auth0-api
vendor/pyLibrary/env/git.py
<reponame>klahnakoski/auth0-api<filename>vendor/pyLibrary/env/git.py<gh_stars>0 # encoding: utf-8 # # # 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/. # # Author: <NAME> (<EMAIL>) # from __future__ import absolute_import, division, unicode_literals from mo_logs.exceptions import suppress_exception from mo_threads import Process, THREAD_STOP from pyLibrary.meta import cache @cache def get_revision(): """ GET THE CURRENT GIT REVISION """ proc = Process("git log", ["git", "log", "-1"]) try: for line in proc.stdout: if line.startswith("commit "): return line[7:] finally: with suppress_exception: proc.join() @cache def get_remote_revision(url, branch): """ GET REVISION OF A REMOTE BRANCH """ proc = Process("git remote revision", ["git", "ls-remote", url, "refs/heads/" + branch]) try: for line in proc.stdout: line = line.strip() if not line: continue return line.split("\t")[0] finally: try: proc.join() except Exception: pass @cache def get_branch(): """ GET THE CURRENT GIT BRANCH """ proc = Process("git status", ["git", "status"]) try: for line in proc.stdout: if line.startswith("On branch "): return line[10:] finally: try: proc.join() except Exception: pass
phatblat/macOSPrivateFrameworks
PrivateFrameworks/OfficeImport/OAVTextBodyProperties.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" __attribute__((visibility("hidden"))) @interface OAVTextBodyProperties : NSObject { } + (void)readFromManager:(id)arg1 toShape:(id)arg2 state:(id)arg3; + (unsigned char)flowTypeWithLayoutFlowString:(id)arg1 altLayoutFlowString:(id)arg2; + (int)readAnchor:(id)arg1; + (int)readWrapStyle:(id)arg1; + (int)readRotation:(id)arg1; @end
JLLeitschuh/SocialSDK
php/moodle-block/src/views/js/globalPluginSettingsEditor.js
<filename>php/moodle-block/src/views/js/globalPluginSettingsEditor.js /** * (C) Copyright IBM Corp. 2012 * * 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. */ /** * @author <NAME> */ window.onload = function() { var authType = document.getElementById('id_s__auth_type'); var basicAuthMethod = document.getElementById('id_s__basic_auth_method'); if (authType != null) { authType.addEventListener( "change", authTypeChange, false ); authTypeChange(); } if (basicAuthMethod != null) { basicAuthMethod.addEventListener( "change", basicAuthMethodChange, false ); authTypeChange(); basicAuthMethodChange(); } } function basicAuthMethodChange() { var auth_method_list = document.getElementById("id_s__basic_auth_method"); var selected_auth_method = auth_method_list.options[auth_method_list.selectedIndex].value; var labels = document.getElementsByTagName('label'); if (selected_auth_method == 'prompt' || selected_auth_method == 'profile') { var el = document.getElementById('id_s__basic_auth_username').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__basic_auth_password').parentNode; el.parentNode.style.display = "none"; for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == 'id_s__basic_auth_password' || labels[i].htmlFor == 'id_s__basic_auth_username') { labels[i].parentNode.style.display = 'none'; } } } else { var el = document.getElementById('id_s__basic_auth_username').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__basic_auth_password').parentNode; el.parentNode.style.display = "block"; for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == 'id_s__basic_auth_password' || labels[i].htmlFor == 'id_s__basic_auth_username') { labels[i].parentNode.style.display = 'block'; } } } } function authTypeChange() { var auth_list = document.getElementById("id_s__auth_type"); var selected_auth = auth_list.options[auth_list.selectedIndex].value; var visibleSectionID = ''; var invisibleSectionID = ''; if (selected_auth == 'basic') { visibleSectionID = 'ibm-sbtk-basic-auth-admin-section'; invisibleSectionID = 'ibm-sbtk-oauth-admin-section'; var el = document.getElementById('id_s__server_url').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__basic_auth_username').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__basic_auth_method').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__basic_auth_password').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__o_auth_server_url').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__consumer_key').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__consumer_secret').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__request_token_url').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__authorization_url').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__access_token_url').parentNode; el.parentNode.style.display = "none"; var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == 'id_s__access_token_url' || labels[i].htmlFor == 'id_s__authorization_url' || labels[i].htmlFor == 'id_s__request_token_url' || labels[i].htmlFor == 'id_s__consumer_secret' || labels[i].htmlFor == 'id_s__consumer_key' || labels[i].htmlFor == 'id_s__o_auth_server_url') { labels[i].parentNode.style.display = 'none'; } else if (labels[i].htmlFor == 'id_s__server_url' || labels[i].htmlFor == 'id_s__basic_auth_username' || labels[i].htmlFor == 'id_s__basic_auth_password' || labels[i].htmlFor == 'id_s__basic_auth_method') { labels[i].parentNode.style.display = 'block'; } } } else if (selected_auth == 'oauth1') { visibleSectionID = 'ibm-sbtk-oauth-admin-section'; invisibleSectionID = 'ibm-sbtk-basic-auth-admin-section'; el = document.getElementById('id_s__o_auth_server_url').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__consumer_key').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__consumer_secret').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__request_token_url').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__authorization_url').parentNode; el.parentNode.style.display = "block"; el = document.getElementById('id_s__access_token_url').parentNode; el.parentNode.style.display = "block"; var el = document.getElementById('id_s__server_url').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__basic_auth_username').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__basic_auth_password').parentNode; el.parentNode.style.display = "none"; el = document.getElementById('id_s__basic_auth_method').parentNode; el.parentNode.style.display = "none"; var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == 'id_s__access_token_url' || labels[i].htmlFor == 'id_s__authorization_url' || labels[i].htmlFor == 'id_s__request_token_url' || labels[i].htmlFor == 'id_s__consumer_secret' || labels[i].htmlFor == 'id_s__consumer_key' || labels[i].htmlFor == 'id_s__o_auth_server_url') { labels[i].parentNode.style.display = 'block'; } else if (labels[i].htmlFor == 'id_s__server_url' || labels[i].htmlFor == 'id_s__basic_auth_username' || labels[i].htmlFor == 'id_s__basic_auth_password' || labels[i].htmlFor == 'id_s__basic_auth_method') { labels[i].parentNode.style.display = 'none'; } } } var visibleSection = document.getElementById(visibleSectionID).parentNode; visibleSection.style.display = "block"; var invisibleSection = document.getElementById(invisibleSectionID).parentNode; invisibleSection.style.display = "none"; }
wolfs/spray
spray-httpx/src/main/scala/spray/httpx/Json4sSupport.scala
/* * Copyright (C) 2011-2012 spray.io * * 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 spray.httpx import org.json4s.native.Serialization import org.json4s.Formats import spray.httpx.marshalling.{ Marshaller, MetaMarshallers } import spray.httpx.unmarshalling.Unmarshaller import spray.http._ import MediaTypes._ trait Json4sSupport extends MetaMarshallers { /** * Supplies the serialization and deserialization formats for JSON4s. * * proper usage * formats = DefaultFormats(NoTypeHints) * if you want extra support add json4s-ext to dependencies and add * * all examples taken from json4s.org site: * Scala enums * implicit val formats = org.json4s.DefaultFormats + new org.json4s.ext.EnumSerializer(MyEnum) * or for enum names * implicit val formats = org.json4s.DefaultFormats + new org.json4s.ext.EnumNameSerializer(MyEnum) * Joda Time * implicit val formats = org.json4s.DefaultFormats ++ org.json4s.ext.JodaTimeSerializers.all */ implicit def json4sFormats: Formats implicit def json4sUnmarshaller[T: Manifest] = Unmarshaller[T](`application/json`) { case x: HttpBody ⇒ Serialization.read[T](x.asString(defaultCharset = HttpCharsets.`UTF-8`)) } implicit def json4sMarshaller[T <: AnyRef] = Marshaller.delegate[T, String](ContentType.`application/json`)(Serialization.write(_)) }
418sec/brewser
lib/brewser/model/fermentable.rb
<filename>lib/brewser/model/fermentable.rb module Brewser class Fermentable < Model belongs_to :recipe property :name, String, :required => true property :origin, String, :length => 512 property :supplier, String, :length => 512 property :description, String, :length => 65535 property :type, String, :set => ['Grain', 'Sugar', 'Extract', 'Dry Extract', 'Adjunct'], :required => true property :yield_percent, Float property :potential, Float, :required => true property :color, Float, :required => true property :amount, Weight, :required => true property :late_addition?, Boolean, :default => false property :coarse_fine_diff, Float property :moisture, Float property :diastatic_power, Float property :protein, Float property :max_in_batch, Float property :recommend_mash?, Boolean property :ibu_gal_per_lb, Float def ppg return 0 if potential.blank? (potential-1)*1000 end def self.json_create(o) a = self.new a.name = o['name'] a.origin = o['origin'] a.supplier = o['supplier'] a.description = o['description'] a.type = o['type'] a.potential = o['potential'] a.color = o['color'] a.amount = o['amount'].u unless o['amount'].blank? a.late_addition = o['added_late'] a.coarse_fine_diff = o['coarse_fine_diff'] a.moisture = o['moisture'] a.diastatic_power = o['diastatic_power'] a.protein = o['protein'] a.max_in_batch = o['max_in_batch'] a.origin = o['origin'] a.recommend_mash = o['recommend_mash'] a.ibu_gal_per_lb = o['ibu_gal_per_lb'] return a end def as_json(options={}) { JSON.create_id => "Brewser::Fermentable", 'name' => name, 'origin' => origin, 'supplier' => supplier, 'description' => description, 'type' => type, 'ppg' => ppg, 'potential' => potential, 'color' => color, 'amount' => amount.to_s, 'added_late' => late_addition?, 'coarse_fine_diff' => coarse_fine_diff, 'moisture' => moisture, 'diastatic_power' => diastatic_power, 'protein' => protein, 'max_in_batch' => max_in_batch, 'recommend_mash' => recommend_mash?, 'ibu_gal_per_lb' => ibu_gal_per_lb } end end end
turgu1/ESP-IDF-Inkplate
include/drivers/touch_screen.hpp
<filename>include/drivers/touch_screen.hpp #pragma once #if defined(INKPLATE_6PLUS) #include "non_copyable.hpp" #include "mcp23017.hpp" #include <array> class TouchScreen : NonCopyable { public: TouchScreen(MCP23017 & _mcp) : mcp(_mcp), ready(false) {} typedef void (* ISRHandlerPtr)(void * value); static const gpio_num_t INTERRUPT_PIN = GPIO_NUM_36; typedef std::array<uint16_t, 2> TouchPositions; bool setup(bool power_on, ISRHandlerPtr isr_handler = nullptr); void shutdown(); bool is_screen_touched(); uint8_t get_position(TouchPositions & x_positions, TouchPositions & y_positions); void set_power_state(bool on_state); bool get_power_state(); bool is_ready() { return ready; } void set_app_isr_handler(ISRHandlerPtr isr_handler); inline uint16_t get_x_resolution() { return x_resolution; } inline uint16_t get_y_resolution() { return y_resolution; } private: static constexpr char const * TAG = "TouchScreen"; MCP23017 & mcp; uint16_t x_resolution, y_resolution; const MCP23017::Pin TOUCHSCREEN_ENABLE = MCP23017::Pin::IOPIN_12; const MCP23017::Pin TOUCHSCREEN_RESET = MCP23017::Pin::IOPIN_10; static const uint8_t TOUCHSCREEN_ADDRESS = 0x15; typedef std::array<uint8_t, 4> Data; typedef std::array<uint8_t, 8> Data8; bool ready; void hardware_reset(); bool software_reset(); bool read( Data & data); bool read( Data8 & data); void write(const Data & data); void retrieve_resolution(); }; #endif
duncte123/weeb.java
src/main/java/me/duncte123/weebJava/configs/base/HasHiddenAndNsfwMode.java
<reponame>duncte123/weeb.java /* * Copyright 2018 - 2020 <NAME> * * 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 me.duncte123.weebJava.configs.base; import me.duncte123.weebJava.types.HiddenMode; import me.duncte123.weebJava.types.NSFWMode; import javax.annotation.Nullable; public abstract class HasHiddenAndNsfwMode { private final HiddenMode hiddenMode; private final NSFWMode nsfwMode; public HasHiddenAndNsfwMode(HiddenMode hiddenMode, NSFWMode nsfwMode) { this.hiddenMode = hiddenMode; this.nsfwMode = nsfwMode; } /** * Returns the current nsfw mode * * @return the current nsfw mode */ @Nullable public NSFWMode getNsfwMode() { return nsfwMode; } /** * Returns the current hidden mode * * @return the current hidden mode */ @Nullable public HiddenMode getHiddenMode() { return hiddenMode; } @SuppressWarnings({"rawtypes", "unchecked"}) public abstract static class Builder<B extends Builder, T> { protected HiddenMode hiddenMode; protected NSFWMode nsfwMode; /** * Sets the current hidden mode for the request * * @param hiddenMode * When {@link HiddenMode#HIDE} you only get public images, {@link HiddenMode#ONLY} will only give you * hidden images uploaded by yourself, the default version is {@code null} or {@link HiddenMode#DEFAULT} * * @return The current builder, useful for chaining */ public B setHiddenMode(@Nullable HiddenMode hiddenMode) { this.hiddenMode = hiddenMode; return (B) this; } /** * Sets the current nsfw mode for the request * * @param nsfwMode * When {@link NSFWMode#DISALLOW_NSFW}, no types from nsfw images will be returned, {@link * NSFWMode#ALLOW_NSFW} returns types from nsfw and non-nsfw images, {@link NSFWMode#ONLY_NSFW} returns * only types from nsfw images * * @return The current builder, useful for chaining */ public B setNsfwMode(@Nullable NSFWMode nsfwMode) { this.nsfwMode = nsfwMode; return (B) this; } /** * Builds the object and returns it * * @return The object from this builder */ public abstract T build(); } }
InNoHurryToCode/xray-162
code/engine/xrPhysics/PHInterpolation.h
<filename>code/engine/xrPhysics/PHInterpolation.h #include "CycleConstStorage.h" #ifndef PHINTERPOLATON_H #define PHINTERPOLATON_H //#include "ode_include.h" #include "ode/include/ode/common.h" class CPHInterpolation { public: CPHInterpolation(); void SetBody(dBodyID body); static const u16 PH_INTERPOLATION_POINTS = 2; void InterpolatePosition(Fvector& pos); void InterpolateRotation(Fmatrix& rot); void UpdatePositions(); void UpdateRotations(); void ResetPositions(); void ResetRotations(); void GetRotation(Fquaternion& q, u16 num); void GetPosition(Fvector& p, u16 num); void SetRotation(const Fquaternion& q, u16 num); void SetPosition(const Fvector& p, u16 num); private: dBodyID m_body; CCycleConstStorage<Fvector, PH_INTERPOLATION_POINTS> qPositions; CCycleConstStorage<Fquaternion, PH_INTERPOLATION_POINTS> qRotations; }; #endif
ChSt98/KraftPad
lib/SX12XX-LoRa-master/examples/SX128x_examples/Tracker/24_GPS_Tracker_Receiver/Settings.h
/******************************************************************************************************* Programs for Arduino - Copyright of the author <NAME> - 22/03/20 This program is supplied as is, it is up to the user of the program to decide if the program is suitable for the intended purpose and free from errors. *******************************************************************************************************/ /******************************************************************************************************* Program Operation - Serial monitor baud rate is set at 9600. *******************************************************************************************************/ //******* Setup hardware pin definitions here ! *************** //These are the pin definitions for one of my own boards, the Easy Pro Mini, //be sure to change the definitiosn to match your own setup. #define NSS 10 //select on LoRa device #define NRESET 9 //reset on LoRa device #define RFBUSY 7 //SX128X busy pin #define DIO1 3 //DIO1 on LoRa device, used for RX and TX done #define RX_EN -1 //pin for RX enable, used on some SX1280 devices, set to -1 if not used #define TX_EN -1 //pin for TX enable, used on some SX1280 devices, set to -1 if not used #define LED1 8 //On board LED, high for on #define BUZZER -1 //Buzzer if fitted, high for on. Set to -1 if not used #define LORA_DEVICE DEVICE_SX1280 //this is the device we are using //******* Setup LoRa Test Parameters Here ! *************** //LoRa Modem Parameters const uint32_t Frequency = 2445000000; //frequency of transmissions const int32_t Offset = 0; //offset frequency for calibration purposes const uint8_t Bandwidth = LORA_BW_0200; //LoRa bandwidth const uint8_t SpreadingFactor = LORA_SF12; //LoRa spreading factor const uint8_t CodeRate = LORA_CR_4_5; //LoRa coding rate
ralphmarchildon-wf/crnk-framework
crnk-setup/crnk-setup-rs/src/main/java/io/crnk/rs/type/JsonApiMediaType.java
<reponame>ralphmarchildon-wf/crnk-framework<gh_stars>100-1000 package io.crnk.rs.type; import javax.ws.rs.core.MediaType; public final class JsonApiMediaType { private JsonApiMediaType() { // private since only a util } /** * A {@code String} constant representing {@value #APPLICATION_JSON_API} media type. */ public final static String APPLICATION_JSON_API = "application/vnd.api+json"; /** * A {@link MediaType} constant representing {@value #APPLICATION_JSON_API} media type. */ public final static MediaType APPLICATION_JSON_API_TYPE = new MediaType("application", "vnd.api+json"); }
JiaoXianjun/free5GRAN
lib/asn1c/nr_rrc/InterFreqCarrierFreqInfo.h
<filename>lib/asn1c/nr_rrc/InterFreqCarrierFreqInfo.h /* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NR-RRC-Definitions" * found in "fixed_grammar.asn" * `asn1c -gen-PER -fcompound-names -findirect-choice -no-gen-example` */ #ifndef _InterFreqCarrierFreqInfo_H_ #define _InterFreqCarrierFreqInfo_H_ #include "asn_application.h" /* Including external dependencies */ #include "ARFCN-ValueNR.h" #include "NativeInteger.h" #include "SubcarrierSpacing.h" #include "BOOLEAN.h" #include "Q-RxLevMin.h" #include "Q-QualMin.h" #include "P-Max.h" #include "T-Reselection.h" #include "ReselectionThreshold.h" #include "CellReselectionPriority.h" #include "CellReselectionSubPriority.h" #include "Q-OffsetRange.h" #include "ReselectionThresholdQ.h" #include "constr_SEQUENCE.h" #ifdef __cplusplus extern "C" { #endif /* Forward declarations */ struct MultiFrequencyBandListNR_SIB; struct ThresholdNR; struct SSB_MTC; struct SSB_ToMeasure; struct SS_RSSI_Measurement; struct SpeedStateScaleFactors; struct InterFreqNeighCellList; struct InterFreqBlackCellList; /* InterFreqCarrierFreqInfo */ typedef struct InterFreqCarrierFreqInfo { ARFCN_ValueNR_t dl_CarrierFreq; struct MultiFrequencyBandListNR_SIB *frequencyBandList; /* OPTIONAL */ struct MultiFrequencyBandListNR_SIB *frequencyBandListSUL; /* OPTIONAL */ long *nrofSS_BlocksToAverage; /* OPTIONAL */ struct ThresholdNR *absThreshSS_BlocksConsolidation; /* OPTIONAL */ struct SSB_MTC *smtc; /* OPTIONAL */ SubcarrierSpacing_t ssbSubcarrierSpacing; struct SSB_ToMeasure *ssb_ToMeasure; /* OPTIONAL */ BOOLEAN_t deriveSSB_IndexFromCell; struct SS_RSSI_Measurement *ss_RSSI_Measurement; /* OPTIONAL */ Q_RxLevMin_t q_RxLevMin; Q_RxLevMin_t *q_RxLevMinSUL; /* OPTIONAL */ Q_QualMin_t *q_QualMin; /* OPTIONAL */ P_Max_t *p_Max; /* OPTIONAL */ T_Reselection_t t_ReselectionNR; struct SpeedStateScaleFactors *t_ReselectionNR_SF; /* OPTIONAL */ ReselectionThreshold_t threshX_HighP; ReselectionThreshold_t threshX_LowP; struct InterFreqCarrierFreqInfo__threshX_Q { ReselectionThresholdQ_t threshX_HighQ; ReselectionThresholdQ_t threshX_LowQ; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } *threshX_Q; CellReselectionPriority_t *cellReselectionPriority; /* OPTIONAL */ CellReselectionSubPriority_t *cellReselectionSubPriority; /* OPTIONAL */ Q_OffsetRange_t *q_OffsetFreq; /* DEFAULT 15 */ struct InterFreqNeighCellList *interFreqNeighCellList; /* OPTIONAL */ struct InterFreqBlackCellList *interFreqBlackCellList; /* OPTIONAL */ /* * This type is extensible, * possible extensions are below. */ /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } InterFreqCarrierFreqInfo_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_InterFreqCarrierFreqInfo; extern asn_SEQUENCE_specifics_t asn_SPC_InterFreqCarrierFreqInfo_specs_1; extern asn_TYPE_member_t asn_MBR_InterFreqCarrierFreqInfo_1[24]; #ifdef __cplusplus } #endif /* Referred external types */ #include "MultiFrequencyBandListNR-SIB.h" #include "ThresholdNR.h" #include "SSB-MTC.h" #include "SSB-ToMeasure.h" #include "SS-RSSI-Measurement.h" #include "SpeedStateScaleFactors.h" #include "InterFreqNeighCellList.h" #include "InterFreqBlackCellList.h" #endif /* _InterFreqCarrierFreqInfo_H_ */ #include "asn_internal.h"
alrs/mortar
middleware/interceptors/client/headers.go
package client import ( "context" "strings" "github.com/go-masonry/mortar/interfaces/cfg" "github.com/go-masonry/mortar/mortar" "go.uber.org/fx" "google.golang.org/grpc" "google.golang.org/grpc/metadata" ) type copyHeadersDeps struct { fx.In Config cfg.Config } // CopyGRPCHeadersClientInterceptor copies filtered Headers found in the Incoming metadata.MD to the Outgoing one. // // This is useful if you want to propagate them to the next service when using grpc Client func CopyGRPCHeadersClientInterceptor(deps copyHeadersDeps) grpc.UnaryClientInterceptor { return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { if md, ok := metadata.FromIncomingContext(ctx); ok { headerPrefixes := deps.Config.Get(mortar.MiddlewareServerGRPCCopyHeadersPrefixes).StringSlice() for _, headerPrefix := range headerPrefixes { for k, vs := range md { if strings.HasPrefix(strings.ToLower(k), headerPrefix) { for _, v := range vs { ctx = metadata.AppendToOutgoingContext(ctx, k, v) } } } } } return invoker(ctx, method, req, reply, cc, opts...) } } // TODO Add http Client Interceptor that copies selected fields to HTTP Request Headers so they will propagate to the next REST service // TODO Add http Client Interceptor that dumps request and response to log
minux/llgo
llgo/testdata/unsafe/offsetof.go
<reponame>minux/llgo package main import "unsafe" type S struct { a int16 b int32 c int8 d int64 } func main() { var s S println(unsafe.Offsetof(s.a)) println(unsafe.Offsetof(s.b)) println(unsafe.Offsetof(s.c)) println(unsafe.Offsetof(s.d)) }
webschik/preact
test/browser/isValidElement.test.js
<filename>test/browser/isValidElement.test.js import { createElement, isValidElement, Component } from 'preact'; import { isValidElementTests } from '../shared/isValidElementTests'; isValidElementTests(expect, isValidElement, createElement, Component);
OLR-xray/OLR-3.0
src/xray/xr_3da/xrGame/Bolt.cpp
<filename>src/xray/xr_3da/xrGame/Bolt.cpp #include "stdafx.h" #include "bolt.h" #include "ParticlesObject.h" #include "PhysicsShell.h" #include "xr_level_controller.h" #include "Actor.h" #include "../../build_config_defines.h" CBolt::CBolt(void) { m_weight = .1f; SetSlot (BOLT_SLOT); m_flags.set (Fruck, FALSE); m_thrower_id =u16(-1); } CBolt::~CBolt(void) { } void CBolt::OnH_A_Chield() { inherited::OnH_A_Chield(); CObject* o= H_Parent()->H_Parent(); if(o)SetInitiator(o->ID()); } void CBolt::OnEvent(NET_Packet& P, u16 type) { inherited::OnEvent(P,type); } bool CBolt::Activate() { Show(); return true; } void CBolt::Deactivate() { Hide(); } void CBolt::Throw() { CMissile *l_pBolt = smart_cast<CMissile*>(m_fake_missile); if(!l_pBolt) return; l_pBolt->set_destroy_time (u32(m_dwDestroyTimeMax/phTimefactor)); inherited::Throw (); spawn_fake_missile (); } bool CBolt::Useful() const { return false; } bool CBolt::Action(s32 cmd, u32 flags) { if(inherited::Action(cmd, flags)) return true; /* switch(cmd) { case kDROP: { if(flags&CMD_START) { m_throw = false; if(State() == MS_IDLE) State(MS_THREATEN); } else if(State() == MS_READY || State() == MS_THREATEN) { m_throw = true; if(State() == MS_READY) State(MS_THROW); } } return true; } */ return false; } void CBolt::Destroy() { inherited::Destroy(); } void CBolt::activate_physic_shell () { inherited::activate_physic_shell (); m_pPhysicsShell->SetAirResistance (.0001f); } void CBolt::SetInitiator (u16 id) { m_thrower_id=id; } u16 CBolt::Initiator () { return m_thrower_id; }
yaoyang4346/DesignPattern
src/VisitorPattern/Visitor.java
package VisitorPattern; /** * Created by cheny on 2018/5/12. */ interface Visitor { void visit(ElementA e); void visit(ElementB e); }
iilab/expo
ios/Exponent/Versioned/Core/Internal/EXResourceLoader.h
// Copyright 2015-present 650 Industries. All rights reserved. #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN /** * This is the versioned protocol for EXCachedResource, this also defines some * of the types used when interacting with EXCachedResource instances. This is * used with the EXCachedResourceManager service to be able to create EXCachedResource * instances in versioned code. * * **Avoid making breaking changes to this and if you do make sure to edit all * versions of this file.** */ @interface EXLoadingProgress : NSObject @property (nonatomic, copy) NSString *status; @property (nonatomic, strong) NSNumber *done; @property (nonatomic, strong) NSNumber *total; @end typedef void (^EXCachedResourceSuccessBlock)(NSData *data); typedef void (^EXCachedResourceErrorBlock)(NSError *error); typedef void (^EXCachedResourceProgressBlock)(EXLoadingProgress *progress); typedef enum EXCachedResourceBehavior { // load the resource without using any cache. EXCachedResourceNoCache, // load the resource without reading from the cache, but still write the loaded resource to the cache. EXCachedResourceWriteToCache, // return immediately with cached data if it exists, then try to download the resource and replace the cache in the background. EXCachedResourceUseCacheImmediately, // return immediately with cached data if it exists, and only try to download the resource if cached data is not found. EXCachedResourceFallBackToNetwork, // try to download the resource, but fall back to the cached version if the download fails. EXCachedResourceFallBackToCache, // use a cache if it exists, otherwise fail. (don't download anything) EXCachedResourceOnlyCache, } EXCachedResourceBehavior; @protocol EXResourceLoader - (void)loadResourceWithBehavior:(EXCachedResourceBehavior)behavior progressBlock:(__nullable EXCachedResourceProgressBlock)progressBlock successBlock:(EXCachedResourceSuccessBlock)successBlock errorBlock:(EXCachedResourceErrorBlock)errorBlock; @end NS_ASSUME_NONNULL_END
leiphp/gulimall
gulimall-product/src/main/java/cn/lxtkj/gulimall/product/dao/CategoryDao.java
package cn.lxtkj.gulimall.product.dao; import cn.lxtkj.gulimall.product.entity.CategoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 商品三级分类 * * @author leixiaotian * @email <EMAIL> * @date 2021-08-12 00:20:21 */ @Mapper public interface CategoryDao extends BaseMapper<CategoryEntity> { }
UlaiS/exoplayer2
library/rtsp/src/main/java/com/upax/exoplayer2/source/rtsp/reader/RtpH264Reader.java
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.upax.exoplayer2.source.rtsp.reader; import static com.upax.exoplayer2.util.Assertions.checkNotNull; import static com.upax.exoplayer2.util.Assertions.checkStateNotNull; import static com.upax.exoplayer2.util.Util.castNonNull; import com.upax.exoplayer2.C; import com.upax.exoplayer2.ParserException; import com.upax.exoplayer2.extractor.ExtractorOutput; import com.upax.exoplayer2.extractor.TrackOutput; import com.upax.exoplayer2.source.rtsp.RtpPacket; import com.upax.exoplayer2.source.rtsp.RtpPayloadFormat; import com.upax.exoplayer2.util.Log; import com.upax.exoplayer2.util.NalUnitUtil; import com.upax.exoplayer2.util.ParsableByteArray; import com.upax.exoplayer2.util.Util; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.RequiresNonNull; /** Parses an H264 byte stream carried on RTP packets, and extracts H264 Access Units. */ /* package */ final class RtpH264Reader implements RtpPayloadReader { private static final String TAG = "RtpH264Reader"; private static final long MEDIA_CLOCK_FREQUENCY = 90_000; /** Offset of payload data within a FU type A payload. */ private static final int FU_PAYLOAD_OFFSET = 2; /** Single Time Aggregation Packet type A. */ private static final int RTP_PACKET_TYPE_STAP_A = 24; /** Fragmentation Unit type A. */ private static final int RTP_PACKET_TYPE_FU_A = 28; /** IDR NAL unit type. */ private static final int NAL_UNIT_TYPE_IDR = 5; /** Scratch for Fragmentation Unit RTP packets. */ private final ParsableByteArray fuScratchBuffer; private final ParsableByteArray nalStartCodeArray = new ParsableByteArray(NalUnitUtil.NAL_START_CODE); private final RtpPayloadFormat payloadFormat; private @MonotonicNonNull TrackOutput trackOutput; @C.BufferFlags private int bufferFlags; private long firstReceivedTimestamp; private int previousSequenceNumber; /** The combined size of a sample that is fragmented into multiple RTP packets. */ private int fragmentedSampleSizeBytes; private long startTimeOffsetUs; /** Creates an instance. */ public RtpH264Reader(RtpPayloadFormat payloadFormat) { this.payloadFormat = payloadFormat; fuScratchBuffer = new ParsableByteArray(); firstReceivedTimestamp = C.TIME_UNSET; previousSequenceNumber = C.INDEX_UNSET; } @Override public void createTracks(ExtractorOutput extractorOutput, int trackId) { trackOutput = extractorOutput.track(trackId, C.TRACK_TYPE_VIDEO); castNonNull(trackOutput).format(payloadFormat.format); } @Override public void onReceivingFirstPacket(long timestamp, int sequenceNumber) {} @Override public void consume(ParsableByteArray data, long timestamp, int sequenceNumber, boolean rtpMarker) throws ParserException { int rtpH264PacketMode; try { // RFC6184 Section 5.6, 5.7 and 5.8. rtpH264PacketMode = data.getData()[0] & 0x1F; } catch (IndexOutOfBoundsException e) { throw ParserException.createForMalformedManifest(/* message= */ null, e); } checkStateNotNull(trackOutput); if (rtpH264PacketMode > 0 && rtpH264PacketMode < 24) { processSingleNalUnitPacket(data); } else if (rtpH264PacketMode == RTP_PACKET_TYPE_STAP_A) { processSingleTimeAggregationPacket(data); } else if (rtpH264PacketMode == RTP_PACKET_TYPE_FU_A) { processFragmentationUnitPacket(data, sequenceNumber); } else { throw ParserException.createForMalformedManifest( String.format("RTP H264 packetization mode [%d] not supported.", rtpH264PacketMode), /* cause= */ null); } if (rtpMarker) { if (firstReceivedTimestamp == C.TIME_UNSET) { firstReceivedTimestamp = timestamp; } long timeUs = toSampleUs(startTimeOffsetUs, timestamp, firstReceivedTimestamp); trackOutput.sampleMetadata( timeUs, bufferFlags, fragmentedSampleSizeBytes, /* offset= */ 0, /* encryptionData= */ null); fragmentedSampleSizeBytes = 0; } previousSequenceNumber = sequenceNumber; } @Override public void seek(long nextRtpTimestamp, long timeUs) { firstReceivedTimestamp = nextRtpTimestamp; fragmentedSampleSizeBytes = 0; startTimeOffsetUs = timeUs; } // Internal methods. /** * Processes Single NAL Unit packet (RFC6184 Section 5.6). * * <p>Outputs the single NAL Unit (with start code prepended) to {@link #trackOutput}. Sets {@link * #bufferFlags} and {@link #fragmentedSampleSizeBytes} accordingly. */ @RequiresNonNull("trackOutput") private void processSingleNalUnitPacket(ParsableByteArray data) { // Example of a Single Nal Unit packet // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |F|NRI| Type | | // +-+-+-+-+-+-+-+-+ | // | | // | Bytes 2..n of a single NAL unit | // | | // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | :...OPTIONAL RTP padding | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ int numBytesInData = data.bytesLeft(); fragmentedSampleSizeBytes += writeStartCode(); trackOutput.sampleData(data, numBytesInData); fragmentedSampleSizeBytes += numBytesInData; int nalHeaderType = data.getData()[0] & 0x1F; bufferFlags = getBufferFlagsFromNalType(nalHeaderType); } /** * Processes STAP Type A packet (RFC6184 Section 5.7). * * <p>Outputs the received aggregation units (with start code prepended) to {@link #trackOutput}. * Sets {@link #bufferFlags} and {@link #fragmentedSampleSizeBytes} accordingly. */ @RequiresNonNull("trackOutput") private void processSingleTimeAggregationPacket(ParsableByteArray data) { // Example of an STAP-A packet. // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | RTP Header | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |STAP-A NAL HDR | NALU 1 Size | NALU 1 HDR | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | NALU 1 Data | // : : // + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | | NALU 2 Size | NALU 2 HDR | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | NALU 2 Data | // : : // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | :...OPTIONAL RTP padding | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // Skips STAP-A NAL HDR that has the NAL format |F|NRI|Type|, but with Type replaced by the // STAP-A type id (RTP_PACKET_TYPE_STAP_A). data.readUnsignedByte(); // Gets all NAL units until the remaining bytes are only enough to store an RTP padding. int nalUnitLength; while (data.bytesLeft() > 4) { nalUnitLength = data.readUnsignedShort(); fragmentedSampleSizeBytes += writeStartCode(); trackOutput.sampleData(data, nalUnitLength); fragmentedSampleSizeBytes += nalUnitLength; } // Treat Aggregated NAL units as non key frames. bufferFlags = 0; } /** * Processes Fragmentation Unit Type A packet (RFC6184 Section 5.8). * * <p>This method will be invoked multiple times to receive a single frame that is broken down * into a series of fragmentation units in multiple RTP packets. * * <p>Outputs the received fragmentation units (with start code prepended) to {@link * #trackOutput}. Sets {@link #bufferFlags} and {@link #fragmentedSampleSizeBytes} accordingly. */ @RequiresNonNull("trackOutput") private void processFragmentationUnitPacket(ParsableByteArray data, int packetSequenceNumber) { // FU-A mode packet layout. // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | FU indicator | FU header | | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | // | | // | FU payload | // | | // | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // | :...OPTIONAL RTP padding | // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // // FU Indicator FU Header // 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // |F|NRI| Type |S|E|R| Type | // +---------------+---------------+ // Indicator: Upper 3 bits are the same as NALU header, Type = 28 (FU-A type). // Header: Start/End/Reserved/Type. Type is same as NALU type. int fuIndicator = data.getData()[0]; int fuHeader = data.getData()[1]; int nalHeader = (fuIndicator & 0xE0) | (fuHeader & 0x1F); boolean isFirstFuPacket = (fuHeader & 0x80) > 0; boolean isLastFuPacket = (fuHeader & 0x40) > 0; if (isFirstFuPacket) { // Prepends starter code. fragmentedSampleSizeBytes += writeStartCode(); // The bytes needed is 1 (NALU header) + payload size. The original data array has size 2 (FU // indicator/header) + payload size. Thus setting the correct header and set position to 1. data.getData()[1] = (byte) nalHeader; fuScratchBuffer.reset(data.getData()); fuScratchBuffer.setPosition(1); } else { // Check that this packet is in the sequence of the previous packet. int expectedSequenceNumber = (previousSequenceNumber + 1) % RtpPacket.MAX_SEQUENCE_NUMBER; if (packetSequenceNumber != expectedSequenceNumber) { Log.w( TAG, Util.formatInvariant( "Received RTP packet with unexpected sequence number. Expected: %d; received: %d." + " Dropping packet.", expectedSequenceNumber, packetSequenceNumber)); return; } // Setting position to ignore FU indicator and header. fuScratchBuffer.reset(data.getData()); fuScratchBuffer.setPosition(FU_PAYLOAD_OFFSET); } int fragmentSize = fuScratchBuffer.bytesLeft(); trackOutput.sampleData(fuScratchBuffer, fragmentSize); fragmentedSampleSizeBytes += fragmentSize; if (isLastFuPacket) { bufferFlags = getBufferFlagsFromNalType(nalHeader & 0x1F); } } private int writeStartCode() { nalStartCodeArray.setPosition(/* position= */ 0); int bytesWritten = nalStartCodeArray.bytesLeft(); checkNotNull(trackOutput).sampleData(nalStartCodeArray, bytesWritten); return bytesWritten; } private static long toSampleUs( long startTimeOffsetUs, long rtpTimestamp, long firstReceivedRtpTimestamp) { return startTimeOffsetUs + Util.scaleLargeTimestamp( (rtpTimestamp - firstReceivedRtpTimestamp), /* multiplier= */ C.MICROS_PER_SECOND, /* divisor= */ MEDIA_CLOCK_FREQUENCY); } @C.BufferFlags private static int getBufferFlagsFromNalType(int nalType) { return nalType == NAL_UNIT_TYPE_IDR ? C.BUFFER_FLAG_KEY_FRAME : 0; } }
whaty/erd-apis
src/main/java/com/java2e/martin/erd/service/SysUserService.java
package com.java2e.martin.erd.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.java2e.martin.erd.entity.SysUser; import com.baomidou.mybatisplus.extension.service.IService; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** * <p> * 服务类 * </p> * * @author shishao * @version 1.0 * @date 2020-11-10 * @describtion * @since 1.0 */ @Transactional(rollbackFor = Exception.class) public interface SysUserService extends IService<SysUser> { /** * 查询用户角色 * * @return * @param page */ List selectUserRoles(Page page); /** * 用户绑定角色 * * @param map * @return */ Boolean bindRole(Map map); }
LuckyChou710/code-traveling
03-js-training-camp/lodash/package/Array/difference.js
<filename>03-js-training-camp/lodash/package/Array/difference.js const { difference } = require('lodash'); difference([3, 2, 1], [4, 2]); // => [3, 1] /** * @example difference(array, [values]) * @param array (Array): 需要处理的数组 * @param [values] (...Array): 排除的值 * @description 创建一个具有唯一array值的数组,每个值不包含在其他给定的数组中 * @param {Array} array * @param {Array} values * @param {Function} func */ const _difference = (array, values, func) => { const result = array.filter((item) => !values.includes(item)); return (func && result.map((item) => func(item))) || result; }; if (require.main === module) { console.log(_difference([3, 2, 1], [4, 2])); _difference([3, 2, 1], [4, 2], (item) => { console.log('item', item); }); } module.exports = _difference;
taoyuc3/CS225
mp_traversals/colorPicker/MyColorPicker.cpp
<gh_stars>0 #include "../cs225/HSLAPixel.h" #include "../Point.h" #include "ColorPicker.h" #include "MyColorPicker.h" using namespace cs225; /** * Picks the color for pixel (x, y). * Using your own algorithm */ HSLAPixel MyColorPicker::getColor(unsigned x, unsigned y) { /* @todo [Part 3] */ double hue; unsigned x_ = x; unsigned y_ = y; hue = (x+y) % 360; return HSLAPixel(hue, 1.0, 0.5); }
JustinCappos/checkapi
posix_checkapi/TRACES/POT/ut_repyv2api_createlockblocks.py
<reponame>JustinCappos/checkapi<gh_stars>0 """ This unit test checks createlock and the lock object doing a blocking acquire. """ #pragma repy lock = createlock() # Sleeps for .5 seconds and unlocks the global "lock" object def thread(): sleep(0.5) _context["lock"].release() # Exits after 2 second time out def timeout(): sleep(2) log("Timed Out!",'\n') exitall() # Launch the timeout thread, then the unlock thread createthread(timeout) createthread(thread) # Double acquire lock.acquire(True) lock.acquire(True) # Exit now exitall()
BethWIntera/Beths_PySandbox
Learning Unittests/matplotlib-tutorial-master/scripts/plot_ex.py
# ----------------------------------------------------------------------------- # Copyright (c) 2015, <NAME>. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import numpy as np import matplotlib.pyplot as plt n = 256 X = np.linspace(-np.pi,np.pi,n,endpoint=True) Y = np.sin(2*X) plt.axes([0.025,0.025,0.95,0.95]) plt.plot (X, Y+1, color='blue', alpha=1.00) plt.fill_between(X, 1, Y+1, color='blue', alpha=.25) plt.plot (X, Y-1, color='blue', alpha=1.00) plt.fill_between(X, -1, Y-1, (Y-1) > -1, color='blue', alpha=.25) plt.fill_between(X, -1, Y-1, (Y-1) < -1, color='red', alpha=.25) plt.xlim(-np.pi,np.pi), plt.xticks([]) plt.ylim(-2.5,2.5), plt.yticks([]) # savefig('../figures/plot_ex.png',dpi=48) plt.show()
smancke/guble
restclient/sender.go
package restclient // Sender is an interface used to send a message to the guble server. type Sender interface { // Send a a message(body) to the guble Server, to the given topic, with the given userID. Send(topic string, body []byte, userID string, params map[string]string) error // Check returns `true` if the guble server endpoint is reachable, or `false` otherwise. Check() bool // GetSubscribers returns a binary encoded JSON of all subscribers of 'topic' or an error otherwise GetSubscribers(topic string) ([]byte, error) }
Pentacode-IAFA/Quad-Remeshing
libs/quadwild/libs/vcglib/vcg/complex/algorithms/polygonal_algorithms.h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_POLY_MESH_ALGORITHM #define __VCGLIB_POLY_MESH_ALGORITHM #include <vcg/complex/complex.h> #include <vcg/complex/algorithms/update/normal.h> #include <vcg/space/polygon3.h> #include <vcg/complex/algorithms/update/color.h> #include <vcg/complex/algorithms/closest.h> #include <vcg/complex/algorithms/update/quality.h> #include <wrap/io_trimesh/export_obj.h> //define a temporary triangle mesh type class TempFace; class TempVertex; struct TempUsedTypes: public vcg::UsedTypes<vcg::Use<TempVertex>::AsVertexType, vcg::Use<TempFace>::AsFaceType>{}; class TempVertex:public vcg::Vertex<TempUsedTypes, vcg::vertex::Coord3d, vcg::vertex::Normal3d, vcg::vertex::BitFlags> {}; class TempFace:public vcg::Face<TempUsedTypes, vcg::face::VertexRef, vcg::face::BitFlags, vcg::face::FFAdj, vcg::face::Mark, vcg::face::Normal3d> {}; class TempMesh: public vcg::tri::TriMesh< std::vector<TempVertex>,std::vector<TempFace > > {}; namespace vcg{ /*! \ingroup PolyMeshType \headerfile color.h vcg/complex/algorithms/polygonal_algorithms.h \brief processing and optimization of generic polygonal meshes. This class is used to performs varisous kind of geometric optimization on generic polygonal mesh such as flattengin or imptove the shape of polygons. */ template <class PolyMeshType> class PolygonalAlgorithm { typedef typename PolyMeshType::FaceType FaceType; typedef typename PolyMeshType::VertexType VertexType; typedef typename PolyMeshType::VertexPointer VertexPointer; typedef typename PolyMeshType::CoordType CoordType; typedef typename PolyMeshType::ScalarType ScalarType; typedef typename vcg::face::Pos<FaceType> PosType; static void SetFacePos(PolyMeshType &poly_m, int IndexF,std::vector<CoordType> &Pos) { poly_m.face[IndexF].Dealloc(); poly_m.face[IndexF].Alloc(Pos.size()); //std::cout<<Pos.size()<<std::endl; int sizeV=poly_m.vert.size(); for (size_t i=0;i<Pos.size();i++) vcg::tri::Allocator<PolyMeshType>::AddVertex(poly_m,Pos[i]); for (size_t i=0;i<Pos.size();i++) poly_m.face[IndexF].V(i)=&poly_m.vert[sizeV+i]; } public: static void SubdivideStep(PolyMeshType &poly_m) { //get the barycenters std::vector<CoordType> Bary; for (size_t i=0;i<poly_m.face.size();i++) { CoordType bary(0,0,0); for (size_t j=0;j<poly_m.face[i].VN();j++) bary+=poly_m.face[i].P(j); bary/=poly_m.face[i].VN(); Bary.push_back(bary); } //get center of edge std::map<std::pair<CoordType,CoordType>, CoordType> EdgeVert; for (size_t i=0;i<poly_m.face.size();i++) for (size_t j=0;j<poly_m.face[i].VN();j++) { CoordType Pos0=poly_m.face[i].P0(j); CoordType Pos1=poly_m.face[i].P1(j); CoordType Avg=(Pos0+Pos1)/2; std::pair<CoordType,CoordType> Key(std::min(Pos0,Pos1),std::max(Pos0,Pos1)); EdgeVert[Key]=Avg; } int sizeF=poly_m.face.size(); for (size_t i=0;i<sizeF;i++) { //retrieve the sequence of pos std::vector<CoordType> Pos; for (size_t j=0;j<poly_m.face[i].VN();j++) { CoordType Pos0=poly_m.face[i].P0(j); CoordType Pos1=poly_m.face[i].P1(j); std::pair<CoordType,CoordType> Key0(std::min(Pos0,Pos1),std::max(Pos0,Pos1)); Pos0=EdgeVert[Key0]; Pos.push_back(Pos0); Pos.push_back(Pos1); } //get also the barycenter CoordType BaryP=Bary[i]; //then retrieve the face std::vector<CoordType> PosQ; PosQ.push_back(Pos[0]); PosQ.push_back(Pos[1]); PosQ.push_back(Pos[2]); PosQ.push_back(BaryP); SetFacePos(poly_m,i,PosQ); int sizeV=Pos.size(); //int start=0; for (size_t j=2;j<sizeV;j+=2) { vcg::tri::Allocator<PolyMeshType>::AddFaces(poly_m,1); std::vector<CoordType> PosQ; PosQ.push_back(Pos[(j)%Pos.size()]); PosQ.push_back(Pos[(j+1)%Pos.size()]); PosQ.push_back(Pos[(j+2)%Pos.size()]); PosQ.push_back(BaryP); //start+=2; SetFacePos(poly_m,poly_m.face.size()-1,PosQ); //break; } } vcg::tri::Clean<PolyMeshType>::RemoveDuplicateVertex(poly_m); vcg::tri::Allocator<PolyMeshType>::CompactEveryVector(poly_m); } static bool CollapseEdges(PolyMeshType &poly_m, const std::vector<PosType> &CollapsePos, const std::vector<CoordType> &InterpPos) { //this set how to remap the vertices after deletion std::map<VertexType*,VertexType*> VertexRemap; vcg::tri::UpdateFlags<PolyMeshType>::VertexClearS(poly_m); bool collapsed=false; //go over all faces and check the ones needed to be deleted for (size_t i=0;i<CollapsePos.size();i++) { FaceType *currF=CollapsePos[i].F(); int IndexE=CollapsePos[i].E(); size_t NumV=currF->VN(); VertexType *v0=currF->V(IndexE); VertexType *v1=currF->V((IndexE+1)%NumV); //safety check assert(v0!=v1); if (v0->IsS())continue; if (v1->IsS())continue; //put on the same position v0->P()=InterpPos[i]; v1->P()=InterpPos[i]; //select the the two vertices v0->SetS(); v1->SetS(); //set the remap VertexRemap[v1]=v0; collapsed=true; } //then remap vertices for (size_t i=0;i<poly_m.face.size();i++) { int NumV=poly_m.face[i].VN(); for (int j=0;j<NumV;j++) { //get the two vertices of the edge VertexType *v0=poly_m.face[i].V(j); //see if it must substituted or not if (VertexRemap.count(v0)==0)continue; //in that case remap to the new one VertexType *newV=VertexRemap[v0]; //assign new vertex poly_m.face[i].V(j)=newV; } } //then re-elaborate the face for (size_t i=0;i<poly_m.face.size();i++) { //get vertices of the face int NumV=poly_m.face[i].VN(); std::vector<VertexType*> FaceV; for (int j=0;j<NumV;j++) { VertexType *v0=poly_m.face[i].V(j); VertexType *v1=poly_m.face[i].V((j+1)%NumV); if(v0==v1)continue; FaceV.push_back(v0); } //then deallocate face if ((int)FaceV.size()==NumV)continue; //otherwise deallocate and set new vertices poly_m.face[i].Dealloc(); poly_m.face[i].Alloc(FaceV.size()); for (size_t j=0;j<FaceV.size();j++) poly_m.face[i].V(j)=FaceV[j]; } //remove unreferenced vertices vcg::tri::Clean<PolyMeshType>::RemoveUnreferencedVertex(poly_m); //and compact them vcg::tri::Allocator<PolyMeshType>::CompactEveryVector(poly_m); return collapsed; } private: static bool CollapseBorderSmallEdgesStep(PolyMeshType &poly_m, const ScalarType edge_limit) { //update topology vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); //update border vertices vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); vcg::tri::UpdateSelection<PolyMeshType>::VertexCornerBorder(poly_m,math::ToRad(150.0)); std::vector<PosType> CollapsePos; std::vector<CoordType> InterpPos; //go over all faces and check the ones needed to be deleted for (size_t i=0;i<poly_m.face.size();i++) { int NumV=poly_m.face[i].VN(); for (int j=0;j<NumV;j++) { VertexType *v0=poly_m.face[i].V(j); VertexType *v1=poly_m.face[i].V((j+1)%NumV); assert(v0!=v1); bool IsBV0=v0->IsB(); bool IsBV1=v1->IsB(); bool IsS0=v0->IsS(); bool IsS1=v1->IsS(); if ((IsS0)&&(IsS1))continue; //in these cases is not possible to collapse if ((!IsBV0)&&(!IsBV1))continue; bool IsBorderE=(poly_m.face[i].FFp(j)==&poly_m.face[i]); if ((!IsBorderE)&&(IsBV0)&&(IsBV1))continue; assert((IsBV0)||(IsBV1)); CoordType pos0=v0->P(); CoordType pos1=v1->P(); ScalarType currL=(pos0-pos1).Norm(); if (currL>edge_limit)continue; //then collapse the point CoordType CurrInterpPos; if ((IsBV0)&&(!IsBV1))CurrInterpPos=pos0; if ((!IsBV0)&&(IsBV1))CurrInterpPos=pos1; if ((IsBV0)&&(IsBV1)) { if ((!IsS0)&&(!IsS1)) CurrInterpPos=(pos0+pos1)/2.0; else { if ((!IsS0)&&(IsS1)) CurrInterpPos=pos1; else { assert((IsS0)&&(!IsS1)); CurrInterpPos=pos0; } } } CollapsePos.push_back(PosType(&poly_m.face[i],j)); InterpPos.push_back(CurrInterpPos); } } return CollapseEdges(poly_m,CollapsePos,InterpPos); } static void LaplacianPos(PolyMeshType &poly_m,std::vector<CoordType> &AvVert) { //cumulate step AvVert.clear(); AvVert.resize(poly_m.vert.size(),CoordType(0,0,0)); std::vector<ScalarType> AvSum(poly_m.vert.size(),0); for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD()) continue; for (size_t j=0;j<(size_t)poly_m.face[i].VN();j++) { //get current vertex VertexType *currV=poly_m.face[i].V(j); //and its position CoordType currP=currV->P(); //cumulate over other positions ScalarType W=vcg::PolyArea(poly_m.face[i]); //assert(W!=0); for (size_t k=0;k<(size_t)poly_m.face[i].VN();k++) { if (k==j) continue; int IndexV=vcg::tri::Index(poly_m,poly_m.face[i].V(k)); AvVert[IndexV]+=currP*W; AvSum[IndexV]+=W; } } } //average step for (size_t i=0;i<poly_m.vert.size();i++) { if (poly_m.vert[i].IsD()) continue; if (AvSum[i]==0)continue; AvVert[i]/=AvSum[i]; } } static void UpdateNormal(FaceType &F) { F.N()=vcg::PolygonNormal(F); } static void UpdateNormalByFitting(FaceType &F) { UpdateNormal(F); vcg::Plane3<ScalarType> PlF; PlF=PolyFittingPlane(F); if ((PlF.Direction()*F.N())<0) F.N()=-PlF.Direction(); else F.N()=PlF.Direction(); } static void DisplaceBySelected(FaceType &f,std::vector<CoordType> &TemplatePos, bool FixS,bool FixB) { CoordType AvPosF(0,0,0); CoordType AvPosT(0,0,0); size_t Num=0; for (size_t i=0;i<f.VN();i++) { bool AddVal=false; AddVal|=((FixS)&&(f.V(i)->IsS())); AddVal|=((FixB)&&(f.V(i)->IsB())); if (!AddVal)continue; Num++; AvPosF+=f.V(i)->P(); AvPosT+=TemplatePos[i]; } if (Num==0)return; AvPosF/=(ScalarType)Num; AvPosT/=(ScalarType)Num; CoordType Displ=AvPosF-AvPosT; for (size_t i=0;i<TemplatePos.size();i++) TemplatePos[i]+=Displ; } public: static void SelectIrregularInternal(PolyMeshType &poly_m) { vcg::tri::UpdateQuality<PolyMeshType>::VertexValence(poly_m); vcg::tri::UpdateSelection<PolyMeshType>::VertexClear(poly_m); for (size_t i=0;i<poly_m.vert.size();i++) { if (poly_m.vert[i].IsB())continue; if (poly_m.vert[i].Q()==4)continue; poly_m.vert[i].SetS(); } } static void SelectIrregularBorder(PolyMeshType &poly_m) { vcg::tri::UpdateQuality<PolyMeshType>::VertexValence(poly_m); for (size_t i=0;i<poly_m.vert.size();i++) { if (!poly_m.vert[i].IsB())continue; if (poly_m.vert[i].Q()==2)continue; poly_m.vert[i].SetS(); } } static CoordType GetFaceGetBary(FaceType &F) { CoordType bary=PolyBarycenter(F); return bary; } /*! \brief update the face normal by averaging among vertex's * normals computed between adjacent edges */ static void UpdateFaceNormals(PolyMeshType &poly_m) { for (size_t i=0;i<poly_m.face.size();i++) if (!poly_m.face[i].IsD()) UpdateNormal(poly_m.face[i]); } /*! \brief update the face normal by fitting a plane */ static void UpdateFaceNormalByFitting(PolyMeshType &poly_m) { for (size_t i=0;i<poly_m.face.size();i++) if (!poly_m.face[i].IsD()) UpdateNormalByFitting(poly_m.face[i]); } enum PolyQualityType{QAngle,QPlanar,QTemplate}; /*! \brief update the quality of the faces by considering different possibilities * QAngle = consider the angle deviation from ideal one (ex 90° quad, 60° triangle...) * QPlanar = consider the difference wrt interpolating plane * QTemplate= consider the difference wrt template polygon as in "Statics Aware Grid Shells" */ static void UpdateQuality(PolyMeshType &poly_m, const PolyQualityType &QType) { for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD())continue; switch (QType) { case QAngle: ScalarType AvgDev,WorstDev; vcg::PolyAngleDeviation(poly_m.face[i],AvgDev,WorstDev); poly_m.face[i].Q()=WorstDev; break; case QPlanar: poly_m.face[i].Q()=vcg::PolyFlatness(poly_m.face[i]); break; default: poly_m.face[i].Q()=vcg::PolyAspectRatio(poly_m.face[i],true); break; } } } /*! \brief given a face this function returns the template positions as in "Statics Aware Grid Shells" */ static void GetRotatedTemplatePos(FaceType &f, std::vector<CoordType> &TemplatePos) { vcg::GetPolyTemplatePos(f,TemplatePos,true); CoordType NormT=Normal(TemplatePos); //get the normal of vertices //CoordType AVN(0,0,0); //CoordType AVN0(0,0,0); CoordType Origin(0,0,0); // for (int j=0;j<f.VN();j++) // AVN0=AVN0+f.V(j)->N(); CoordType AVN=vcg::PolygonNormal(f); //AVN0.Normalize(); // std::cout<<"AVN "<<AVN.X()<<","<<AVN.Y()<<","<<AVN.Z()<<std::endl; // std::cout<<"AVN0 "<<AVN0.X()<<","<<AVN0.Y()<<","<<AVN0.Z()<<std::endl; // std::cout<<"NormT "<<NormT.X()<<","<<NormT.Y()<<","<<NormT.Z()<<std::endl; for (size_t j=0;j<TemplatePos.size();j++) Origin+=TemplatePos[j]; Origin/=(ScalarType)TemplatePos.size(); AVN.Normalize(); //find rotation matrix vcg::Matrix33<ScalarType> Rot=vcg::RotationMatrix(NormT,AVN); //apply transformation for (size_t j=0;j<TemplatePos.size();j++) { TemplatePos[j]=TemplatePos[j]-Origin; TemplatePos[j]=Rot*TemplatePos[j]; TemplatePos[j]=TemplatePos[j]+Origin; } } /*! \brief This function performs the polygon regularization as in "Statics Aware Grid Shells" */ static void SmoothPCA(PolyMeshType &poly_m, int relax_step=10, ScalarType Damp=0.5, bool FixS=false, bool isotropic=true, ScalarType smoothTerm=0.1, bool fixB=true, bool WeightByQuality=false, const std::vector<bool> *IgnoreF=NULL) { (void)isotropic; typedef typename PolyMeshType::FaceType PolygonType; // // select irregular ones // if (fixIrr) // poly_m.NumIrregular(true); // compute the average edge ScalarType MeshArea=0; for (size_t i=0;i<poly_m.face.size();i++) MeshArea+=vcg::PolyArea(poly_m.face[i]); ScalarType AvgArea=MeshArea/(ScalarType)poly_m.face.size(); if (WeightByQuality) UpdateQuality(poly_m,QTemplate); if (IgnoreF!=NULL){assert((*IgnoreF).size()==poly_m.face.size());} for (size_t s=0;s<(size_t)relax_step;s++) { //initialize the accumulation vector std::vector<CoordType> avgPos(poly_m.vert.size(),CoordType(0,0,0)); std::vector<ScalarType> weightSum(poly_m.vert.size(),0); //then compute the templated positions for (size_t i=0;i<poly_m.face.size();i++) { if ((IgnoreF!=NULL)&&((*IgnoreF)[i]))continue; std::vector<typename PolygonType::CoordType> TemplatePos; GetRotatedTemplatePos(poly_m.face[i],TemplatePos); if ((FixS)||(fixB)) DisplaceBySelected(poly_m.face[i],TemplatePos,FixS,fixB); //then cumulate the position per vertex ScalarType val=vcg::PolyArea(poly_m.face[i]); if (val<(AvgArea*0.00001)) val=(AvgArea*0.00001); ScalarType W=1.0/val; if (WeightByQuality) W=poly_m.face[i].Q()+0.00001; for (size_t j=0;j<TemplatePos.size();j++) { int IndexV=vcg::tri::Index(poly_m,poly_m.face[i].V(j)); CoordType Pos=TemplatePos[j]; //sum up contributes avgPos[IndexV]+=Pos*W; weightSum[IndexV]+=W; } } //get the laplacian contribute std::vector<CoordType> AvVert; LaplacianPos(poly_m,AvVert); //then update the position for (size_t i=0;i<poly_m.vert.size();i++) { ScalarType alpha=smoothTerm;//PolyNormDeviation(poly_m.face[i]); // if (alpha<0)alpha=0; // if (alpha>1)alpha=1; // if (isnan(alpha))alpha=1; CoordType newP=poly_m.vert[i].P(); //safety checks if (weightSum[i]>0) newP=avgPos[i]/weightSum[i]; if (isnan(newP.X())||isnan(newP.Y())||isnan(newP.Z())) newP=poly_m.vert[i].P(); if ((newP-poly_m.vert[i].P()).Norm()>poly_m.bbox.Diag()) newP=poly_m.vert[i].P(); //std::cout<<"W "<<weightSum[i]<<std::endl; newP=newP*(1-alpha)+AvVert[i]*alpha; //newP=AvVert[i]; if ((fixB)&&(poly_m.vert[i].IsB()))continue; if ((FixS)&&(poly_m.vert[i].IsS()))continue; poly_m.vert[i].P()=poly_m.vert[i].P()*Damp+ newP*(1-Damp); } } } template <class TriMeshType> static void ReprojectBorder(PolyMeshType &poly_m, TriMeshType &tri_mesh, bool FixS=true) { //then reproject on border for (size_t i=0;i<poly_m.vert.size();i++) { if (!poly_m.vert[i].IsB())continue; if (FixS && poly_m.vert[i].IsS())continue; CoordType testPos=poly_m.vert[i].P(); ScalarType minD=std::numeric_limits<ScalarType>::max(); CoordType closPos; for (size_t j=0;j<tri_mesh.face.size();j++) for (size_t k=0;k<3;k++) { //check if border edge if (tri_mesh.face[j].FFp(k)!=(&tri_mesh.face[j]))continue; CoordType P0,P1; P0.Import(tri_mesh.face[j].cP0(k)); P1.Import(tri_mesh.face[j].cP1(k)); vcg::Segment3<ScalarType> Seg(P0,P1); ScalarType testD; CoordType closTest; vcg::SegmentPointDistance(Seg,testPos,closTest,testD); if (testD>minD)continue; minD=testD; closPos=closTest; } poly_m.vert[i].P()=closPos; } } /*! \brief This function smooth the borders of the polygonal mesh and reproject back to the triangolar one * except the vertices that are considered as corner wrt the angleDeg threshold */ template <class TriMeshType> static void LaplacianReprojectBorder(PolyMeshType &poly_m, TriMeshType &tri_mesh, int nstep=100, ScalarType Damp=0.5, ScalarType angleDeg=100) { //first select corners vcg::tri::UpdateFlags<PolyMeshType>::VertexClearS(poly_m); //update topology vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); //update border vertices vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); //select corner vertices on the border ScalarType angleRad=angleDeg * M_PI / 180; vcg::tri::UpdateSelection<PolyMeshType>::VertexCornerBorder(poly_m,angleRad); for (int s=0;s<nstep;s++) { std::vector<CoordType> AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i<poly_m.vert.size();i++) { if (!poly_m.vert[i].IsB())continue; if (poly_m.vert[i].IsS())continue; poly_m.vert[i].P()=poly_m.vert[i].P()*Damp+ AvVert[i]*(1-Damp); } // //then reproject on border // for (size_t i=0;i<poly_m.vert.size();i++) // { // if (!poly_m.vert[i].IsB())continue; // if (poly_m.vert[i].IsS())continue; // CoordType testPos=poly_m.vert[i].P(); // ScalarType minD=std::numeric_limits<ScalarType>::max(); // CoordType closPos; // for (size_t j=0;j<tri_mesh.face.size();j++) // for (size_t k=0;k<3;k++) // { // if (tri_mesh.face[j].FFp(k)!=(&tri_mesh.face[j]))continue; // CoordType P0,P1; // P0.Import(tri_mesh.face[j].cP0(k)); // P1.Import(tri_mesh.face[j].cP1(k)); // vcg::Segment3<ScalarType> Seg(P0,P1); // ScalarType testD; // CoordType closTest; // vcg::SegmentPointDistance(Seg,testPos,closTest,testD); // if (testD>minD)continue; // minD=testD; // closPos=closTest; // } // poly_m.vert[i].P()=closPos; // } ReprojectBorder(poly_m,tri_mesh); } } /*! \brief This function smooth the borders of the polygonal mesh and reproject back to its border */ static void LaplacianReprojectBorder(PolyMeshType &poly_m, int nstep=100, ScalarType Damp=0.5, ScalarType Angle=100) { //transform into triangular TempMesh GuideSurf; vcg::tri::PolygonSupport<TempMesh,PolyMeshType>::ImportFromPolyMesh(GuideSurf,poly_m); vcg::tri::UpdateBounding<TempMesh>::Box(GuideSurf); vcg::tri::UpdateNormal<TempMesh>::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology<TempMesh>::FaceFace(GuideSurf); vcg::tri::UpdateFlags<TempMesh>::FaceBorderFromFF(GuideSurf); LaplacianReprojectBorder<TempMesh>(poly_m,GuideSurf,nstep,Damp,Angle); } /*! \brief This function performs the reprojection of the polygonal mesh onto a triangular one passed as input parameter */ template <class TriMeshType> static void LaplacianReproject(PolyMeshType &poly_m, TriMeshType &tri_mesh, int nstep=100, ScalarType DampS=0.5, ScalarType DampR=0.5, bool OnlyOnSelected=false) { typedef typename TriMeshType::FaceType TriFaceType; typedef typename TriMeshType::ScalarType TriScalarType; typedef typename TriMeshType::CoordType TriCoordType; typedef vcg::GridStaticPtr<TriFaceType, TriScalarType> TriMeshGrid; TriMeshGrid grid; tri::MeshAssert<TriMeshType>::VertexNormalNormalized(tri_mesh); //initialize the grid grid.Set(tri_mesh.face.begin(),tri_mesh.face.end()); TriScalarType MaxD=tri_mesh.bbox.Diag(); for (int s=0;s<nstep;s++) { std::vector<CoordType> AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i<poly_m.vert.size();i++) { if (poly_m.vert[i].IsB()) continue; if(poly_m.vert[i].IsD() || (OnlyOnSelected && !poly_m.vert[i].IsS())) continue; poly_m.vert[i].P()=poly_m.vert[i].P()*DampS+ AvVert[i]*(1-DampS); } for (size_t i=0;i<poly_m.vert.size();i++) { if(poly_m.vert[i].IsD() || (OnlyOnSelected && !poly_m.vert[i].IsS())) continue; TriCoordType testPos; testPos.Import(poly_m.vert[i].P()); TriCoordType closestPt; TriScalarType minDist; TriFaceType *f=NULL; TriCoordType norm,ip; f=vcg::tri::GetClosestFaceBase(tri_mesh,grid,testPos,MaxD,minDist,closestPt,norm,ip); CoordType closestImp; closestImp.Import(closestPt); poly_m.vert[i].P()=poly_m.vert[i].P()*DampR+ closestImp*(1-DampR); CoordType normalImp; normalImp.Import(norm); poly_m.vert[i].N()=normalImp; } } } static void LaplacianReproject(PolyMeshType &poly_m, int nstep=100, ScalarType Damp=0.5, bool OnlyOnSelected=false) { //transform into triangular TempMesh GuideSurf; //vcg::tri::PolygonSupport<TempMesh,PolyMeshType>:(GuideSurf,poly_m); TriangulateToTriMesh<TempMesh>(poly_m,GuideSurf); vcg::tri::UpdateBounding<TempMesh>::Box(GuideSurf); vcg::tri::UpdateNormal<TempMesh>::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology<TempMesh>::FaceFace(GuideSurf); vcg::tri::UpdateFlags<TempMesh>::FaceBorderFromFF(GuideSurf); LaplacianReproject<TempMesh>(poly_m,GuideSurf,nstep,Damp,0.5,OnlyOnSelected); } static void Laplacian(PolyMeshType &poly_m, bool FixS=false, int nstep=10, ScalarType Damp=0.5) { for (int s=0;s<nstep;s++) { std::vector<CoordType> AvVert; LaplacianPos(poly_m,AvVert); for (size_t i=0;i<poly_m.vert.size();i++) { if ((FixS) && (poly_m.vert[i].IsS()))continue; poly_m.vert[i].P()=poly_m.vert[i].P()*Damp+ AvVert[i]*(1-Damp); } } } /*! \brief This function performs the polygon regularization as in "Statics Aware Grid Shells" * followed by a reprojection step on the triangle mesh passed as parameter */ template <class TriMeshType> static void SmoothReprojectPCA(PolyMeshType &poly_m, TriMeshType &tri_mesh, int relaxStep=100, bool fixS=false, ScalarType Damp=0.5, ScalarType SharpDeg=0, bool WeightByQuality=false, bool FixB=true) { //vcg::tri::UpdateFlags<PolyMeshType>::VertexClearS(poly_m); vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); //UpdateBorderVertexFromPFFAdj(poly_m); vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); std::vector<std::vector<vcg::Line3<ScalarType> > > SharpEdge(poly_m.vert.size()); //first select sharp features if (SharpDeg>0) { for (int i=0;i<(int)poly_m.face.size();i++) for (int j=0;j<(int)poly_m.face[i].VN();j++) { //check only one side if ((&poly_m.face[i])>=poly_m.face[i].FFp(j))continue; CoordType N0=poly_m.face[i].N(); CoordType N1=poly_m.face[i].FFp(j)->N(); ScalarType Angle=vcg::Angle(N0,N1); if (fabs(Angle)>(SharpDeg* (M_PI / 180.0))) { CoordType Pos0=poly_m.face[i].V0(j)->P(); CoordType Pos1=poly_m.face[i].V1(j)->P(); CoordType Ori=Pos0; CoordType Dir=Pos1-Pos0; Dir.Normalize(); vcg::Line3<ScalarType> L(Ori,Dir); int Index0=vcg::tri::Index(poly_m,poly_m.face[i].V0(j)); int Index1=vcg::tri::Index(poly_m,poly_m.face[i].V1(j)); SharpEdge[Index0].push_back(L); SharpEdge[Index1].push_back(L); } } for (size_t i=0;i<poly_m.vert.size();i++) { if (SharpEdge[i].size()==0)continue; if (SharpEdge[i].size()>2)poly_m.vert[i].SetS(); } } // if (fixIrr) // { // vcg::tri::UpdateQuality<PolyMeshType>::VertexValence(poly_m); // for (size_t i=0;i<poly_m.vert.size();i++) // { // if (poly_m.vert[i].IsB())continue; // if (poly_m.vert[i].Q()==4)continue; // poly_m.vert[i].SetS(); // } // } typedef typename TriMeshType::FaceType FaceType; typedef vcg::GridStaticPtr<FaceType, typename TriMeshType::ScalarType> TriMeshGrid; TriMeshGrid grid; //initialize the grid grid.Set(tri_mesh.face.begin(),tri_mesh.face.end()); ScalarType MaxD=tri_mesh.bbox.Diag(); // //update quality as area // for (size_t i=0;i<poly_m.face.size();i++) // poly_m.face[i].Q()=vcg::PolyArea(poly_m.face[i]); // for (size_t i=0;i<poly_m.vert.size();i++) // { // typename TriMeshType::CoordType testPos; // testPos.Import(poly_m.vert[i].P()); // typename TriMeshType::CoordType closestPt; // typename TriMeshType::ScalarType minDist; // typename TriMeshType::FaceType *f=NULL; // typename TriMeshType::CoordType norm,ip; // f=vcg::tri::GetClosestFaceBase(tri_mesh,grid,testPos,MaxD,minDist,closestPt,norm,ip); // //poly_m.vert[i].N().Import(norm); // } for(int k=0;k<relaxStep;k++) { //smooth PCA step SmoothPCA(poly_m,1,Damp,fixS,true,0.1,FixB,WeightByQuality); //reprojection step //laplacian smooth step //Laplacian(poly_m,Damp,1); for (size_t i=0;i<poly_m.vert.size();i++) { typename TriMeshType::CoordType testPos; testPos.Import(poly_m.vert[i].P()); typename TriMeshType::CoordType closestPt; typename TriMeshType::ScalarType minDist; if ((FixB)&&(poly_m.vert[i].IsB())) {continue;} else if (SharpEdge[i].size()==0)//reproject onto original mesh { FaceType *f=NULL; typename TriMeshType::CoordType norm,ip; f=vcg::tri::GetClosestFaceBase(tri_mesh,grid,testPos,MaxD,minDist,closestPt,norm,ip); poly_m.vert[i].P().Import(testPos*Damp+closestPt*(1-Damp)); //poly_m.vert[i].N().Import(norm); } else //reproject onto segments { CoordType av_closest(0,0,0); size_t sum=0; for (size_t j=0;j<SharpEdge[i].size();j++) { CoordType currPos; currPos.Import(testPos); CoordType closest; ScalarType dist; vcg::LinePointDistance(SharpEdge[i][j],currPos,closest,dist); av_closest+=closest; sum++; } assert(sum>0); poly_m.vert[i].P()=av_closest/sum; } } if (!FixB) ReprojectBorder(poly_m,tri_mesh,true); UpdateFaceNormals(poly_m); vcg::tri::UpdateNormal<PolyMeshType>::PerVertexFromCurrentFaceNormal(poly_m); } } template <class TriMeshType> static void TriangulateToTriMesh(PolyMeshType &poly_m,TriMeshType &triangle_mesh, bool alsoTriangles = true) { triangle_mesh.Clear(); PolyMeshType PolySwap; vcg::tri::Append<PolyMeshType,PolyMeshType>::Mesh(PolySwap,poly_m); Triangulate(PolySwap, alsoTriangles); //then copy onto the triangle mesh vcg::tri::Append<TriMeshType,PolyMeshType>::Mesh(triangle_mesh,PolySwap); } /*! \brief This function performs the polygon regularization as in "Statics Aware Grid Shells" * followed by a reprojection step on the original mesh */ static void SmoothReprojectPCA(PolyMeshType &poly_m, int relaxStep=100, bool fixS=false, ScalarType Damp=0.5, ScalarType SharpDeg=0, bool WeightByQuality=false, bool FixB=true) { //transform into triangular TempMesh GuideSurf; //vcg::tri::PolygonSupport<TempMesh,PolyMeshType>:(GuideSurf,poly_m); TriangulateToTriMesh<TempMesh>(poly_m,GuideSurf); vcg::tri::UpdateBounding<TempMesh>::Box(GuideSurf); vcg::tri::UpdateNormal<TempMesh>::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology<TempMesh>::FaceFace(GuideSurf); vcg::tri::UpdateFlags<TempMesh>::FaceBorderFromFF(GuideSurf); //optimize it vcg::PolygonalAlgorithm<PolyMeshType>::SmoothReprojectPCA<TempMesh>(poly_m,GuideSurf,relaxStep,fixS,Damp,SharpDeg,WeightByQuality,FixB); } static void Reproject(PolyMeshType &poly_m, PolyMeshType &target) { vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); //transform into triangular TempMesh GuideSurf; //vcg::tri::PolygonSupport<TempMesh,PolyMeshType>:(GuideSurf,poly_m); TriangulateToTriMesh<TempMesh>(target,GuideSurf); vcg::tri::UpdateBounding<TempMesh>::Box(GuideSurf); vcg::tri::UpdateNormal<TempMesh>::PerVertexNormalizedPerFace(GuideSurf); vcg::tri::UpdateTopology<TempMesh>::FaceFace(GuideSurf); vcg::tri::UpdateFlags<TempMesh>::FaceBorderFromFF(GuideSurf); //initialize the grid typedef typename TempMesh::FaceType FaceType; typedef vcg::GridStaticPtr<FaceType, typename TempMesh::ScalarType> TriMeshGrid; TriMeshGrid grid; grid.Set(GuideSurf.face.begin(),GuideSurf.face.end()); ScalarType MaxD=GuideSurf.bbox.Diag(); for (size_t i=0;i<poly_m.vert.size();i++) { //reproject on border later if (poly_m.vert[i].IsB())continue; typename TempMesh::CoordType testPos; testPos.Import(poly_m.vert[i].P()); typename TempMesh::CoordType closestPt; typename TempMesh::ScalarType minDist; typename TempMesh::FaceType *f=NULL; typename TempMesh::CoordType norm,ip; f=vcg::tri::GetClosestFaceBase(GuideSurf,grid,testPos,MaxD,minDist,closestPt,norm,ip); poly_m.vert[i].P()=closestPt; } //then reprojec the border ReprojectBorder(poly_m,GuideSurf); } template <class TriMesh> static void ReprojectonTriMesh(PolyMeshType &poly_m, TriMesh &target) { vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); //initialize the grid typedef typename TriMesh::FaceType FaceType; typedef vcg::GridStaticPtr<FaceType, typename TriMesh::ScalarType> TriMeshGrid; TriMeshGrid grid; grid.Set(target.face.begin(),target.face.end()); ScalarType MaxD=target.bbox.Diag(); for (size_t i=0;i<poly_m.vert.size();i++) { //reproject on border later if (poly_m.vert[i].IsB())continue; typename TriMesh::CoordType testPos; testPos.Import(poly_m.vert[i].P()); typename TriMesh::CoordType closestPt; typename TriMesh::ScalarType minDist; typename TriMesh::FaceType *f=NULL; typename TriMesh::CoordType norm,ip; f=vcg::tri::GetClosestFaceBase(target,grid,testPos,MaxD,minDist,closestPt,norm,ip); poly_m.vert[i].P()=closestPt; } //then reprojec the border ReprojectBorder(poly_m,target); } /*! \brief This function return average edge size */ static ScalarType AverageEdge(const PolyMeshType &poly_m) { ScalarType AvL=0; size_t numE=0; for (size_t i=0;i<poly_m.face.size();i++) { int NumV=poly_m.face[i].VN(); for (int j=0;j<NumV;j++) { CoordType pos0=poly_m.face[i].cV(j)->P(); CoordType pos1=poly_m.face[i].cV((j+1)%NumV)->P(); AvL+=(pos0-pos1).Norm(); numE++; } } AvL/=numE; return AvL; } /*! \brief This function remove valence 2 faces from the mesh */ static void RemoveValence2Faces(PolyMeshType &poly_m) { for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].VN()>=3)continue; vcg::tri::Allocator<PolyMeshType>::DeleteFace(poly_m,poly_m.face[i]); } //then remove unreferenced vertices vcg::tri::Clean<PolyMeshType>::RemoveUnreferencedVertex(poly_m); vcg::tri::Allocator<PolyMeshType>::CompactEveryVector(poly_m); } /*! \brief This function remove valence 2 vertices on the border by considering the degree threshold * bacause there could be eventually some corner that should be preserved */ static void RemoveValence2Vertices(PolyMeshType &poly_m, ScalarType corner_degree=25) { //update topology vcg::tri::UpdateTopology<PolyMeshType>::FaceFace(poly_m); //update border vertices //UpdateBorderVertexFromPFFAdj(poly_m); vcg::tri::UpdateFlags<PolyMeshType>::VertexBorderFromFaceAdj(poly_m); vcg::tri::UpdateFlags<PolyMeshType>::VertexClearS(poly_m); //select corners for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD())continue; //get vertices of the face int NumV=poly_m.face[i].VN(); for (int j=0;j<NumV;j++) { VertexType *v0=poly_m.face[i].V((j+NumV-1)%NumV); VertexType *v1=poly_m.face[i].V(j); VertexType *v2=poly_m.face[i].V((j+1)%NumV); //must be 3 borders bool IsB=((v0->IsB())&&(v1->IsB())&&(v2->IsB())); CoordType dir0=(v0->P()-v1->P()); CoordType dir1=(v2->P()-v1->P()); dir0.Normalize(); dir1.Normalize(); ScalarType testDot=(dir0*dir1); if ((IsB)&&(testDot>(-cos(corner_degree* (M_PI / 180.0))))) v1->SetS(); } } typename PolyMeshType::template PerVertexAttributeHandle<size_t> valenceVertH = vcg::tri::Allocator<PolyMeshType>:: template GetPerVertexAttribute<size_t> (poly_m); //initialize to zero for (size_t i=0;i<poly_m.vert.size();i++) valenceVertH[i]=0; //then sum up the valence for (size_t i=0;i<poly_m.face.size();i++) for (int j=0;j<poly_m.face[i].VN();j++) valenceVertH[poly_m.face[i].V(j)]++; //cannot collapse triangular vertices otherwise will collapse to a segment for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].VN()>3)continue; for (int j=0;j<poly_m.face[i].VN();j++) valenceVertH[poly_m.face[i].V(j)]=3; } //then re-elaborate the faces for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD())continue; //get vertices of the face int NumV=poly_m.face[i].VN(); std::vector<VertexType*> FaceV; for (int j=0;j<NumV;j++) { VertexType *v=poly_m.face[i].V(j); assert(!v->IsD()); //if ((!v->IsS()) && (v->IsB()) && (valenceVertH[v]==1)) continue; if ((!v->IsS()) && (v->IsB()) && (valenceVertH[v]==1)) continue; if ((!v->IsB()) && (valenceVertH[v]<3)) continue; //if (!v->IsS()) continue; FaceV.push_back(v); } //then deallocate face if ((int)FaceV.size()==NumV)continue; //otherwise deallocate and set new vertices poly_m.face[i].Dealloc(); poly_m.face[i].Alloc(FaceV.size()); for (size_t j=0;j<FaceV.size();j++) poly_m.face[i].V(j)=FaceV[j]; } //then remove unreferenced vertices vcg::tri::Clean<PolyMeshType>::RemoveUnreferencedVertex(poly_m); vcg::tri::Allocator<PolyMeshType>::CompactEveryVector(poly_m); vcg::tri::Allocator<PolyMeshType>::DeletePerVertexAttribute(poly_m,valenceVertH); } /*! \brief This function collapse small edges which are on the boundary of the mesh * this is sometimes useful to remove small edges coming out from a quadrangulation which is not * aligned to boundaries */ static bool CollapseBorderSmallEdges(PolyMeshType &poly_m, const ScalarType perc_average=0.3) { //compute the average edge ScalarType AvEdge=AverageEdge(poly_m); ScalarType minLimit=AvEdge*perc_average; bool collapsed=false; while(CollapseBorderSmallEdgesStep(poly_m,minLimit)){collapsed=true;}; RemoveValence2Faces(poly_m); //RemoveValence2BorderVertices(poly_m); RemoveValence2Vertices(poly_m); return collapsed; } /*! \brief This function use a local global approach to flatten polygonal faces * the approach is similar to "Shape-Up: Shaping Discrete Geometry with Projections" */ static ScalarType FlattenFaces(PolyMeshType &poly_m, size_t steps=100,bool OnlySFaces=false) { ScalarType MaxDispl=0; for (size_t s=0;s<steps;s++) { std::vector<std::vector<CoordType> > VertPos(poly_m.vert.size()); for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD())continue; if (OnlySFaces && (!poly_m.face[i].IsS()))continue; //get vertices of the face int NumV=poly_m.face[i].VN(); if (NumV<=3)continue; //save vertice's positions std::vector<CoordType> FacePos; for (int j=0;j<NumV;j++) { VertexType *v=poly_m.face[i].V(j); assert(!v->IsD()); FacePos.push_back(v->P()); } //then fit the plane vcg::Plane3<ScalarType> FitPl; vcg::FitPlaneToPointSet(FacePos,FitPl); //project each point onto fitting plane for (int j=0;j<NumV;j++) { VertexType *v=poly_m.face[i].V(j); int IndexV=vcg::tri::Index(poly_m,v); CoordType ProjP=FitPl.Projection(v->P()); VertPos[IndexV].push_back(ProjP); } } for (size_t i=0;i<poly_m.vert.size();i++) { CoordType AvgPos(0,0,0); for (size_t j=0;j<VertPos[i].size();j++) AvgPos+=VertPos[i][j]; if (VertPos[i].size()==0)continue; AvgPos/=(ScalarType)VertPos[i].size(); MaxDispl=std::max(MaxDispl,(poly_m.vert[i].P()-AvgPos).Norm()); poly_m.vert[i].P()=AvgPos; } } return MaxDispl; } static ScalarType Area(PolyMeshType &poly_m) { ScalarType MeshArea=0; for (size_t i=0;i<poly_m.face.size();i++) MeshArea+=vcg::PolyArea(poly_m.face[i]); return MeshArea; } static void InitQualityVertVoronoiArea(PolyMeshType &poly_m) { for (size_t i=0;i<poly_m.vert.size();i++) poly_m.vert[i].Q()=0; for (size_t i=0;i<poly_m.face.size();i++) { // ScalarType AreaF=vcg::PolyArea(poly_m.face[i]); size_t sizeV=poly_m.face[i].VN()-1; CoordType baryF=vcg::PolyBarycenter(poly_m.face[i]); for (int j=0;j<poly_m.face[i].VN();j++) { CoordType P0=poly_m.face[i].P((j+sizeV-1)%sizeV); CoordType P1=poly_m.face[i].P(j); CoordType P2=poly_m.face[i].P1(j); vcg::Triangle3<ScalarType> T0(P1,(P0+P1)/2,baryF); vcg::Triangle3<ScalarType> T1(P1,(P1+P2)/2,baryF); poly_m.face[i].V(j)->Q()+=vcg::DoubleArea(T0)/2; poly_m.face[i].V(j)->Q()+=vcg::DoubleArea(T1)/2; } } } static ScalarType InitQualityFaceTorsion(PolyMeshType &poly_m) { UpdateFaceNormalByFitting(poly_m); vcg::tri::UpdateNormal<PolyMeshType>::PerVertexFromCurrentFaceNormal(poly_m); ScalarType MaxA=0; for (size_t i=0;i<poly_m.face.size();i++) { poly_m.face[i].Q()=PolygonTorsion(poly_m.face[i]); MaxA=std::max(MaxA,poly_m.face[i].Q()); } return MaxA; } static ScalarType InitQualityFaceBending(PolyMeshType &poly_m) { UpdateFaceNormalByFitting(poly_m); vcg::tri::UpdateNormal<PolyMeshType>::PerVertexFromCurrentFaceNormal(poly_m); ScalarType MaxA=0; for (size_t i=0;i<poly_m.face.size();i++) { poly_m.face[i].Q()=PolygonBending(poly_m.face[i]); MaxA=std::max(MaxA,poly_m.face[i].Q()); } return MaxA; } static void InitQualityVertEdgeLenght(PolyMeshType &poly_m) { for (size_t i=0;i<poly_m.vert.size();i++) poly_m.vert[i].Q()=0; for (size_t i=0;i<poly_m.face.size();i++) { for (int j=0;j<poly_m.face[i].VN();j++) { FaceType *f=&poly_m.face[i]; FaceType *f1=f->FFp(j); if (f>f1)continue; ScalarType L=(poly_m.face[i].P0(j)-poly_m.face[i].P1(j)).Norm(); poly_m.face[i].V0(j)->Q()+=L; poly_m.face[i].V1(j)->Q()+=L; } } } static void InterpolateQualityVertFormFaces(PolyMeshType &poly_m) { std::vector<ScalarType> SumW(poly_m.vert.size(),0); for (size_t i=0;i<poly_m.vert.size();i++) poly_m.vert[i].Q()=0; for (size_t i=0;i<poly_m.face.size();i++) { ScalarType AreaF=vcg::PolyArea(poly_m.face[i]); for (size_t j=0;j<poly_m.face[i].VN();j++) { poly_m.face[i].V(j)->Q()+=AreaF*(ScalarType)poly_m.face[i].Q(); size_t IndexV=vcg::tri::Index(poly_m,poly_m.face[i].V(j)); SumW[IndexV]+=AreaF; } } for (size_t i=0;i<poly_m.vert.size();i++) { if (SumW[i]>0) poly_m.vert[i].Q()/=SumW[i]; else poly_m.vert[i].Q()=0; } } static void ClosestPoint(const PolyMeshType &poly_m,const CoordType &pos, int &CloseF,CoordType &ClosePos) { ScalarType minD=std::numeric_limits<ScalarType>::max(); CloseF=-1; for (size_t i=0;i<poly_m.face.size();i++) { CoordType closeTest; ScalarType currD=vcg::PolygonPointDistance(poly_m.face[i],pos,closeTest); if (currD>minD)continue; minD=currD; CloseF=i; ClosePos=closeTest; } } /*! \brief Triangulate a polygonal face with a triangle fan. * \returns pointer to the newly added vertex. */ static VertexPointer Triangulate(PolyMeshType & poly_m, size_t IndexF) { const CoordType bary = vcg::PolyBarycenter(poly_m.face[IndexF]); size_t sizeV = poly_m.face[IndexF].VN(); //add the new vertex VertexPointer newV = &(*vcg::tri::Allocator<PolyMeshType>::AddVertex(poly_m,bary)); //then reupdate the faces for (size_t j=0;j<(sizeV-1);j++) { VertexType * v0=poly_m.face[IndexF].V0(j); VertexType * v1=poly_m.face[IndexF].V1(j); VertexType * v2=newV; vcg::tri::Allocator<PolyMeshType>::AddFaces(poly_m,1); poly_m.face.back().Alloc(3); poly_m.face.back().V(0)=v0; poly_m.face.back().V(1)=v1; poly_m.face.back().V(2)=v2; poly_m.face.back().Q()=poly_m.face[IndexF].Q(); } VertexType * v0=poly_m.face[IndexF].V0((sizeV-1)); VertexType * v1=poly_m.face[IndexF].V1((sizeV-1)); poly_m.face[IndexF].Dealloc(); poly_m.face[IndexF].Alloc(3); poly_m.face[IndexF].V(0)=v0; poly_m.face[IndexF].V(1)=v1; poly_m.face[IndexF].V(2)=newV; return newV; } static void ReorderFaceVert(FaceType &f,const size_t &StartI) { if (StartI==0)return; size_t sizeN=f.VN(); assert(StartI>=0); assert(StartI<sizeN); std::vector<VertexType*> NewV; for (size_t i=0;i<sizeN;i++) { int IndexV=(i+StartI)%sizeN; NewV.push_back(f.V(IndexV)); } //then reset all vertices for (size_t i=0;i<sizeN;i++) f.V(i)=NewV[i]; } static void MergeAlongEdge(PolyMeshType &poly_m, FaceType &f, const size_t &EdgeI) { //cannot be a border assert(f.FFp(EdgeI)!=&f); FaceType *f1=f.FFp(EdgeI); int EdgeI1=f.FFi(EdgeI); //sort first face int FirstV0=(EdgeI+1) % f.VN(); ReorderFaceVert(f,FirstV0); int FirstV1=(EdgeI1+1)%f1->VN(); ReorderFaceVert(*f1,FirstV1); std::vector<VertexType*> NewV; for (size_t i=0;i<(f.VN()-1);i++) NewV.push_back(f.V(i)); for (size_t i=0;i<(f1->VN()-1);i++) NewV.push_back(f1->V(i)); f.Dealloc(); f.Alloc(NewV.size()); for (size_t i=0;i<NewV.size();i++) f.V(i)=NewV[i]; vcg::tri::Allocator<PolyMeshType>::DeleteFace(poly_m,*f1); } static void MergeAlongEdges(PolyMeshType &poly_m, const std::vector<FaceType*> &PolyF, const std::vector<size_t> &EdgeI) { //create a table with all edges that have to be merged std::set<std::pair<CoordType,CoordType> > NeedMerge; for (size_t i=0;i<PolyF.size();i++) { CoordType P0=PolyF[i]->P0(EdgeI[i]); CoordType P1=PolyF[i]->P1(EdgeI[i]); std::pair<CoordType,CoordType> key(std::min(P0,P1),std::max(P0,P1)); NeedMerge.insert(key); } //then cycle and collapse do{ for (size_t i=0;i<poly_m.face.size();i++) { if (poly_m.face[i].IsD())continue; for (size_t j=0;j<poly_m.face[i].VN();j++) { CoordType P0=poly_m.face[i].P0(j); CoordType P1=poly_m.face[i].P1(j); std::pair<CoordType,CoordType> key(std::min(P0,P1),std::max(P0,P1)); if (NeedMerge.count(key)==0)continue; //do the merge MergeAlongEdge(poly_m,poly_m.face[i],j); //remove it NeedMerge.erase(key); break; } } vcg::tri::Allocator<PolyMeshType>::CompactEveryVector(poly_m); }while (!NeedMerge.empty()); } static void Triangulate(PolyMeshType &poly_m, bool alsoTriangles = true, bool OnlyS=false) { size_t size0 = poly_m.face.size(); if (alsoTriangles) { for (size_t i=0; i<size0; i++) { if ((OnlyS)&&(!poly_m.face[i].IsS()))continue; Triangulate(poly_m, i); } } else { for (size_t i=0; i<size0; i++) { if ((OnlyS)&&(!poly_m.face[i].IsS()))continue; if (poly_m.face[i].VN() > 3) { Triangulate(poly_m, i); } } } } }; }//end namespace vcg #endif
dog-days/webpack-launcher
examples/custom/.babelrc.js
<gh_stars>1-10 'use strict'; module.exports = { presets: ['@babel/react'], };
doananh234/gatsby-mysite
src/components/common/Card/index.js
import React from 'react'; import PropTypes from 'prop-types'; import { ThemeContext } from '..'; import CardHeader from './components/CardHeader'; import CardBody from './components/CardBody'; import CardFooter from './components/CardFooter'; import { Wrapper, StyledCard } from './styles'; export const Card = ({ id, link, title, image, description, frontmatter, }) => ( <ThemeContext.Consumer> {({ theme }) => ( <Wrapper id={id} as="a" href={link}> <StyledCard className="shadow-super-light" theme={theme}> <CardHeader {...frontmatter} title={frontmatter.name || title} /> <CardBody image={image} title={title} {...frontmatter} /> <CardFooter description={description} {...frontmatter} /> </StyledCard> </Wrapper> )} </ThemeContext.Consumer> ); Card.propTypes = { id: PropTypes.any, link: PropTypes.string, title: PropTypes.string, image: PropTypes.any, description: PropTypes.string, frontmatter: PropTypes.object, }; Card.defaultProps = { frontmatter: {}, };
ashariati/gtsam-3.2.1
doc/html/a00477.js
<filename>doc/html/a00477.js var a00477 = [ [ "buildFactorSubgraph", "a00477.html#ac06ac82e22341b1b9fdcd4c67280f619", null ], [ "getSubvector", "a00477.html#ae306d44122f0f405fe316e93fcab468a", null ], [ "operator<<", "a00477.html#a9b7724a6c56d8f80e77daf50dfa0170d", null ], [ "operator<<", "a00477.html#ae70a6a8d52d5497f91bfd4e4ecb945a0", null ], [ "operator<<", "a00477.html#ab76d4bf3a01df4d2ff1305da52c83f6c", null ], [ "setSubvector", "a00477.html#a90c21f17922a3cbcf0773eb33386f937", null ], [ "uniqueSampler", "a00477.html#a37fc2f71b5144965a053094fee569a20", null ] ];
jessicaleete/numerical_computing
Python/scipyoptimize/solutionstester.py
<filename>Python/scipyoptimize/solutionstester.py<gh_stars>1-10 import scipy.optimize as opt import numpy as np import solutions as sol prob2=5.488168656962328 prob3=np.array([-0.39965477, -1.21959745, 0.81994268]) prob4=np.array([0.56263117, 132.61958892, -116.26997494]) def fun(x): return np.array([-x[0]+x[1]+x[2], 1+x[0]**3-x[1]**2+x[2]**3, -2-x[0]**2+x[1]**2+x[2]**2]) x=sol.Problem2() if(np.allclose(prob2,x)): print("Problem2 Passed") else: print("Problem2 Falied") print("Your answer:") print(x) print("Correct answer:") print(prob2) x=sol.Problem3() if(np.allclose(fun(prob3),np.zeros(3))): print("Problem3 Passed") else: print("Problem3 Falied") print("Your answer:") print(x) print("A Correct answer:") print(prob3) x=sol.Problem4() if(np.allclose(prob4,x)): print("Problem4 Passed") else: print("Problem4 Falied") print("Your answer:") print(x) print("Correct answer:") print(prob4)
amirsaad2015/dsl
node_modules/@theia/editor/lib/browser/editor.js
<reponame>amirsaad2015/dsl "use strict"; /* * Copyright (C) 2018 TypeFox and others. * * 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 */ Object.defineProperty(exports, "__esModule", { value: true }); var vscode_languageserver_types_1 = require("vscode-languageserver-types"); exports.Position = vscode_languageserver_types_1.Position; exports.Range = vscode_languageserver_types_1.Range; var uri_1 = require("@theia/core/lib/common/uri"); exports.TextEditorProvider = Symbol('TextEditorProvider'); var TextEditorSelection; (function (TextEditorSelection) { function is(e) { return e && e["uri"] instanceof uri_1.default; } TextEditorSelection.is = is; })(TextEditorSelection = exports.TextEditorSelection || (exports.TextEditorSelection = {})); //# sourceMappingURL=editor.js.map
qlcchain/go-virtual-lsobus
orchestra/sonata/address/client/geographic_address_validation/geographic_address_validation_create_responses.go
<reponame>qlcchain/go-virtual-lsobus // Code generated by go-swagger; DO NOT EDIT. package geographic_address_validation // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/qlcchain/go-lsobus/orchestra/sonata/address/models" ) // GeographicAddressValidationCreateReader is a Reader for the GeographicAddressValidationCreate structure. type GeographicAddressValidationCreateReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GeographicAddressValidationCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 201: result := NewGeographicAddressValidationCreateCreated() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewGeographicAddressValidationCreateBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 401: result := NewGeographicAddressValidationCreateUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 403: result := NewGeographicAddressValidationCreateForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewGeographicAddressValidationCreateNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 405: result := NewGeographicAddressValidationCreateMethodNotAllowed() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 422: result := NewGeographicAddressValidationCreateUnprocessableEntity() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewGeographicAddressValidationCreateInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 503: result := NewGeographicAddressValidationCreateServiceUnavailable() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewGeographicAddressValidationCreateCreated creates a GeographicAddressValidationCreateCreated with default headers values func NewGeographicAddressValidationCreateCreated() *GeographicAddressValidationCreateCreated { return &GeographicAddressValidationCreateCreated{} } /*GeographicAddressValidationCreateCreated handles this case with default header values. Created */ type GeographicAddressValidationCreateCreated struct { Payload *models.GeographicAddressValidation } func (o *GeographicAddressValidationCreateCreated) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateCreated %+v", 201, o.Payload) } func (o *GeographicAddressValidationCreateCreated) GetPayload() *models.GeographicAddressValidation { return o.Payload } func (o *GeographicAddressValidationCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.GeographicAddressValidation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateBadRequest creates a GeographicAddressValidationCreateBadRequest with default headers values func NewGeographicAddressValidationCreateBadRequest() *GeographicAddressValidationCreateBadRequest { return &GeographicAddressValidationCreateBadRequest{} } /*GeographicAddressValidationCreateBadRequest handles this case with default header values. Bad Request List of supported error codes: - 20: Invalid URL parameter value - 21: Missing body - 22: Invalid body - 23: Missing body field - 24: Invalid body field - 25: Missing header - 26: Invalid header value - 27: Missing query-string parameter - 28: Invalid query-string parameter value */ type GeographicAddressValidationCreateBadRequest struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateBadRequest) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateBadRequest %+v", 400, o.Payload) } func (o *GeographicAddressValidationCreateBadRequest) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateUnauthorized creates a GeographicAddressValidationCreateUnauthorized with default headers values func NewGeographicAddressValidationCreateUnauthorized() *GeographicAddressValidationCreateUnauthorized { return &GeographicAddressValidationCreateUnauthorized{} } /*GeographicAddressValidationCreateUnauthorized handles this case with default header values. Unauthorized List of supported error codes: - 40: Missing credentials - 41: Invalid credentials - 42: Expired credentials */ type GeographicAddressValidationCreateUnauthorized struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateUnauthorized) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateUnauthorized %+v", 401, o.Payload) } func (o *GeographicAddressValidationCreateUnauthorized) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateForbidden creates a GeographicAddressValidationCreateForbidden with default headers values func NewGeographicAddressValidationCreateForbidden() *GeographicAddressValidationCreateForbidden { return &GeographicAddressValidationCreateForbidden{} } /*GeographicAddressValidationCreateForbidden handles this case with default header values. Forbidden List of supported error codes: - 50: Access denied - 51: Forbidden requester - 52: Forbidden user - 53: Too many requests */ type GeographicAddressValidationCreateForbidden struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateForbidden) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateForbidden %+v", 403, o.Payload) } func (o *GeographicAddressValidationCreateForbidden) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateNotFound creates a GeographicAddressValidationCreateNotFound with default headers values func NewGeographicAddressValidationCreateNotFound() *GeographicAddressValidationCreateNotFound { return &GeographicAddressValidationCreateNotFound{} } /*GeographicAddressValidationCreateNotFound handles this case with default header values. Not Found List of supported error codes: - 60: Resource not found */ type GeographicAddressValidationCreateNotFound struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateNotFound) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateNotFound %+v", 404, o.Payload) } func (o *GeographicAddressValidationCreateNotFound) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateMethodNotAllowed creates a GeographicAddressValidationCreateMethodNotAllowed with default headers values func NewGeographicAddressValidationCreateMethodNotAllowed() *GeographicAddressValidationCreateMethodNotAllowed { return &GeographicAddressValidationCreateMethodNotAllowed{} } /*GeographicAddressValidationCreateMethodNotAllowed handles this case with default header values. Method Not Allowed List of supported error codes: - 61: Method not allowed */ type GeographicAddressValidationCreateMethodNotAllowed struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateMethodNotAllowed) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateMethodNotAllowed %+v", 405, o.Payload) } func (o *GeographicAddressValidationCreateMethodNotAllowed) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateMethodNotAllowed) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateUnprocessableEntity creates a GeographicAddressValidationCreateUnprocessableEntity with default headers values func NewGeographicAddressValidationCreateUnprocessableEntity() *GeographicAddressValidationCreateUnprocessableEntity { return &GeographicAddressValidationCreateUnprocessableEntity{} } /*GeographicAddressValidationCreateUnprocessableEntity handles this case with default header values. Unprocessable entity Functional error - code: 100 message: Too many addresses match - please re-try with more attribute values restriction description: */ type GeographicAddressValidationCreateUnprocessableEntity struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateUnprocessableEntity) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateUnprocessableEntity %+v", 422, o.Payload) } func (o *GeographicAddressValidationCreateUnprocessableEntity) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateUnprocessableEntity) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateInternalServerError creates a GeographicAddressValidationCreateInternalServerError with default headers values func NewGeographicAddressValidationCreateInternalServerError() *GeographicAddressValidationCreateInternalServerError { return &GeographicAddressValidationCreateInternalServerError{} } /*GeographicAddressValidationCreateInternalServerError handles this case with default header values. Internal Server Error List of supported error codes: - 1: Internal error */ type GeographicAddressValidationCreateInternalServerError struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateInternalServerError) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateInternalServerError %+v", 500, o.Payload) } func (o *GeographicAddressValidationCreateInternalServerError) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGeographicAddressValidationCreateServiceUnavailable creates a GeographicAddressValidationCreateServiceUnavailable with default headers values func NewGeographicAddressValidationCreateServiceUnavailable() *GeographicAddressValidationCreateServiceUnavailable { return &GeographicAddressValidationCreateServiceUnavailable{} } /*GeographicAddressValidationCreateServiceUnavailable handles this case with default header values. Service Unavailable */ type GeographicAddressValidationCreateServiceUnavailable struct { Payload *models.ErrorRepresentation } func (o *GeographicAddressValidationCreateServiceUnavailable) Error() string { return fmt.Sprintf("[POST /geographicAddressValidation][%d] geographicAddressValidationCreateServiceUnavailable %+v", 503, o.Payload) } func (o *GeographicAddressValidationCreateServiceUnavailable) GetPayload() *models.ErrorRepresentation { return o.Payload } func (o *GeographicAddressValidationCreateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.ErrorRepresentation) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
davidstl/braincloud-cpp
src/win/CppRestFileUploader.cpp
#ifndef __ANDROID__ #include "braincloud/internal/win/CppRestFileUploader.h" #include <string> #include <iostream> #include <sstream> #include <chrono> #include <thread> #include <cpprest/http_client.h> #include <cpprest/filestream.h> #include "braincloud/http_codes.h" #include "braincloud/reason_codes.h" #include "braincloud/internal/IBrainCloudComms.h" using namespace web::http; namespace BrainCloud { bool CppRestFileUploader::_loggingEnabled = false; CppRestFileUploader::CppRestFileUploader() : _status(IFileUploader::UPLOAD_STATUS_NONE) , _isThreadRunning(false) , _uploadLowTransferRateTimeoutSecs(0) , _uploadLowTransferRateThresholdBytesPerSec(0) , _fileLength(0) , _uploadTotalBytes(0) , _uploadTransferredBytes(0) , _shouldCancelUpload(false) , _httpStatus(0) , _errorReasonCode(0) { } CppRestFileUploader::~CppRestFileUploader() { } void CppRestFileUploader::enableLogging(bool in_loggingEnabled) { _loggingEnabled = in_loggingEnabled; } bool CppRestFileUploader::uploadFile( std::string & in_sessionId, std::string & in_fileUploadId, std::string & in_fileName, int64_t in_fileSize, std::string & in_uploadUrl) { if (_isThreadRunning) { return false; // this class is not re-entrant } _sessionId = in_sessionId; _fileUploadId = in_fileUploadId; _fileName = in_fileName; _fileLength = in_fileSize; _uploadUrl = in_uploadUrl; // this is an underestimation which is later improved upon by the actual http request body size _uploadTotalBytes = _fileLength; _isThreadRunning = true; _status = UPLOAD_STATUS_PENDING; _thread = std::thread(&CppRestFileUploader::run, this); _thread.detach(); return true; } void CppRestFileUploader::setUploadLowTransferRateTimeout(int in_timeoutSecs) { _uploadLowTransferRateTimeoutSecs = in_timeoutSecs; } void CppRestFileUploader::setUploadLowTransferRateThreshold(int in_bytesPerSec) { _uploadLowTransferRateThresholdBytesPerSec = in_bytesPerSec; } void CppRestFileUploader::cancelUpload() { std::unique_lock<std::recursive_mutex> lock(_mutex); _shouldCancelUpload = true; if (_status == UPLOAD_STATUS_UPLOADING) { _cancelTokenSource.cancel(); } } int64_t CppRestFileUploader::getBytesTransferred() { std::unique_lock<std::recursive_mutex> lock(_mutex); return _uploadTransferredBytes; } int64_t CppRestFileUploader::getTotalBytesToTransfer() { std::unique_lock<std::recursive_mutex> lock(_mutex); return _uploadTotalBytes; } double CppRestFileUploader::getProgress() { std::unique_lock<std::recursive_mutex> lock(_mutex); double progress = 0; if (_uploadTotalBytes > 0) { progress = _uploadTransferredBytes / (double)_uploadTotalBytes; } if (progress > 1.0) { progress = 1.0; } return progress; } IFileUploader::eFileUploaderStatus CppRestFileUploader::getStatus() { std::unique_lock<std::recursive_mutex> lock(_mutex); return _status; } const std::string & CppRestFileUploader::getHttpResponse() { return _httpJsonResponse; } int CppRestFileUploader::getHttpStatus() { return _httpStatus; } int CppRestFileUploader::getErrorReasonCode() { return _errorReasonCode; } bool CppRestFileUploader::isThreadRunning() { return _isThreadRunning; } bool CppRestFileUploader::buildHttpBody(const std::string & in_boundary, std::vector<unsigned char> & out_body) { out_body.clear(); std::stringstream ss; std::string httpLineEnd = "\r\n"; std::string endBoundary = "--"; endBoundary += in_boundary; ss << httpLineEnd << endBoundary << httpLineEnd; ss << "Content-Disposition: form-data; name=\"sessionId\"" << httpLineEnd << httpLineEnd; ss << _sessionId << httpLineEnd << endBoundary << httpLineEnd; ss << "Content-Disposition: form-data; name=\"uploadId\"" << httpLineEnd << httpLineEnd; ss << _fileUploadId << httpLineEnd << endBoundary << httpLineEnd; ss << "Content-Disposition: form-data; name=\"fileSize\"" << httpLineEnd << httpLineEnd; ss << _fileLength << httpLineEnd << endBoundary << httpLineEnd; ss << "Content-Disposition: form-data; name=\"uploadFile\"; filename=\"" << _fileName << "\"" << httpLineEnd; ss << "Content-Type: application/octet-stream" << httpLineEnd << httpLineEnd; std::string preFileBody = ss.str(); ss.str(""); ss.clear(); ss << httpLineEnd << endBoundary << "--"; std::string postFileBody = ss.str(); size_t preFileBodyLen = preFileBody.length(); size_t postFileBodyLen = postFileBody.length(); size_t bodyLength = preFileBodyLen + _fileLength + postFileBodyLen; out_body.resize(bodyLength); if (_loggingEnabled) { //std::cout << preFileBody << "XXXXXXXX" << postFileBody << std::endl; } size_t written = 0; for (size_t i = 0; i < preFileBodyLen; ++i, ++written) { out_body[written] = preFileBody[i]; } FILE * fp = NULL; fopen_s(&fp, _fileName.c_str(), "rb"); if (fp == NULL) { if (_loggingEnabled) { std::cout << "#BCC Cannot open file: " << _fileName << std::endl; } return false; } int byteRead = 0; for (size_t i = 0; i < (size_t) _fileLength; ++i, ++written) { byteRead = fgetc(fp); if (byteRead == EOF) { if (_loggingEnabled) { std::cout << "#BCC Unexpected EOF while reading file:" << _fileName << std::endl; } fclose(fp); fp = NULL; return false; } out_body[written] = byteRead; } fclose(fp); fp = NULL; for (size_t i = 0; i < postFileBodyLen; ++i, ++written) { out_body[written] = postFileBody[i]; } _uploadTotalBytes = out_body.size(); return true; } void CppRestFileUploader::progressHandler(web::http::message_direction::direction in_direction, utility::size64_t in_bytesTransferred) { // they say not to lock in this function so I'm being loose if (in_direction == web::http::message_direction::upload) { _uploadTransferredBytes = in_bytesTransferred; } } void CppRestFileUploader::run(void * in_data) { CppRestFileUploader * fileUploader = reinterpret_cast<CppRestFileUploader*>(in_data); { std::unique_lock<std::recursive_mutex> lock(fileUploader->_mutex); fileUploader->_status = UPLOAD_STATUS_UPLOADING; } std::string boundary = "UploaderBoundary"; boundary += fileUploader->_fileUploadId; std::vector<unsigned char> body; if (!fileUploader->buildHttpBody(boundary, body)) { std::unique_lock<std::recursive_mutex> lock(fileUploader->_mutex); fileUploader->_status = UPLOAD_STATUS_COMPLETE_FAILED; fileUploader->_httpStatus = HTTP_CUSTOM; fileUploader->_errorReasonCode = CLIENT_UPLOAD_FILE_UNKNOWN; IBrainCloudComms::createJsonErrorResponse( fileUploader->_httpStatus, fileUploader->_errorReasonCode, "Creating HTTP body failed", fileUploader->_httpJsonResponse); fileUploader->_isThreadRunning = false; return; } utility::string_t url = utility::conversions::to_string_t(fileUploader->_uploadUrl); web::http::client::http_client_config cfg; // the default timeout is 30 seconds. If _uploadOverallTimeoutSecs is default (0) // then this call will set the timeout to be indefinite, otherwise the timeout // will be user-defined if (fileUploader->_uploadLowTransferRateTimeoutSecs > 0) { cfg.set_timeout(utility::seconds(fileUploader->_uploadLowTransferRateTimeoutSecs)); } web::http::client::http_client client(url, cfg); web::http::http_request request; request.set_method(methods::POST); std::string contentType = "multipart/form-data; boundary="; contentType += boundary; utility::string_t utContentType = utility::conversions::to_string_t(contentType); request.headers().add(web::http::header_names::content_type, utContentType); std::stringstream ss; ss << body.size(); std::string contentLength = ss.str(); utility::string_t utContentLength = utility::conversions::to_string_t(contentLength); request.headers().add(web::http::header_names::content_length, utContentLength); request.set_body(body); // brutal code to create a progress callback to a member fn std::function<void(web::http::message_direction::direction in_direction, utility::size64_t in_bytesTransferred)> progressHandler = std::bind(&CppRestFileUploader::progressHandler, fileUploader, std::placeholders::_1, std::placeholders::_2); request.set_progress_handler(progressHandler); pplx::cancellation_token_source cts; pplx::task<web::http::http_response> httpTask = client.request(request, cts.get_token()); { std::unique_lock<std::recursive_mutex> lock(fileUploader->_mutex); fileUploader->_cancelTokenSource = cts; fileUploader->_status = UPLOAD_STATUS_UPLOADING; } pplx::task_status taskStatus = pplx::task_status::canceled; bool requestTimedOut = false; if (!fileUploader->_shouldCancelUpload) { try { taskStatus = httpTask.wait(); // blocks } catch (web::http::http_exception e) { const char * err = e.what(); int errCode = e.error_code().value(); if (errCode == 12002 // timeout || errCode == 12030 // server terminated connection abnormally ) { requestTimedOut = true; } else { if (fileUploader->_loggingEnabled) { // not sure what this error is } } } catch (...) { // oh well... assume it was cancelled } } if (taskStatus == pplx::task_status::canceled) { std::unique_lock<std::recursive_mutex> lock(fileUploader->_mutex); fileUploader->_status = UPLOAD_STATUS_COMPLETE_FAILED; fileUploader->_httpStatus = HTTP_CUSTOM; if (requestTimedOut) { fileUploader->_errorReasonCode = CLIENT_UPLOAD_FILE_TIMED_OUT; IBrainCloudComms::createJsonErrorResponse( fileUploader->_httpStatus, fileUploader->_errorReasonCode, "Upload timed out", fileUploader->_httpJsonResponse); } else { fileUploader->_errorReasonCode = CLIENT_UPLOAD_FILE_CANCELLED; IBrainCloudComms::createJsonErrorResponse( fileUploader->_httpStatus, fileUploader->_errorReasonCode, "Upload cancelled by user", fileUploader->_httpJsonResponse); } } else if (taskStatus == pplx::task_status::completed) { web::http::http_response response = httpTask.get(); pplx::task<utility::string_t> extractTask = response.extract_string(); utility::string_t responseBody = extractTask.get(); fileUploader->_httpInternalResponse = utility::conversions::to_utf8string(responseBody); web::http::status_code httpStatusCode = response.status_code(); fileUploader->_httpStatus = httpStatusCode; std::unique_lock<std::recursive_mutex> lock(fileUploader->_mutex); if (httpStatusCode != web::http::status_codes::OK) { // if there's an error, attempt to parse the response into json, otherwise fake it Json::Value root; Json::Reader reader; if (reader.parse(fileUploader->_httpInternalResponse, root)) { fileUploader->_errorReasonCode = root["reason_code"].asInt(); fileUploader->_httpJsonResponse = fileUploader->_httpInternalResponse; } else { fileUploader->_errorReasonCode = CLIENT_UPLOAD_FILE_UNKNOWN; IBrainCloudComms::createJsonErrorResponse(fileUploader->_httpStatus, fileUploader->_errorReasonCode, fileUploader->_httpInternalResponse, fileUploader->_httpJsonResponse); } //if (httpStatusCode == web::http::status_codes::RequestTimeout // || httpStatusCode == web::http::status_codes::ServiceUnavailable) //{ //} fileUploader->_status = UPLOAD_STATUS_COMPLETE_FAILED; } else { fileUploader->_status = UPLOAD_STATUS_COMPLETE_SUCCESS; fileUploader->_httpJsonResponse = fileUploader->_httpInternalResponse; } } if (_loggingEnabled) { Json::Reader reader; Json::StyledWriter writer; Json::Value root; reader.parse(fileUploader->_httpJsonResponse, root); std::string jsonOutput = writer.write(root); std::cout << "#BCC UPLOADER_INCOMING " << jsonOutput << std::endl; } fileUploader->_isThreadRunning = false; } } #endif //__ANDROID__
MECLabTUDA/ACS
mp/visualization/visualize_imgs.py
<filename>mp/visualization/visualize_imgs.py # ------------------------------------------------------------------------------ # Visualize images (in Numpy, PyTorch or TorchIO formats) and dataloaders. # ------------------------------------------------------------------------------ import os import numpy as np import torch import matplotlib.pyplot as plt import SimpleITK as sitk import math import random from PIL import Image from mp.data.pytorch.transformation import one_output_channel def img_to_numpy_array(x): r"""Transform an image in several formats into a numpy array.""" type_str = str(type(x)) if 'SimpleITK.SimpleITK.Image' in type_str: return sitk.GetArrayFromImage(x) elif 'torchio.data.image.Image' in type_str: return x.tensor.numpy() elif 'torch.Tensor' in type_str: return x.detach().cpu().numpy() elif 'numpy.ndarray' in type_str: return x else: raise NotImplementedError def ensure_channel_width_height_depth(np_array): r"""Ensure the dimensions go channels, width, height(, depth)""" # TODO keep width and height in initial dimensions, right now largest first axis_order = np.argsort(np_array.shape) if len(np_array.shape) == 3: np_array = np_array.transpose( axis_order[0], axis_order[2], axis_order[1]) if len(np_array.shape) == 4: np_array = np_array.transpose( axis_order[0], axis_order[3], axis_order[2], axis_order[1]) return np_array def normalize_range(img_array, max_value=255.): r"""Normalize in range [0, 255]""" img_array /= (img_array.max()/max_value) return img_array.astype(np.uint8) def overlay_images(base, overlay, alpha=0.5): r"""Add transparency to mask, and make composition of image overlayed by transparent mask. """ alpha = int(255*alpha) overlay.putalpha(alpha) return Image.alpha_composite(base, overlay) def stretch_mask_range(mask): r"""Stretches the range of mask values to [0, 255] so that they are differentiable, and converts to RGBA PIL Image. """ if mask.max() != 0: mask *= (255.0/mask.max()) mask = mask.astype(np.uint8) segmask_colors = {1: {'red': 206, 'green': 24, 'blue': 30}, # Red 2: {'red': 64, 'green': 201, 'blue': 204}, # Mint 3: {'red': 250, 'green': 245, 'blue': 56}, # Yellow 4: {'red': 193, 'green': 69, 'blue': 172}, # Purple 5: {'red': 54, 'green': 71, 'blue': 217} # Blue } def color_mask(mask): r"""Converts a mask with integer values that are typically < 5 to an RGBA PIL image which each integer is a differentiable color. """ mask = mask.astype(np.uint8) mask = np.stack((mask,)*3, axis=-1) red, green, blue = mask.T for seg_value, new_color in segmask_colors.items(): to_replace = (red == seg_value) & (blue == seg_value) & (green == seg_value) red[to_replace] = new_color['red'] green[to_replace] = new_color['green'] blue[to_replace] = new_color['blue'] mask = np.array([red, green, blue]).T return mask ### Visualize images, masks and dataloaders using Pillow ### def plot_3d_subject_gt(subject, save_path=None): r"""Plot a subject with input and ground truth""" inputs = subject['x'].data targets = subject['y'].data plot_3d_segmentation(inputs, targets, save_path=save_path) def plot_3d_subject_pred(subject, pred, save_path=None): r"""Plot a subject with input and prediction""" inputs = subject['x'].data assert pred.shape == subject['y'].data.shape, "Prediction has the wrong size." plot_3d_segmentation(inputs, pred, save_path=save_path) def plot_3d_img(img, save_path=None, img_size=(512, 512)): r"""Visualize a 3D image.""" img = img_to_numpy_array(img) if len(img.shape) == 3: # Add channel dimension img = np.expand_dims(img, axis=0) # Ensure (channel, width, height, depth) img = ensure_channel_width_height_depth(img) assert len(img.shape) == 4 and int(img.shape[0]) == 1 # Rotate axis to (depth, 1, width, height) from (1, width, height, depth) img = np.moveaxis(img, -1, 0) # Create 2D image list imgs = [] for ix in range(len(img)): imgs.append(img[ix]) grid_side = int(math.ceil(math.sqrt(len(imgs)))) img_grid = get_img_grid(imgs, grid_side, grid_side) create_img_grid( img_grid=img_grid, save_path=save_path, img_size=img_size) def plot_3d_segmentation( img, segmentation, save_path=None, img_size=(512, 512), alpha=0.5): r"""Visualize a 3D image with coresponding segmentation.""" img = img_to_numpy_array(img) segmentation = img_to_numpy_array(segmentation) assert img.shape == segmentation.shape if len(img.shape) == 3: # Add channel dimension img = np.expand_dims(img, axis=0) segmentation = np.expand_dims(segmentation, axis=0) # Ensure (channel, width, height, depth) img = ensure_channel_width_height_depth(img) segmentation = ensure_channel_width_height_depth(segmentation) assert len(img.shape) == 4 and int(img.shape[0]) == 1 # Rotate axis to (depth, 1, width, height) from (1, width, height, depth) img = np.moveaxis(img, -1, 0) segmentation = np.moveaxis(segmentation, -1, 0) # Create 2D image list imgs = [] for ix in range(len(img)): imgs.append((img[ix], segmentation[ix])) grid_side = int(math.ceil(math.sqrt(len(imgs)))) img_grid = get_img_grid(imgs, grid_side, grid_side) create_x_y_grid( img_grid=img_grid, save_path=save_path, img_size=img_size, alpha=alpha) def get_img_grid(img_list, nr_rows, nr_cols, randomize=False): r"""Place list items in a gris format.""" if randomize: random.shuffle(img_list) img_grid = [[None for i in range(nr_cols)] for j in range(nr_rows)] for j in range(nr_rows): for i in range(nr_cols): if i+j*nr_cols < len(img_list): img_grid[j][i] = img_list[i+j*nr_cols] return img_grid def create_img_grid(img_grid = [[]], img_size = (512, 512), margin = (5, 5), background_color = (255, 255, 255, 255), save_path=None): r"""Visualize a grid with 2d image slices, overlayed with masks.""" bg_width = len(img_grid[0])*img_size[0] + (len(img_grid[0])+1)*margin[0] bg_height = len(img_grid)*img_size[1] + (len(img_grid)+1)*margin[1] new_img = Image.new('RGBA', (bg_width, bg_height), background_color) left = margin[0] top = margin[1] for row in img_grid: for img in row: if img is not None: if img.shape[0]==1: # Grayscale images img = img[0] else: # Colored images if np.argpartition(img.shape, 1)[0] == 0: # Channels first img = np.moveaxis(img, 0, 2) img = normalize_range(img) img = Image.fromarray(img).resize(img_size).convert('RGBA') new_img.paste(img, (left, top)) left += img_size[0] + margin[0] top += img_size[1] + margin[1] left = margin[0] if save_path is None: new_img.show() else: new_img.save(save_path) def create_x_y_grid(img_grid = [[]], img_size = (512, 512), alpha=0.5, margin = (5, 5), background_color = (255, 255, 255, 255), save_path=None): r"""Visualize a grid with 2d image slices, overlayed with masks.""" bg_width = len(img_grid[0])*img_size[0] + (len(img_grid[0])+1)*margin[0] bg_height = len(img_grid)*img_size[1] + (len(img_grid)+1)*margin[1] new_img = Image.new('RGBA', (bg_width, bg_height), background_color) left = margin[0] top = margin[1] for row in img_grid: for img_mask_pair in row: if img_mask_pair is not None: # Is None if grid to large for img nr. img, mask = img_mask_pair if img.shape[0]==1: # Grayscale images img = img[0] # Normalize image values between 0 and 255 img = normalize_range(img) img = Image.fromarray(img).resize(img_size).convert('RGBA') # Stretch the mask values between 0 and 255 mask = mask[0] mask = color_mask(mask) Image.fromarray(mask) Image.fromarray(mask).resize(img_size) mask = Image.fromarray(mask).resize(img_size).convert('RGBA') else: # Colored images if np.argpartition(img.shape, 1)[0] == 0: # If channels first img = np.moveaxis(img, 0, 2) mask = np.moveaxis(mask, 0, 2) img = normalize_range(img) img = Image.fromarray( (img).astype(np.uint8)).resize(img_size).convert('RGBA') mask = Image.fromarray( (mask).astype(np.uint8)).resize(img_size).convert('RGBA') # Overlay images x_y_img = overlay_images(img, mask, alpha=alpha) # Paste into original image new_img.paste(x_y_img, (left, top)) left += img_size[0] + margin[0] top += img_size[1] + margin[1] left = margin[0] if save_path is None: new_img.show() else: new_img.save(save_path) def visualize_dataloader( dataloader, max_nr_imgs=100, save_path=None, img_size=(256, 256)): r"""Visualize images (inputs) from dataloader.""" imgs = get_imgs_from_dataloader(dataloader, max_nr_imgs) grid_side = int(math.ceil(math.sqrt(len(imgs)))) img_grid = get_img_grid(imgs, grid_side, grid_side) create_img_grid(img_grid=img_grid, save_path=save_path, img_size=img_size) def get_imgs_from_dataloader(dataloader, nr_imgs): r"""Get images (inputs) from dataloader and place in list.""" imgs = [] for x, y in dataloader: x = x.cpu().detach().numpy() for img in x: if len(imgs) < nr_imgs: imgs.append(img) if len(imgs) == nr_imgs: break return imgs def visualize_dataloader_with_masks(dataloader, max_nr_imgs=100, save_path=None, img_size=(256, 256), alpha=0.5): r"""Visualize images and masks from dataloader.""" imgs = get_x_y_from_dataloader(dataloader, max_nr_imgs) grid_side = int(math.ceil(math.sqrt(len(imgs)))) img_grid = get_img_grid(imgs, grid_side, grid_side) create_x_y_grid( img_grid=img_grid, save_path=save_path, img_size=img_size, alpha=alpha) def get_x_y_from_dataloader(dataloader, nr_imgs): r"""Get images and masks from dataloader and place in list.""" imgs = [] for x, y in dataloader: x = x.cpu().detach().numpy() # If one channel per label, transform into one mask if y.shape[1] > 1: y = one_output_channel(y, channel_dim=1) y = y.cpu().detach().numpy() if len(x.shape) == 5: # If each x or y is a batch of volumes # Go from shape (batch, 1, width, height, depth) to # (batch*depth, 1, width, height) by shifting the depth channel to # the beginning and concatenating all volumes. x_batch = [np.moveaxis(volume_x, -1, 0) for volume_x in x] y_batch = [np.moveaxis(volume_y, -1, 0) for volume_y in y] x = np.concatenate(x_batch) y = np.concatenate(y_batch) assert len(x.shape) == 4 for ix, img in enumerate(x): if len(imgs) < nr_imgs: imgs.append((img, y[ix])) if len(imgs) == nr_imgs: break return imgs ### Visualize using matplotlib, deprecated ### def plot_overlay_mask(img, mask, save_path=None, figsize=(20, 20)): r""" Compare two 2d imgs, one on top of the other. TODO: background takes on blue tones. """ if 'torch.Tensor' in str(type(img)): img, mask = img.cpu().detach().numpy(), mask.cpu().detach().numpy() while len(img.shape) > 2: img, mask = img[0], mask[0] assert img.shape == mask.shape plt.figure(figsize=figsize, frameon=False) plt.imshow(img, 'gray'), plt.axis('off') plt.imshow(mask, 'jet', alpha=0.7), plt.axis('off') if save_path: plt.savefig(save_path) else: plt.show() def plot_2d_img(img, save_path=None, figsize=(20, 20)): r"""Plot a 2d image""" if 'torch.Tensor' in str(type(img)): img = img.cpu().detach().numpy() while img.shape[0] == 1: img = img[0] if len(img.shape) == 3: # If channels first, rotate so channels last if np.argpartition(img.shape, 1)[0] == 0: img = np.moveaxis(img, 0, 2) # Plot plt.figure(figsize=figsize, frameon=False) plt.imshow(img), plt.axis('off') if save_path: plt.savefig(save_path) else: plt.show()
liangjisheng/C-Cpp
Tools/Unicode/char_wchar_t.cpp
#include <iostream> #include <string> #include <locale> #include <Windows.h> using namespace std; void test() { wchar_t *str = L"ABC我们"; // 强制转化后,字符串数据并没有发生任何变化,只是用多字节字符编码重新 // 对它进行解释,只会输出一个A char *s = (char*)str; cout << s << endl; } // 标准C++库实现字符编码转换 // 如果第二个参数为空,函数返回当前的locale设置,否则依据输入的两个参数设置新 // 的locale,设置成功返回一个描述新的locale的字符串,否则返回一个空指针 // char* setlocale(int category, const char *locale); // pReturnValue指向转换后的字符串长度,sizeOfmbchar是多字节字符串所可能拥有的 // 最大长度,mbstate是一个指向状态字的指针 // errno_t wcstombs_s(size_t *pReturnValue, char *mbchar, size_t sizeOfmbchar, // wchar_t *wchar, mbstate_t *mbstate); // mbstowcs_s() string ws2s(const wstring &ws) { size_t convertedChars = 0; string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C" setlocale(LC_ALL, "chs"); const wchar_t *_source = ws.c_str(); size_t _Dsize = 2 * ws.size() + 1; char *_Dest = new char[_Dsize]; wcstombs_s(&convertedChars, _Dest, _Dsize, _source, _TRUNCATE); string result = _Dest; delete []_Dest; _Dest = NULL; setlocale(LC_ALL, curLocale.c_str()); return result; } wstring s2ws(const string &s) { size_t convertedChars = 0; setlocale(LC_ALL, "chs"); const char *_Sourct = s.c_str(); size_t _Dsize = s.size() + 1; wchar_t *_Dest = new wchar_t[_Dsize]; mbstowcs_s(&convertedChars, _Dest, _Dsize, _Sourct, _TRUNCATE); wstring result = _Dest; delete []_Dest; _Dest = NULL; setlocale(LC_ALL, "C"); return result; } void test_ws_s() { wchar_t *wstr = L"ABC我们"; string obj(ws2s(wstr)); cout << obj << endl; char *str = "ABC我们"; wstring wobj(s2ws(str)); std::wcout.imbue(std::locale("chs")); wcout << wobj << endl; } void test_ws_s_WINAPI() { wchar_t *ws = L"测试字符串"; char *ss = "ABC我们"; int BufSize = 0; // 第一个参数是CP_UTF8是将宽字符转换成UTF8,此时最后两个参数必须设为NULL // 第二个参数dwFlags指定如何处理没有转换的字符,一般设为0 // -1表示转换到字符串结尾 // cbMultiByte,即第5个参数,如果为0,则第四个参数将被忽略,函数返回所需 // 缓冲区的大小 BufSize = WideCharToMultiByte(CP_ACP, 0, ws, -1, NULL, 0, NULL, FALSE); cout << BufSize << endl; char *sp = new char[BufSize]; WideCharToMultiByte(CP_ACP, 0, ws, -1, sp, BufSize, NULL, FALSE); cout << sp << endl; delete [] sp; sp = NULL; BufSize = MultiByteToWideChar(CP_ACP, 0, ss, -1, NULL, 0); cout << BufSize << endl; wchar_t *wp = new wchar_t[BufSize]; MultiByteToWideChar(CP_ACP, 0, ss, -1, wp, BufSize); std::wcout.imbue(std::locale("chs")); std::wcout << wp << endl; delete [] wp; wp = NULL; } int main() { // test_ws_s(); test_ws_s_WINAPI(); system("pause"); return 0; }
dmgerman/camel
components/camel-openstack/src/test/java/org/apache/camel/component/openstack/keystone/ProjectProducerTest.java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.openstack.keystone package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|openstack operator|. name|keystone package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|openstack operator|. name|common operator|. name|OpenstackConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|openstack operator|. name|keystone operator|. name|producer operator|. name|ProjectProducer import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|runner operator|. name|RunWith import|; end_import begin_import import|import name|org operator|. name|mockito operator|. name|ArgumentCaptor import|; end_import begin_import import|import name|org operator|. name|mockito operator|. name|Captor import|; end_import begin_import import|import name|org operator|. name|mockito operator|. name|Mock import|; end_import begin_import import|import name|org operator|. name|mockito operator|. name|junit operator|. name|MockitoJUnitRunner import|; end_import begin_import import|import name|org operator|. name|openstack4j operator|. name|api operator|. name|Builders import|; end_import begin_import import|import name|org operator|. name|openstack4j operator|. name|api operator|. name|identity operator|. name|v3 operator|. name|ProjectService import|; end_import begin_import import|import name|org operator|. name|openstack4j operator|. name|model operator|. name|common operator|. name|ActionResponse import|; end_import begin_import import|import name|org operator|. name|openstack4j operator|. name|model operator|. name|identity operator|. name|v3 operator|. name|Project import|; end_import begin_import import|import name|org operator|. name|openstack4j operator|. name|model operator|. name|network operator|. name|Network import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertNotNull import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|ArgumentMatchers operator|. name|any import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|ArgumentMatchers operator|. name|anyString import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|doReturn import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|verify import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|when import|; end_import begin_class annotation|@ name|RunWith argument_list|( name|MockitoJUnitRunner operator|. name|class argument_list|) DECL|class|ProjectProducerTest specifier|public class|class name|ProjectProducerTest extends|extends name|KeystoneProducerTestSupport block|{ DECL|field|dummyProject specifier|private name|Project name|dummyProject decl_stmt|; annotation|@ name|Mock DECL|field|testOSproject specifier|private name|Project name|testOSproject decl_stmt|; annotation|@ name|Mock DECL|field|projectService specifier|private name|ProjectService name|projectService decl_stmt|; annotation|@ name|Captor DECL|field|projectCaptor specifier|private name|ArgumentCaptor argument_list|< name|Project argument_list|> name|projectCaptor decl_stmt|; annotation|@ name|Captor DECL|field|projectIdCaptor specifier|private name|ArgumentCaptor argument_list|< name|String argument_list|> name|projectIdCaptor decl_stmt|; annotation|@ name|Before DECL|method|setUp () specifier|public name|void name|setUp parameter_list|() block|{ name|when argument_list|( name|identityService operator|. name|projects argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|projectService argument_list|) expr_stmt|; name|producer operator|= operator|new name|ProjectProducer argument_list|( name|endpoint argument_list|, name|client argument_list|) expr_stmt|; name|when argument_list|( name|projectService operator|. name|create argument_list|( name|any argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|testOSproject argument_list|) expr_stmt|; name|when argument_list|( name|projectService operator|. name|get argument_list|( name|anyString argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|testOSproject argument_list|) expr_stmt|; name|List argument_list|< name|Project argument_list|> name|getAllList init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|getAllList operator|. name|add argument_list|( name|testOSproject argument_list|) expr_stmt|; name|getAllList operator|. name|add argument_list|( name|testOSproject argument_list|) expr_stmt|; name|doReturn argument_list|( name|getAllList argument_list|) operator|. name|when argument_list|( name|projectService argument_list|) operator|. name|list argument_list|() expr_stmt|; name|dummyProject operator|= name|createProject argument_list|() expr_stmt|; name|when argument_list|( name|testOSproject operator|. name|getName argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|dummyProject operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|when argument_list|( name|testOSproject operator|. name|getDescription argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|dummyProject operator|. name|getDescription argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|createTest () specifier|public name|void name|createTest parameter_list|() throws|throws name|Exception block|{ name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|OPERATION argument_list|, name|OpenstackConstants operator|. name|CREATE argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|NAME argument_list|, name|dummyProject operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|KeystoneConstants operator|. name|DESCRIPTION argument_list|, name|dummyProject operator|. name|getDescription argument_list|() argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|KeystoneConstants operator|. name|DOMAIN_ID argument_list|, name|dummyProject operator|. name|getDomainId argument_list|() argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|KeystoneConstants operator|. name|PARENT_ID argument_list|, name|dummyProject operator|. name|getParentId argument_list|() argument_list|) expr_stmt|; name|producer operator|. name|process argument_list|( name|exchange argument_list|) expr_stmt|; name|verify argument_list|( name|projectService argument_list|) operator|. name|create argument_list|( name|projectCaptor operator|. name|capture argument_list|() argument_list|) expr_stmt|; name|assertEqualsProject argument_list|( name|dummyProject argument_list|, name|projectCaptor operator|. name|getValue argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getTest () specifier|public name|void name|getTest parameter_list|() throws|throws name|Exception block|{ specifier|final name|String name|id init|= literal|"id" decl_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|OPERATION argument_list|, name|OpenstackConstants operator|. name|GET argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|ID argument_list|, name|id argument_list|) expr_stmt|; name|producer operator|. name|process argument_list|( name|exchange argument_list|) expr_stmt|; name|verify argument_list|( name|projectService argument_list|) operator|. name|get argument_list|( name|projectIdCaptor operator|. name|capture argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|id argument_list|, name|projectIdCaptor operator|. name|getValue argument_list|() argument_list|) expr_stmt|; name|assertEqualsProject argument_list|( name|testOSproject argument_list|, name|msg operator|. name|getBody argument_list|( name|Project operator|. name|class argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getAllTest () specifier|public name|void name|getAllTest parameter_list|() throws|throws name|Exception block|{ name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|OPERATION argument_list|, name|OpenstackConstants operator|. name|GET_ALL argument_list|) expr_stmt|; name|producer operator|. name|process argument_list|( name|exchange argument_list|) expr_stmt|; specifier|final name|List argument_list|< name|Network argument_list|> name|result init|= name|msg operator|. name|getBody argument_list|( name|List operator|. name|class argument_list|) decl_stmt|; name|assertTrue argument_list|( name|result operator|. name|size argument_list|() operator|== literal|2 argument_list|) expr_stmt|; name|assertEquals argument_list|( name|testOSproject argument_list|, name|result operator|. name|get argument_list|( literal|0 argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|updateTest () specifier|public name|void name|updateTest parameter_list|() throws|throws name|Exception block|{ specifier|final name|String name|id init|= literal|"myID" decl_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|OPERATION argument_list|, name|OpenstackConstants operator|. name|UPDATE argument_list|) expr_stmt|; specifier|final name|String name|newName init|= literal|"newName" decl_stmt|; name|when argument_list|( name|testOSproject operator|. name|getId argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|id argument_list|) expr_stmt|; name|when argument_list|( name|testOSproject operator|. name|getName argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|newName argument_list|) expr_stmt|; name|when argument_list|( name|testOSproject operator|. name|getDescription argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"desc" argument_list|) expr_stmt|; name|when argument_list|( name|projectService operator|. name|update argument_list|( name|any argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|testOSproject argument_list|) expr_stmt|; name|msg operator|. name|setBody argument_list|( name|testOSproject argument_list|) expr_stmt|; name|producer operator|. name|process argument_list|( name|exchange argument_list|) expr_stmt|; name|verify argument_list|( name|projectService argument_list|) operator|. name|update argument_list|( name|projectCaptor operator|. name|capture argument_list|() argument_list|) expr_stmt|; name|assertEqualsProject argument_list|( name|testOSproject argument_list|, name|projectCaptor operator|. name|getValue argument_list|() argument_list|) expr_stmt|; name|assertNotNull argument_list|( name|projectCaptor operator|. name|getValue argument_list|() operator|. name|getId argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|newName argument_list|, name|msg operator|. name|getBody argument_list|( name|Project operator|. name|class argument_list|) operator|. name|getName argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|deleteTest () specifier|public name|void name|deleteTest parameter_list|() throws|throws name|Exception block|{ name|when argument_list|( name|projectService operator|. name|delete argument_list|( name|anyString argument_list|() argument_list|) argument_list|) operator|. name|thenReturn argument_list|( name|ActionResponse operator|. name|actionSuccess argument_list|() argument_list|) expr_stmt|; specifier|final name|String name|networkID init|= literal|"myID" decl_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|OPERATION argument_list|, name|OpenstackConstants operator|. name|DELETE argument_list|) expr_stmt|; name|msg operator|. name|setHeader argument_list|( name|OpenstackConstants operator|. name|ID argument_list|, name|networkID argument_list|) expr_stmt|; name|producer operator|. name|process argument_list|( name|exchange argument_list|) expr_stmt|; name|verify argument_list|( name|projectService argument_list|) operator|. name|delete argument_list|( name|projectIdCaptor operator|. name|capture argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|networkID argument_list|, name|projectIdCaptor operator|. name|getValue argument_list|() argument_list|) expr_stmt|; block|} DECL|method|assertEqualsProject (Project old, Project newProject) specifier|private name|void name|assertEqualsProject parameter_list|( name|Project name|old parameter_list|, name|Project name|newProject parameter_list|) block|{ name|assertEquals argument_list|( name|old operator|. name|getName argument_list|() argument_list|, name|newProject operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|old operator|. name|getDescription argument_list|() argument_list|, name|newProject operator|. name|getDescription argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|old operator|. name|getDomainId argument_list|() argument_list|, name|newProject operator|. name|getDomainId argument_list|() argument_list|) expr_stmt|; block|} DECL|method|createProject () specifier|private name|Project name|createProject parameter_list|() block|{ return|return name|Builders operator|. name|project argument_list|() operator|. name|domainId argument_list|( literal|"domain" argument_list|) operator|. name|description argument_list|( literal|"desc" argument_list|) operator|. name|name argument_list|( literal|"project Name" argument_list|) operator|. name|parentId argument_list|( literal|"parent" argument_list|) operator|. name|build argument_list|() return|; block|} block|} end_class end_unit
jsswd888/2020_Summer_JAVA_BILIBILI
Day6/MethodTest06.java
<filename>Day6/MethodTest06.java public class MethodTest06 { public static void main(String[] args) { //调用方法 MethodTest06.m(); //对于方法的修饰符列表当中由static关键字,类名可以不写 //省略的方式 m(); //完整的方式 MethodTest06.m(); //调用其他类(非本类中的)方法 A.doOther(); //注意:当不想调用当前本类中与其他类同名的方法时,必须添加类名 A.m(); //省略类名:编译报错,类名省略以后默认从当前类中寻找doOther方法,但是再当前类中该方法不存在 //doOther(); } public static void m() { System.out.println("m method execute!"); } } class A{ public static void doOther() { System.out.println("doOther method execute!"); } public static void m() { System.out.println("mA method execute!"); } }
sxmatch/taibai-microserviceplatform
taibai-common/taibai-common-core/src/main/java/com/fitmgr/common/core/constant/enums/DiscountTypeEunm.java
<reponame>sxmatch/taibai-microserviceplatform package com.taibai.common.core.constant.enums; import lombok.AllArgsConstructor; import lombok.Getter; /** * 折扣类型:0-系统,1-手动 * * @author Taibai * @date 2020/10/21 16:33 */ @Getter @AllArgsConstructor public enum DiscountTypeEunm { /** * 折扣类型 */ SYSTEM(0, "系统"), MANUAL(1, "手动"); private Integer status; private String msg; }
SoniaZotz/IOsonata
ARM/Nordic/exemples/BleAdvertiser.cpp
<reponame>SoniaZotz/IOsonata<gh_stars>10-100 /**------------------------------------------------------------------------- @example BleAdvertiser.cpp @brief BLE non-connectable advertiser This demo show how to advertise an incremental counter in the manufacturer specific data. The counter increments every second. @author <NAME> @date Dec. 19, 2017 @license MIT License Copyright (c) 2017, I-SYST inc., all rights reserved Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------*/ #include <string.h> #include "app_util.h" #include "istddef.h" #include "ble_app.h" #include "iopinctrl.h" #define DEVICE_NAME "Advertiser" #define APP_ADV_INTERVAL MSEC_TO_UNITS(100, UNIT_0_625_MS) #define APP_ADV_TIMEOUT_IN_SECONDS MSEC_TO_UNITS(1000, UNIT_10_MS) uint32_t g_AdvCnt = 0; const BLEAPP_CFG s_BleAppCfg = { { // Clock config nrf_clock_lf_cfg_t #ifdef IMM_NRF51822 NRF_CLOCK_LF_SRC_RC, // Source RC 1, 1, 0 #else NRF_CLOCK_LF_SRC_XTAL, // Source 32KHz XTAL //NRF_CLOCK_LF_SRC_RC, #ifdef NRF51 0, 0, NRF_CLOCK_LF_XTAL_ACCURACY_20_PPM #else 0, 0, NRF_CLOCK_LF_ACCURACY_20_PPM #endif #endif }, 0, // Number of central link 1, // Number of peripheral link BLEAPP_MODE_NOCONNECT, // Connectionless beacon type DEVICE_NAME, // Device name ISYST_BLUETOOTH_ID, // PnP Bluetooth/USB vendor id 1, // PnP Product ID 0, // Pnp prod version false, // Enable device information service (DIS) NULL, // Pointer device info descriptor (uint8_t*)&g_AdvCnt, // Manufacture specific data to advertise sizeof(g_AdvCnt), // Length of manufacture specific data NULL, 0, BLEAPP_SECTYPE_NONE, // Secure connection type BLEAPP_SECEXCHG_NONE, // Security key exchange NULL, // Service uuids to advertise 0, // Total number of uuids APP_ADV_INTERVAL, // Advertising interval in msec APP_ADV_TIMEOUT_IN_SECONDS, // Advertising timeout in sec 0, // Slow advertising interval, if > 0, fallback to // slow interval on adv timeout and advertise until connected 0, // Min. connection interval 0, // Max. connection interval -1, // Led port nuber -1, // Led pin number 0, 0, // Tx power NULL // RTOS Softdevice handler }; void BlePeriphEvtUserHandler(ble_evt_t * p_ble_evt) { } void BleAppAdvTimeoutHandler() { g_AdvCnt++; BleAppAdvManDataSet((uint8_t*)&g_AdvCnt, sizeof(g_AdvCnt), NULL, 0); BleAppAdvStart(BLEAPP_ADVMODE_FAST); } int main() { BleAppInit((const BLEAPP_CFG *)&s_BleAppCfg, true); BleAppRun(); return 0; }
martarozek/buckit
infra_macros/fbcode_macros/tests/native_rules_test.py
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import tests.utils from tests.utils import dedent class NativeRulesTest(tests.utils.TestCase): import_lines = dedent(""" load("@fbcode_macros//build_defs:native_rules.bzl", "buck_command_alias", "buck_filegroup", "cxx_genrule", "buck_genrule", "buck_python_binary", "buck_python_library", "remote_file", "buck_sh_binary", "buck_sh_test", "versioned_alias", "buck_cxx_binary", "buck_cxx_library", "buck_cxx_test", "test_suite", ) """) @tests.utils.with_project() def test_ungated_rules_propagate_properly(self, root): root.addFile("BUCK", self.import_lines + "\n" + dedent(""" buck_command_alias(name="command_alias", exe=":sh_binary") buck_filegroup(name="filegroup", srcs=["python_library.py"]) cxx_genrule(name="cxx_genrule", out="out.h", cmd="echo > $OUT") buck_genrule(name="genrule", out="out", cmd="echo > $OUT") buck_python_binary(name="python_binary", deps=[":python_library"], main_module="python_binary") buck_python_library(name="python_library", srcs=["python_library.py"]) remote_file( name="file", url="http://example.com/foo", sha1="d8b7ec2e8d5a713858d12bb8a8e22a4dad2abb04", ) buck_sh_binary(name="sh_binary", main="sh_binary.sh") buck_sh_binary(name="sh_binary2.sh") buck_sh_test(name="sh_test", test="sh_test.sh") test_suite(name="all_tests", tests=[":sh_test"]) versioned_alias( name="versioned_alias", versions={ "1.0": ":sh_binary", "1.1": ":sh_binary", }, ) """)) expected = dedent(""" test_suite( name = "all_tests", tests = [ ":sh_test", ], visibility = [ "PUBLIC", ], ) command_alias( name = "command_alias", exe = ":sh_binary", ) cxx_genrule( name = "cxx_genrule", cmd = "echo > $OUT", out = "out.h", ) remote_file( name = "file", sha1 = "d8b7ec2e8d5a713858d12bb8a8e22a4dad2abb04", url = "http://example.com/foo", ) filegroup( name = "filegroup", srcs = [ "python_library.py", ], ) genrule( name = "genrule", cmd = "echo > $OUT", out = "out", ) python_binary( name = "python_binary", main_module = "python_binary", deps = [ ":python_library", ], ) python_library( name = "python_library", srcs = [ "python_library.py", ], ) sh_binary( name = "sh_binary", main = "sh_binary.sh", ) sh_binary( name = "sh_binary2.sh", main = "sh_binary2.sh", ) sh_test( name = "sh_test", test = "sh_test.sh", ) versioned_alias( name = "versioned_alias", versions = { "1.0": ":sh_binary", "1.1": ":sh_binary", }, ) """) results = root.runAudit(["BUCK"]) self.validateAudit({"BUCK": expected}, results) @tests.utils.with_project() def test_python_library_generates_typing_file(self, root): root.addFile("BUCK", self.import_lines + "\n" + dedent(""" buck_python_binary( name="python_binary", deps=[":python_library"], main_module="python_binary", ) buck_python_library( name="python_library", srcs=[ "python_library.py", ], ) """)) expected = dedent(r""" python_binary( name = "python_binary", main_module = "python_binary", deps = [ ":python_library", ], ) python_library( name = "python_library", srcs = [ "python_library.py", ], ) genrule( name = "python_library-typing", cmd = "mkdir -p \"$OUT\"", out = "root", visibility = [ "PUBLIC", ], ) """) root.updateBuckconfig("python", "typing_config", "//python:typing") results = root.runAudit(["BUCK"]) self.validateAudit({"BUCK": expected}, results) @tests.utils.with_project() def test_gated_rules_reject_on_non_whitelisted(self, root): whitelist = ( "cxx_library=foo:bar_lib," "cxx_library=foo:bar_bin," "cxx_test=foo:bar_test" ) root.updateBuckconfig( "fbcode", "forbid_raw_buck_rules", "true") root.updateBuckconfig( "fbcode", "whitelisted_raw_buck_rules", whitelist) prefix = dedent(""" load( "@fbcode_macros//build_defs:native_rules.bzl", "buck_cxx_binary", "buck_cxx_library", "buck_cxx_test" ) """) target1 = prefix + '\nbuck_cxx_binary(name="bin", srcs=["main.cpp"])' target2 = prefix + '\nbuck_cxx_library(name="lib", srcs=["lib.cpp"])' target3 = prefix + '\nbuck_cxx_test(name="test", srcs=["test.cpp"])' root.addFile("target1/BUCK", target1) root.addFile("target2/BUCK", target2) root.addFile("target3/BUCK", target3) result1 = root.runAudit(["target1/BUCK"]) result2 = root.runAudit(["target2/BUCK"]) result3 = root.runAudit(["target3/BUCK"]) self.assertFailureWithMessage( result1, "Unsupported access to Buck rules!", "cxx_binary(): native rule target1:bin is not whitelisted") self.assertFailureWithMessage( result2, "Unsupported access to Buck rules!", "cxx_library(): native rule target2:bin is not whitelisted") self.assertFailureWithMessage( result3, "Unsupported access to Buck rules!", "cxx_test(): native rule target3:bin is not whitelisted") @tests.utils.with_project() def test_gated_rules_accept_on_whitelisted(self, root): whitelist = ( "cxx_binary=foo:bar_bin," "cxx_library=foo:bar_lib," "cxx_test=foo:bar_test" ) root.updateBuckconfig( "fbcode", "forbid_raw_buck_rules", "true") root.updateBuckconfig( "fbcode", "whitelisted_raw_buck_rules", whitelist) contents = dedent(""" load( "@fbcode_macros//build_defs:native_rules.bzl", "buck_cxx_binary", "buck_cxx_library", "buck_cxx_test" ) buck_cxx_binary(name="bar_bin", srcs=["main.cpp"]) buck_cxx_library(name="bar_lib", srcs=["lib.cpp"]) buck_cxx_test(name="bar_test", srcs=["test.cpp"]) """) root.addFile("foo/BUCK", contents) expected = dedent(""" cxx_binary( name = "bar_bin", srcs = [ "main.cpp", ], ) cxx_library( name = "bar_lib", srcs = [ "lib.cpp", ], ) cxx_test( name = "bar_test", srcs = [ "test.cpp", ], ) """) result = root.runAudit(["foo/BUCK"]) self.validateAudit({"foo/BUCK": expected}, result) @tests.utils.with_project() def test_gated_rules_accepted_on_non_whitelisted_if_forbid_disabled(self, root): whitelist = ( "cxx_binary=foo:bar_bin," "cxx_library=foo:bar_lib," "cxx_test=foo:bar_test" ) root.updateBuckconfig( "fbcode", "whitelisted_raw_buck_rules", whitelist) # don't forbid raw_rules by default contents = dedent(""" load( "@fbcode_macros//build_defs:native_rules.bzl", "buck_cxx_binary", "buck_cxx_library", "buck_cxx_test" ) buck_cxx_binary(name="bar_bin", srcs=["main.cpp"]) buck_cxx_library(name="bar_lib", srcs=["lib.cpp"]) buck_cxx_test(name="bar_test", srcs=["test.cpp"]) """) root.addFile("not_foo/BUCK", contents) expected = dedent(""" cxx_binary( name = "bar_bin", srcs = [ "main.cpp", ], ) cxx_library( name = "bar_lib", srcs = [ "lib.cpp", ], ) cxx_test( name = "bar_test", srcs = [ "test.cpp", ], ) """) result = root.runAudit(["not_foo/BUCK"]) self.validateAudit({"not_foo/BUCK": expected}, result)
KaizhiDu/Bingzheng-Mechanical-Management-System
src/main/java/cn/jeeweb/modules/ckgl/service/ICkglJhsService.java
<gh_stars>0 package cn.jeeweb.modules.ckgl.service; import cn.jeeweb.core.common.service.ICommonService; import cn.jeeweb.core.model.PageJson; import cn.jeeweb.core.query.data.Queryable; import cn.jeeweb.modules.ckgl.entity.CkglJhs; /** * Dscription: 仓库管理 - 进货商 * @author : <NAME> * @version : 1.0 * @date : 2018/11/12 13:02 */ public interface ICkglJhsService extends ICommonService<CkglJhs>{ public PageJson<CkglJhs> ajaxJhsList(Queryable queryable, CkglJhs ckglJhs); }
evernife/OpenTerrainGenerator
common/common-util/src/main/java/com/pg85/otg/util/biome/SimpleColorSet.java
<reponame>evernife/OpenTerrainGenerator package com.pg85.otg.util.biome; import java.util.List; import com.pg85.otg.exceptions.InvalidConfigException; import com.pg85.otg.interfaces.IMaterialReader; import com.pg85.otg.util.helpers.StringHelper; public class SimpleColorSet extends ColorSet { public SimpleColorSet(String[] args, IMaterialReader materialReader) throws InvalidConfigException { for (int i = 0; i < args.length - 1; i += 2) { Integer color = StringHelper.readColor(args[i]); float maxNoise = (float) StringHelper.readDouble(args[i + 1], -1, 1); layers.add(new ColorThreshold(color, maxNoise)); } } public SimpleColorSet(List<ColorThreshold> list) { layers = list; } @Override public String toString() { if (this.layers.isEmpty()) { return ""; } StringBuilder stringBuilder = new StringBuilder(); for (ColorThreshold layer : this.layers) { stringBuilder.append("#" + Integer.toHexString(layer.getColor() | 0x1000000).substring(1).toUpperCase()); stringBuilder.append(',').append(' '); stringBuilder.append(layer.maxNoise); stringBuilder.append(',').append(' '); } // Delete last ", " stringBuilder.deleteCharAt(stringBuilder.length() - 2); return stringBuilder.toString(); } }
Zalexanninev15/VitNX
docs/search--/s_1969.js
<filename>docs/search--/s_1969.js search_result['1969']=["topic_0000000000000700.html","ERROR_DS_DRA_REF_NOT_FOUND Field",""];
zhipengzhaocmu/fpga2022_artifact
pigasus/software/src/service_inspectors/http_inspect/http_stream_splitter_finish.cc
<filename>pigasus/software/src/service_inspectors/http_inspect/http_stream_splitter_finish.cc //-------------------------------------------------------------------------- // Copyright (C) 2014-2018 Cisco and/or its affiliates. All rights reserved. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- // http_stream_splitter_finish.cc author <NAME> <<EMAIL>> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "file_api/file_flows.h" #include "http_module.h" #include "http_msg_request.h" #include "http_stream_splitter.h" #include "http_test_input.h" using namespace HttpEnums; bool HttpStreamSplitter::finish(snort::Flow* flow) { snort::Profile profile(HttpModule::get_profile_stats()); HttpFlowData* session_data = (HttpFlowData*)flow->get_flow_data(HttpFlowData::inspector_id); // FIXIT-M - this assert has been changed to check for null session data and return false if so // due to lack of reliable feedback to stream that scan has been called...if that is // addressed in stream reassembly rewrite this can be reverted to an assert //assert(session_data != nullptr); if(!session_data) return false; #ifdef REG_TEST if (HttpTestManager::use_test_output()) { if (HttpTestManager::use_test_input()) { if (!HttpTestManager::get_test_input_source()->finish()) return false; } else { printf("Finish from flow data %" PRIu64 " direction %d\n", session_data->seq_num, source_id); fflush(stdout); } } #endif if (session_data->type_expected[source_id] == SEC_ABORT) { return false; } session_data->tcp_close[source_id] = true; // If there is leftover data for which we returned PAF_SEARCH and never flushed, we need to set // up to process because it is about to go to reassemble(). But we don't support partial start // lines. if ((session_data->section_type[source_id] == SEC__NOT_COMPUTE) && (session_data->cutter[source_id] != nullptr) && (session_data->cutter[source_id]->get_octets_seen() > 0)) { if ((session_data->type_expected[source_id] == SEC_REQUEST) || (session_data->type_expected[source_id] == SEC_STATUS)) { *session_data->get_infractions(source_id) += INF_PARTIAL_START; // FIXIT-M why not use generate_misformatted_http()? session_data->get_events(source_id)->create_event(EVENT_LOSS_OF_SYNC); return false; } uint32_t not_used; prepare_flush(session_data, &not_used, session_data->type_expected[source_id], 0, session_data->cutter[source_id]->get_num_excess(), session_data->cutter[source_id]->get_num_head_lines(), session_data->cutter[source_id]->get_is_broken_chunk(), session_data->cutter[source_id]->get_num_good_chunks(), session_data->cutter[source_id]->get_octets_seen(), true); delete session_data->cutter[source_id]; session_data->cutter[source_id] = nullptr; return true; } // If the message has been truncated immediately following the start line or immediately // following the headers (a body was expected) then we need to process an empty section to // provide an inspection section. Otherwise the start line and headers won't go through // detection. if (((session_data->type_expected[source_id] == SEC_HEADER) || (session_data->type_expected[source_id] == SEC_BODY_CL) || (session_data->type_expected[source_id] == SEC_BODY_CHUNK) || (session_data->type_expected[source_id] == SEC_BODY_OLD)) && (session_data->cutter[source_id] == nullptr) && (session_data->section_type[source_id] == SEC__NOT_COMPUTE)) { // Set up to process empty message section uint32_t not_used; prepare_flush(session_data, &not_used, session_data->type_expected[source_id], 0, 0, 0, false, 0, 0, true); return true; } // If there is no more data to process we need to wrap up file processing right now if ((session_data->section_type[source_id] == SEC__NOT_COMPUTE) && (session_data->file_depth_remaining[source_id] > 0) && (session_data->cutter[source_id] != nullptr) && (session_data->cutter[source_id]->get_octets_seen() == 0)) { if (!session_data->mime_state[source_id]) { snort::FileFlows* file_flows = snort::FileFlows::get_file_flows(flow); const bool download = (source_id == SRC_SERVER); size_t file_index = 0; if (session_data->transaction[source_id] != nullptr) { HttpMsgRequest* request = session_data->transaction[source_id]->get_request(); if ((request != nullptr) and (request->get_http_uri() != nullptr)) { file_index = request->get_http_uri()->get_file_proc_hash(); } } file_flows->file_process(nullptr, 0, SNORT_FILE_END, !download, file_index); } else { session_data->mime_state[source_id]->process_mime_data(flow, nullptr, 0, true, SNORT_FILE_POSITION_UNKNOWN); delete session_data->mime_state[source_id]; session_data->mime_state[source_id] = nullptr; } return false; } return session_data->section_type[source_id] != SEC__NOT_COMPUTE; }
x-meta/xworker
xworker_explorer/src/main/java/xworker/ide/functions/thingeditor/ThingEditorFunctionActions.java
<filename>xworker_explorer/src/main/java/xworker/ide/functions/thingeditor/ThingEditorFunctionActions.java package xworker.ide.functions.thingeditor; import org.xmeta.ActionContext; import org.xmeta.ActionException; import org.xmeta.Thing; import org.xmeta.World; import org.xmeta.util.UtilMap; import xworker.swt.ActionContainer; import xworker.swt.events.SwtListener; public class ThingEditorFunctionActions { public static void selectThingAtOutline(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); Thing thing = getThing(self, actionContext); ActionContainer actions = getThingActions(self, actionContext); actions.doAction("selectThing", UtilMap.toMap(new Object[]{"thing", thing, "refresh", true})); } public static void save(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); ActionContainer actions = getThingActions(self, actionContext); actions.doAction("save"); } public static void refreshOutline(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); ActionContainer actions = getThingActions(self, actionContext); actions.doAction("refreshOutline", UtilMap.toMap(new Object[]{"refreshThing", null})); } public static void openAddChildComposite(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); SwtListener listener = (SwtListener) getObjectFromThingContext("addChildSelectionListener", self, actionContext); listener.handleEvent(null); } public static void openEditComposite(ActionContext actionContext){ Thing self = (Thing) actionContext.get("self"); SwtListener listener = (SwtListener) getObjectFromThingContext("cancelAddChildListener", self, actionContext); listener.handleEvent(null); } public static Object getObjectFromThingContext(String name, Thing self, ActionContext actionContext){ ActionContext thingContext = (ActionContext) actionContext.get("thingContext"); if(thingContext == null){ throw new ActionException("may be not a thing editor enviroment, path=" + self.getMetadata().getPath()); } return thingContext.get(name); } private static ActionContainer getThingActions(Thing self, ActionContext actionContext){ ActionContext thingContext = (ActionContext) actionContext.get("thingContext"); if(thingContext == null){ throw new ActionException("may be not a thing editor enviroment, path=" + self.getMetadata().getPath()); } return (ActionContainer) thingContext.get("actions"); } private static Thing getThing(Thing self, ActionContext actionContext){ Object thingObj = actionContext.get("thing"); Thing thing = null; if(thingObj instanceof String){ thing = World.getInstance().getThing((String) thingObj); }else if(thingObj instanceof Thing){ thing = (Thing) thingObj; }else{ throw new ActionException("thing is null or not a thing, path=" + self.getMetadata().getPath()); } return thing; } }
spasovski/web-client-ui
packages/chart/src/ChartTestUtils.js
<reponame>spasovski/web-client-ui import dh from '@deephaven/jsapi-shim'; class ChartTestUtils { static DEFAULT_CHART_TITLE = 'Chart Title'; static DEFAULT_X_TITLE = 'X Axis'; static DEFAULT_Y_TITLE = 'Y Axis'; static DEFAULT_SERIES_NAME = 'MySeries'; static makeAxis({ label = 'Axis', type = dh.plot.AxisType.X, position = dh.plot.AxisPosition.BOTTOM, formatType = dh.Axis.FORMAT_TYPE_NUMBER, formatPattern = '###,###0.00', log = false, } = {}) { return new dh.Axis({ label, type, position, formatType, formatPattern, log, }); } static makeDefaultAxes() { return [ ChartTestUtils.makeAxis({ label: ChartTestUtils.DEFAULT_X_TITLE, type: dh.plot.AxisType.X, }), ChartTestUtils.makeAxis({ label: ChartTestUtils.DEFAULT_Y_TITLE, type: dh.plot.AxisType.Y, }), ]; } static makeSource({ axis = ChartTestUtils.makeAxis() }) { return new dh.SeriesDataSource({ axis, type: axis.type }); } static makeDefaultSources() { const axes = ChartTestUtils.makeDefaultAxes(); return axes.map(axis => ChartTestUtils.makeSource({ axis })); } static makeSeries({ name = ChartTestUtils.DEFAULT_SERIES_NAME, plotStyle = dh.plot.SeriesPlotStyle.SCATTER, sources = ChartTestUtils.makeDefaultSources(), lineColor = null, shapeColor = null, } = {}) { return new dh.Series(name, plotStyle, sources, lineColor, shapeColor); } static makeChart({ title = ChartTestUtils.DEFAULT_CHART_TITLE, series = [ChartTestUtils.makeSeries()], axes = ChartTestUtils.makeDefaultAxes(), } = {}) { return new dh.Chart({ title, series, axes }); } static makeFigure({ title = 'Figure', charts = [ChartTestUtils.makeChart()], } = {}) { return new dh.plot.Figure({ title, charts }); } } export default ChartTestUtils;
TheCandianVendingMachine/TCVM_Flat_Engine
src/fe/math/random.cpp
<reponame>TheCandianVendingMachine/TCVM_Flat_Engine<gh_stars>1-10 #include "fe/math/random.hpp" #include "fe/feAssert.hpp" #include "fe/typeDefines.hpp" fe::random *fe::random::m_instance = nullptr; void fe::random::startUp() { FE_ASSERT((m_instance == nullptr), "Randomizer instance already created!"); if (!m_instance) { m_instance = this; #ifdef _DEBUG and FE_DEBUG_NO_SEED m_seed = FE_DEFAULT_RANDOM_SEED; #else m_seed = std::random_device{}(); #endif } } void fe::random::useSeed(bool value) { m_hasSeed = value; } void fe::random::setSeed(unsigned int seed) { m_seed = seed; } fe::random &fe::random::get() { return *m_instance; }
Sma-Das/Leetcode
1-Easy/countNegatives.py
""" 90.58% faster """ def countNegatives(list[list[int]]) -> int: return sum(map(lambda x: sum(map(lambda y: 1 if y < 0 else 0, x)), grid))
storopoli/Machine-Learning-Probalistic
pyprobml-master/figgen/daft/pose-eccv18.py
<reponame>storopoli/Machine-Learning-Probalistic # pose model #from matplotlib import rc #rc("font", family="serif", size=12) #rc("text", usetex=True) #rc("text.latex", preamble=open("macros.tex").read()) #import daft import os import imp daft = imp.load_source('daft', 'daft-080308/daft.py') pgm = daft.PGM([4, 4], origin=[0, 0], observed_style="inner") pgm.add_node(daft.Node("k", r"$k$", 1, 1)) pgm.add_node(daft.Node("x", r"$x$", 2, 2)) pgm.add_node(daft.Node("kk", r"$k'$", 3, 2)) pgm.add_edge("k", "x") pgm.add_edge("x", "kk") pgm.add_edge("k", "kk") pgm.render() folder = "/Users/kpmurphy/github/pyprobml/figures" fname = "pose-eccv18" pgm.figure.savefig(os.path.join(folder, "{}.png".format(fname)))
AlbandeCrevoisier/ldd-athens
linux-socfpga/arch/x86/kernel/cpu/bugs.c
<filename>linux-socfpga/arch/x86/kernel/cpu/bugs.c /* * Copyright (C) 1994 <NAME> * * Cyrix stuff, June 1998 by: * - <NAME> (moved everything from head.S), * <<EMAIL>> * - <NAME> (tests & fixes), * - <NAME> (code cleanup). */ #include <linux/init.h> #include <linux/utsname.h> #include <asm/bugs.h> #include <asm/processor.h> #include <asm/processor-flags.h> #include <asm/fpu/internal.h> #include <asm/msr.h> #include <asm/paravirt.h> #include <asm/alternative.h> void __init check_bugs(void) { identify_boot_cpu(); #ifndef CONFIG_SMP pr_info("CPU: "); print_cpu_info(&boot_cpu_data); #endif /* * Check whether we are able to run this kernel safely on SMP. * * - i386 is no longer supported. * - In order to run on anything without a TSC, we need to be * compiled for a i486. */ if (boot_cpu_data.x86 < 4) panic("Kernel requires i486+ for 'invlpg' and other features"); init_utsname()->machine[1] = '0' + (boot_cpu_data.x86 > 6 ? 6 : boot_cpu_data.x86); alternative_instructions(); fpu__init_check_bugs(); }
Dom58/vuba
client/src/pages/DashbardProjectCategory.js
import React, { useContext, useState, useEffect } from 'react'; import { Divider, Grid, Icon, Table, Button, Form, Container, Accordion, Modal } from 'semantic-ui-react'; import { useQuery, useMutation } from '@apollo/react-hooks'; import moment from 'moment'; import { toast } from 'react-toastify'; import { useHistory } from 'react-router-dom'; import displayError from '../helpers/displayError'; import { AuthContext } from '../context/auth'; import MainHeader from '../components/MainHeader'; import LeftSideDashboard from '../components/LeftSideDashboard'; import MainCardsOfDashboard from '../components/dashboardMainCards'; import OnTopOfDashboard from '../components/dashboardOnTopOfMainCards'; import lang from '../utils/translations'; import { searchInTableFunc } from '../helpers/searchInTable'; import Spinner from '../common/Spinner'; import { GET_CATEGORIES, GET_CATEGORY } from '../graphql/queries/projectCategories'; import { CREATE_PROJECT_CATEGORY, DELETE_CATEGORY, UPDATE_CATEGORY } from '../graphql/mutations/projectCategory'; export default function DashbardProjectCategory() { const { user } = useContext(AuthContext); const history = useHistory(); const [activeIndex, setActiveIndex] = useState(1); const [open, setOpen] = useState(false); const [openUpdating, setOpenUpdating ] = useState(false); const [variables, setVariables] = useState({ name: '', description: '', }); const [errors, setErrors] = useState(null); const [loading, setLoading] = useState(false); const [values, setValues] = useState({ id: 0 }); const [theId, setId] = useState(0) const [updateVariables, setUpdateVariables] = useState({ id: values.id, name: '', description: '', createdAt: new Date(), }); const close = () => { setOpen(false); } const onChangeHandle = ({ target: { name, value } }) => { setVariables({ ...variables, [name]: value, }); } const onChangeUpdateHandle = ({ target: { name, value } }) => { setUpdateVariables({ ...updateVariables, [name]: value, }); setErrors({ ...errors, [name]: '', }); }; const handleClick = (e, titleProps) => { const { index } = titleProps; const newIndex = activeIndex === index ? -1 : index; setActiveIndex(newIndex); }; const { data: { getProjectCategories: { data = [] } = {} } = {}, theLoading, error, } = useQuery(GET_CATEGORIES); const { data: { getProjectCategory } = {}, loading: loadingCategory, error: categoryError, } = useQuery(GET_CATEGORY , { variables: { id: theId }, }) || {}; const [createProjectCategory] = useMutation(CREATE_PROJECT_CATEGORY, { update( proxy, { data }, ) { toast.success(`${lang.t('Project Category submitted successffuly!')}`); setLoading(false); return data ? history.push('/dashboard/all/project-categories') : null; }, onError(err) { if (err) { let onerr = err.graphQLErrors[0].message.split(','); setErrors(onerr); displayError(err); } setLoading(false); }, variables: { ...variables }, refetchQueries: [{ query: GET_CATEGORIES }], awaitRefetchQueries: true }); const [deleteProjectCategory, { loading: DeleteLoading }] = useMutation( DELETE_CATEGORY, { update( proxy, { data: { deleteProjectCategory: { message }, }, }, ) { toast.success(`${lang.t(message)}`); }, onError(err) { if (err.graphQLErrors.length > 0) { let onerr = err.graphQLErrors[0].message.split(','); setErrors(onerr); } }, variables: { id: values.id }, refetchQueries: [{ query: GET_CATEGORIES }], awaitRefetchQueries: true }, ); const [updateProjectCategory] = useMutation(UPDATE_CATEGORY, { update(proxy, { data }) { toast.success( `${lang.t('Category updated successfully!')}`, ); }, onError(err) { if (err) { const onerr = err.graphQLErrors[0].message.split(','); setErrors(onerr); displayError(err); } setOpenUpdating(false); }, variables: { ...updateVariables, id: theId, }, refetchQueries: [{ query: GET_CATEGORIES }], awaitRefetchQueries: true }); useEffect(() => { if (getProjectCategory) { setUpdateVariables({ name: getProjectCategory.name, description: getProjectCategory.description, createdAt: getProjectCategory.createdAt, }); } }, [getProjectCategory]); const handleSubmit = async () => { const { name, description } = variables; if (name.length < 4) { toast.error( `${lang.t('Project category name must be atleast four characters!!')}`, ); } else if (description === '') { toast.error( `${lang.t( 'Project description is Required!', )}`, ); } else { setLoading(true); createProjectCategory(); setVariables({ name: '', description: '', }); } } const onClickDelete = (id) => { setOpen(true) setValues({ id: id }); } const onDeleteHandler = () => { deleteProjectCategory(); setOpen(false); } const onClickUpdate = (id) => { setOpenUpdating(true); setId(id); } const onUpdateHandler =() => { updateProjectCategory(); setOpenUpdating(false); } if(errors) { console.log(errors); console.clear(); } if (error) { return ( <> <MainHeader /> <Container> <div className="s-flex-center" style={{ flexDirection: 'column' }} > <h2 style={{ color: 'brown', textAlign: 'center' }}> <Icon name="info circle" /> {error && error.graphQLErrors[0].message}. </h2> <br /> </div> </Container> </> ); } return ( <> <MainHeader /> <Container> <div style={{fontSize: "17px"}} className="about-us-div"> <Divider hidden /> <OnTopOfDashboard /> <MainCardsOfDashboard /> <Grid> <Grid.Column mobile={4} tablet={4} computer={4} style={{ fontSize: '20px' }} > <Divider hidden /> <h1> <Icon name="linkify" /> Links </h1> <Divider hidden /> <LeftSideDashboard /> </Grid.Column> <Grid.Column mobile={12} tablet={12} computer={12}> <Divider hidden /> <Accordion style={{ float: 'right', padding: 5}}> <Accordion.Title active={activeIndex === 0} index={0} onClick={handleClick}> <Button> <Icon name="add circle" /> {lang.t('Add New Project Category')} </Button> </Accordion.Title> <Accordion.Content active={activeIndex === 0} style={{ backgroundColor: 'white', padding: '10px', position: 'absolute',}}> <Form> <Form.Input placeholder="Category name..." name="name" type="text" required value={variables.name} onChange={onChangeHandle} /> <Form.Input placeholder="Description..." name="description" type="text" required value={variables.description} onChange={onChangeHandle} /> </Form> <br /> <Button primary loading={loading} onClick={() => !loading && handleSubmit()}> <Icon name="add circle" /> {lang.t('SAVE CATEGORY')} </Button> </Accordion.Content> </Accordion> <Divider hidden/> <h1> <Icon name="list" /> {lang.t('Project Categories')} </h1> <Divider /> <div> <Form.Input icon="search" iconPosition="left" placeholder="Search..." id="searchInput" onKeyUp={() => searchInTableFunc()} /> </div> <div className="table-responsive" id="tableContainer" style={{marginTop: 20}}> <Table striped id="tableItems"> <Table.Header> <Table.Row> <Table.HeaderCell>No.</Table.HeaderCell> {/* <Table.HeaderCell>Profile</Table.HeaderCell> */} <Table.HeaderCell>Name</Table.HeaderCell> {/* <Table.HeaderCell>Value</Table.HeaderCell> */} <Table.HeaderCell>Description</Table.HeaderCell> <Table.HeaderCell>CreatedAt</Table.HeaderCell> <Table.HeaderCell>Options</Table.HeaderCell> </Table.Row> </Table.Header> {!theLoading ? ( data && data.map((category, index) => ( <Table.Body> <Table.Row key={index + 1}> <Table.Cell>{index + 1}</Table.Cell> <Table.Cell>{category.name}</Table.Cell> {/* <Table.Cell>{category.value}</Table.Cell> */} <Table.Cell>{category.description}</Table.Cell> <Table.Cell> {moment(category.createdAt).format('LL')} </Table.Cell> <Table.Cell> {user && user.role === 'admin' ? ( <> <Button primary icon="edit" title="Edit Category" style={{ color: 'white', }} onClick={() => onClickUpdate(category.id)} /> <Button icon="trash" title="Delete Project Category" style={{ backgroundColor: 'brown', color: 'white', }} onClick={() => onClickDelete(category.id)} /> </> ) : ( ' ' )} </Table.Cell> </Table.Row> { open && ( <Modal size="tiny" open={open} onClose={close}> <Modal.Header>Do you want to delete this category?</Modal.Header> <Modal.Content> <p style={{ color: "black" }}> <b style={{ color: "brown" }}> <i className="info circular icon"></i> </b> If you click on Delete Button, This category will be deleted permanently! </p> </Modal.Content> <Modal.Actions> { DeleteLoading ? <Spinner /> : ( <> <button positive icon='trash' labelPosition='right' content='YES' onClick={onDeleteHandler} className= 'modelButton' style={{ backgroundColor: "#005ac2" }} > Yes </button> <button className= 'modelButton' onClick={() => setOpen(false)} style={{ backgroundColor: "gray" }} > No </button> </> ) } </Modal.Actions> </Modal> ) } {/* +++++++++++++++ Updating ++++++++++++ */} { openUpdating && ( <Modal size="tiny" open={openUpdating} onClose={() => setOpenUpdating(false)} closeIcon > <Modal.Header> UPDATE </Modal.Header> {!loadingCategory && !categoryError ? ( <> <Modal.Content style={{ backgroundColor: '#f1eeee', }} > <div> <h5>Category Name: </h5> <input name="name" type="text" value={updateVariables.name} onChange={onChangeUpdateHandle} /> <h5>Category Name: </h5> <input name="description" type="text" value={updateVariables.description} onChange={onChangeUpdateHandle} /> <h5>CreatedAt: </h5> <input name="createdAt" type="date" value={updateVariables.createdAt} onChange={onChangeUpdateHandle} /> </div> </Modal.Content> <Modal.Actions> <button positive icon='trash' labelPosition='right' content='YES' onClick={onUpdateHandler} className= 'modelButton' style={{ backgroundColor: "#005ac2" }} > Update </button> <button className= 'modelButton' onClick={() => setOpenUpdating(false)} style={{ backgroundColor: "gray" }} > Cancel </button> </Modal.Actions> </> ): <Spinner />} </Modal> ) } </Table.Body> )) ) : ( <Table.Body> <Table.Row> <Table.Cell className="loader-centered"> <Spinner /> </Table.Cell> </Table.Row> </Table.Body> )} </Table> </div> <Divider hidden /> </Grid.Column> </Grid> </div> </Container> </> ); }
CTSNE/NodeDefender
NodeDefender/db/data/sensor/__init__.py
<reponame>CTSNE/NodeDefender<filename>NodeDefender/db/data/sensor/__init__.py import NodeDefender.db.data.sensor.heat import NodeDefender.db.data.sensor.power import NodeDefender.db.data.sensor.event
hjabird/Quad1D
include/HBTK/Generators.h
#pragma once /*//////////////////////////////////////////////////////////////////////////// Generators.h Generate vectors of values. Has functions like linspace, logspace, meshgrid... Copyright 2017 <NAME> 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 <vector> #include <type_traits> #include <cassert> #include <cmath> #include "Checks.h" #include "Constants.h" namespace HBTK { std::vector<double> linspace(double start, double end); std::vector<double> linspace(double start, double end, int number_of_points); template< typename Ty > void linspace(double start, double end, int number_of_points, Ty & target_indexable); std::vector<double> logspace(double start_power, double end_power); std::vector<double> logspace(double start_power, double end_power, int number_of_points); std::vector<double> logspace(double start_power, double end_power, int number_of_points, double base); template< typename Ty > void logspace(double start_power, double end_power, int number_of_points, double base, Ty & target_indexable); std::vector<double> geomspace(double start, double end); std::vector<double> geomspace(double start, double end, int number_of_points); std::vector<double> geomspace(double start, double end, int number_of_points, double base); template< typename Ty > void geomspace(double start, double end, int number_of_points, double base, Ty & target_indexable); std::vector<double> uniform(double value, int number_of_points); template<typename TyStore, typename TyVal> void uniform(TyStore & target_indexable, TyVal fill_value); std::vector<double> semicircspace(double radius); std::vector<double> semicircspace(double radius, double centre); std::vector<double> semicircspace(double radius, double centre, int number_of_points); template< typename Ty > void semicircspace(double radius, double centre, int number_of_points, Ty & target_indexable); } // End Namespace HBTK - Declarations namespace HBTK // Definitions { /// \param start value of first point /// \param end value of last point /// \param number_of_points the number of points to generate. /// \param target_indexable where to put the points - assumed preallocated, floating point. /// /// \brief generate a linearly space container of points template<typename Ty> void linspace(double start, double end, int number_of_points, Ty & target_indexable) { using TyIdx = decltype(target_indexable[0]); static_assert(std::is_floating_point<typename std::remove_reference<TyIdx>::type>::value, "Output container must hold floating points"); static_assert(std::is_reference<TyIdx>::value, "target_indexable[idx] must be something you can assign to."); assert(HBTK::check_finite(start)); assert(HBTK::check_finite(end)); assert(number_of_points > 0); if (number_of_points > 1) { for (int idx = 0; idx < number_of_points; idx++) { target_indexable[idx] = start + idx * (end - start) / (number_of_points - 1); } } else { target_indexable[0] = (start + end) / 2; } return; } template<typename Ty> void logspace(double start, double end, int number_of_points, double base, Ty & target_indexable) { using TyIdx = decltype(target_indexable[0]); static_assert(std::is_floating_point<typename std::remove_reference<TyIdx>::type>::value, "Output container must hold floating points"); static_assert(std::is_reference<TyIdx>::value, "target_indexable[idx] must be something you can assign to."); assert(HBTK::check_finite(start)); assert(HBTK::check_finite(end)); assert(number_of_points > 0); for (int idx = 0; idx < number_of_points; idx++) { auto linear_pos = start + idx * (end - start) / (number_of_points - 1); target_indexable[idx] = pow(base, linear_pos); } return; } template<typename Ty> void geomspace(double start, double end, int number_of_points, double base, Ty & target_indexable) { using TyIdx = decltype(target_indexable[0]); static_assert(std::is_floating_point<typename std::remove_reference<TyIdx>::type>::value, "Output container must hold floating points"); static_assert(std::is_reference<TyIdx>::value, "target_indexable[idx] must be something you can assign to."); assert(HBTK::check_finite(start) && (start > 0)); assert(HBTK::check_finite(end) && (end > 0)); assert(number_of_points > 0); auto log_start = log(start) / log(base); auto log_end = log(end) / log(base); logspace(log_start, log_end, number_of_points, base, target_indexable); return; } /// \param target_indexable where to write points to /// \param uniform_value what to put in each of the values. /// /// \brief fills an indexable object with a given value /// /// Object must have interator that can be assigend to. template<typename TyStore, typename TyVal> void uniform(TyStore & target_indexable, TyVal uniform_value) { using TyIdx = decltype(target_indexable[0]); static_assert(std::is_reference<TyIdx>::value, "target_indexable[idx] must be something you can assign to."); for (int idx = 0; idx < (int) target_indexable.size(); idx++) { target_indexable[idx] = uniform_value; } } /// \param target_indexable where to write points to /// \param radius the radius of the circular distribution - goes from /// centre + radius to centre - radius /// \param number_of_points the number of points to generate. /// \param centre the average value of the distribution /// /// \brief fills an indexable object with a semicircular distribution. /// /// Object must have interator that can be assigend to. /// Imagine you have a semicircle with radii drawn with equal angular spacing. /// The x coords where the radii meet the perimeter are what this returns. /// Half the usual angle is used before the first and last radius so that they /// are not the max or min possible x. /// /// x_n = centre + r * cos( (idx_n + 0.5) * pi / num_points ) template<typename Ty> void semicircspace(double radius, double centre, int number_of_points, Ty & target_indexable) { using TyIdx = decltype(target_indexable[0]); static_assert(std::is_floating_point<typename std::remove_reference<TyIdx>::type>::value, "Output container must hold floating points"); static_assert(std::is_reference<TyIdx>::value, "target_indexable[idx] must be something you can assign to."); assert(HBTK::check_finite(radius)); assert(HBTK::check_finite(centre)); assert(number_of_points > 0); for (int idx = 0; idx < number_of_points; idx++) { auto lin_pos = ((idx + 0.5) * HBTK::Constants::pi<typename std::remove_reference<TyIdx>::type>())/ (number_of_points); target_indexable[idx] = - radius * cos(lin_pos) + centre; } return; } } // End HBTK namespace
no33fewi/saiga
src/saiga/core/imgui/imgui_saiga.h
/** * Copyright (c) 2021 <NAME> * Licensed under the MIT License. * See LICENSE file for more information. */ #pragma once #include "saiga/config.h" #include "saiga/core/imgui/imgui_main_menu.h" #include "saiga/core/math/math.h" #include "saiga/core/time/timer.h" #include "saiga/core/util/Align.h" #include "saiga/core/util/table.h" #include <vector> struct ImDrawList; namespace ImGui { class SAIGA_CORE_API IMConsole : public std::ostream, public std::streambuf { public: IMConsole(const std::string& name = "Console", const Saiga::ivec2& position = {0, 0}, const Saiga::ivec2& size = {500, 250}, bool write_to_cout = false); void render(); void BeginWindow(); void EndWindow(); void RenderTextArea(); // additionally log to the given file. // Note: calling this method will clear the exsisting content! void setOutputFile(const std::string& file); // additonally write to std::cout (default = false) void setWriteToCout(bool b) { writeToCout = b; } // derived int overflow(int c) override; std::string name; Saiga::ivec2 position, size; bool should_render = true; private: bool scrollDownAtNextRender = true; bool writeToCout = false; bool scrollToBottom = true; std::string data; std::shared_ptr<std::ofstream> outFile; std::streambuf* cout_buf; }; // An ImGUi table window where you can add new lines like in Saiga::Table. // Example: // // ImGui::IMTable test_table("Fancy Table", {10, 10}, {"First", "Second"}); // test_table << 2346346 << 1424; // test_table << 23 << 1424; // // test_table.Render(); // class SAIGA_CORE_API IMTable : public Saiga::Table { public: IMTable(const std::string& name, const std::vector<int>& colum_width, const std::vector<std::string>& colum_name); void Render(); public: std::string header; ImGui::IMConsole console; }; class SAIGA_CORE_API Graph { public: Graph(const std::string& name = "Graph", int numValues = 80); virtual ~Graph() {} void addValue(float t); void renderImGui(); void SetName(const std::string& n) { name = n; } protected: virtual void renderImGuiDerived(); std::string name; int numValues; float maxValue = 0; float lastValue = 0; float average = 0; int currentIndex = 0; int r; std::vector<float> values; }; class SAIGA_CORE_API TimeGraph : public Graph { public: TimeGraph(const std::string& name = "Time", int numValues = 80); void addTime(float t); protected: virtual void renderImGuiDerived(); float hzExp = 0; Saiga::Timer timer; }; class SAIGA_CORE_API HzTimeGraph : public Graph { public: HzTimeGraph(const std::string& name = "Hz", int numValues = 80); void addTime(); protected: virtual void renderImGuiDerived(); float hzExp = 0; Saiga::Timer timer; }; class SAIGA_CORE_API ColoredBar { public: using vec4 = Saiga::vec4; using vec2 = Saiga::vec2; struct BarColor { vec4 fill; vec4 outline; }; private: vec2 m_size; BarColor m_back_color; bool m_auto_size; uint32_t m_rows; std::vector<vec2> m_lastCorner; ImDrawList* m_lastDrawList; float m_rounding; int m_rounding_corners; private: void DrawOutlinedRect(const vec2& begin, const vec2& end, const BarColor& color); void DrawRect(const vec2& begin, const vec2& end, const BarColor& color); public: ColoredBar(vec2 size, BarColor background, bool auto_size = false, uint32_t rows = 1, float rounding = 0.0f, int rounding_corners = 0) : m_size(size), m_back_color(background), m_auto_size(auto_size), m_rows(rows), m_lastCorner(rows), m_lastDrawList(nullptr), m_rounding(rounding), m_rounding_corners(rounding_corners) { SAIGA_ASSERT(rows >= 1, "Must have a positive number of rows"); } void renderBackground(); void renderArea(float begin, float end, const BarColor& color, bool outline = true); }; /** * A helper function that checks if a context is present and * if ImGui wants to capture the mouse inputs. * * A typical use-case is to update the camera only if no ImGui widgets are active: * * if (renderer->use_keyboard_input_in_3dview) * { * camera.update(dt); * } * if (renderer->use_mouse_input_in_3dview) * { * camera.interpolate(dt, 0); * } * */ SAIGA_CORE_API bool captureMouse(); SAIGA_CORE_API bool captureKeyboard(); // Similar to ImGui::Combo but with C++ strings instead of a char array. SAIGA_CORE_API bool StringCombo(const char* label, int* current_item, const std::vector<std::string>& data); } // namespace ImGui namespace Saiga { enum class ImGuiTheme : int { SAIGA = 0, IMGUI, // imgui default theme }; struct SAIGA_CORE_API ImGuiParameters { // imgui parameters bool enable = true; std::string font = "SourceSansPro-Regular.ttf"; int fontSize = 18; float fontBrightness = 2; ImGuiTheme theme = ImGuiTheme::SAIGA; /** * Reads all paramters from the given config file. * Creates the file with the default values if it doesn't exist. */ void fromConfigFile(const std::string& file); }; SAIGA_CORE_API void initImGui(const ImGuiParameters& params); // The main console from saiga SAIGA_CORE_API extern ImGui::IMConsole console; } // namespace Saiga
KimGulmatico/Stacktrek
src/frontend/pages/main/notificationTab/RequestItem.js
import React from 'react' import { List, Button, Icon, Card } from 'antd' import PropTypes from 'prop-types' import ProfilePicture from '../../../components/profilePicture' class Request extends React.Component { constructor(props) { super(props) this.renderRequestType = this.renderRequestType.bind(this) this.renderDescription = this.renderDescription.bind(this) } renderRequestType() { const { request } = this.props switch (request.type) { case 'ATTEST_SKILL': return 'ATTEST' case 'CONNECT_USER': return 'CONNECT' default: return null } } renderDescription() { const { request } = this.props switch (request.type) { case 'ATTEST_SKILL': return `Sent an attestation request on ${request.data.name}` case 'ATTEST_EXPERIENCE': return `Sent an attestation request as a ${request.data.title} on ${request.data.company} from ${new Date(request.data.dateFrom).getFullYear()} to ${new Date(request.data.dateTo).getFullYear()}` case 'CONNECT_USER': return 'Wants to connect with you' default: return null } } render() { const { request, onApprove, onReject } = this.props return ( <Card> <List.Item style={{ padding: '0px', margin: '0px' }} actions={[ <Button type="primary" ghost onClick={() => onApprove(JSON.stringify(request))} ><Icon type="check" />Yes</Button>, <Button type="danger" ghost onClick={() => onReject(request._id)}><Icon type="close" />No</Button>, ]} > <List.Item.Meta avatar={<ProfilePicture facebookId={request.senderFBID} width="42px" height="42px" />} title={<a href={`/#/user/${request.senderFBID}`} style={{ color: 'inherit' }}>{request.senderName}</a>} description={this.renderDescription()} /> <div>{this.renderRequestType()}</div> </List.Item> </Card> ) } } Request.propType = { name: PropTypes.object.isRequired, onReject: PropTypes.func.isRequired, onApprove: PropTypes.func.isRequired, } export default Request
dsabanin/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/lang/resolve2/ResolveTestBase.scala
package org.jetbrains.plugins.scala.lang.resolve2 import _root_.org.jetbrains.plugins.scala.lang.resolve.ScalaResolveTestCase import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference import com.intellij.psi.{PsiElement, PsiReference} import org.jetbrains.plugins.scala.extensions._ import org.jetbrains.plugins.scala.lang.psi.api.base.ScReference import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTypeDefinition import org.junit.Assert._ /** * Pavel.Fatin, 02.02.2010 */ abstract class ResolveTestBase extends ScalaResolveTestCase { val pattern = """/\*\s*(.*?)\s*\*/\s*""".r type Parameters = Map[String, String] val Resolved = "resolved" // default: true val Name = "name" // default: reference name val File = "file" // default: this (if line or offset provided) val Line = "line" val Offset = "offset" val Length = "length" val Type = "type" val Path = "path" val Applicable = "applicable" // default: true val Accessible = "accessible" // default: true val Parameters = List(Resolved, Name, File, Line, Offset, Length, Type, Path, Applicable, Accessible) var options: List[Parameters] = List() var references: List[PsiReference] = List() override def setUp(): Unit = { super.setUp() configureReferences() } override def folderPath: String = { super.folderPath + "resolve2/" } def configureReferences(): PsiReference = { options = List() references = List() val matches = pattern.findAllIn(getFileAdapter.getText).matchData for (m <- matches) { val parameters = parseParameters(m.group(1)) val reference = getFileAdapter.findReferenceAt(m.end) assertKnown(parameters) assertNotNull("No reference found at offset " + m.end, references) options = parameters :: options references = reference :: references } options = options.reverse references = references.reverse assertFalse("At least one expectation must be specified", references.isEmpty) assertEquals("Options number", references.size, options.size) null } def assertKnown(parameters: Parameters): Unit = { for ((key, value) <- parameters) { assertTrue("Unknown parameter: " + key + "\nAllowed: " + Parameters.mkString(", "), Parameters.contains(key)) } } def parseParameters(s: String): Parameters = { if (s.isEmpty) Map() else Map(s.split("""\s*,\s*""").map(_.trim).map { (it: String) => val parts = it.split("""\s*:\s*""") (parts(0), parts(1)) }.toSeq: _*) } def doTest(): Unit = doTestImpl() private def doTestImpl(): Unit = references.zip(options).foreach { it => it._1 match { case ref: ScReference => doEachTest(ref, it._2) case ref: PsiMultiReference => val hostReferences = ref.getReferences if (hostReferences.length == 2) { hostReferences.find(_.isInstanceOf[ScReference]) match { case Some(r: ScReference) => doEachTest(r, it._2) case _ => assert(assertion = false, message = "Multihost references are not supported") } } else { assert(assertion = false, message = "Multihost references are not supported") } } } def doEachTest(reference: ScReference, options: Parameters): Unit = { val referenceName = reference.refName val result = reference.bind() val (target, accessible, applicable) = if(result.isDefined) ( result.get.element, result.get.isAccessible, result.get.isApplicable()) else (null, true, true) def message = format(getFileAdapter.getText, _: String, lineOf(reference)) def assertEquals(name: String, v1: Any, v2: Any): Unit = { if(v1 != v2) fail(message(name + " - expected: " + v1 + ", actual: " + v2)) } if (options.contains(Resolved) && options(Resolved) == "false") { assertNull(message(referenceName + " must NOT be resolved!"), target) } else { assertNotNull(message(referenceName + " must BE resolved!"), target) if (options.contains(Accessible) && options(Accessible) == "false") { assertFalse(message(referenceName + " must NOT be accessible!"), accessible) } else { assertTrue(message(referenceName + " must BE accessible!"), accessible) } if (options.contains(Applicable) && options(Applicable) == "false") { assertFalse(message(referenceName + " must NOT be applicable!"), applicable) } else { assertTrue(message(referenceName + " must BE applicable! " + result.get.problems.mkString("(", ",", ")")), applicable) } if (options.contains(Path)) { assertEquals(Path, options(Path), target.asInstanceOf[ScTypeDefinition].qualifiedName) } if (options.contains(File) || options.contains(Offset) || options.contains(Line)) { val actual = target.getContainingFile.getVirtualFile.getNameWithoutExtension val expected = if (!options.contains(File) || options(File) == "this") { reference.getElement.getContainingFile.getVirtualFile.getNameWithoutExtension } else options(File) assertEquals(File, expected, actual) } val expectedName = if (options.contains(Name)) options(Name) else referenceName assertEquals(Name, expectedName, target.name) if (options.contains(Line)) { assertEquals(Line, options(Line).toInt, lineOf(target)) } if (options.contains(Offset)) { assertEquals(Offset, options(Offset).toInt, target.getTextOffset) } if (options.contains(Length)) { assertEquals(Length, options(Length).toInt, target.getTextLength) } if (options.contains(Type)) { val expectedClass = Class.forName(options(Type)) val targetClass = target.getClass val text = Type + " - expected: " + expectedClass.getSimpleName + ", actual: " + targetClass.getSimpleName assertTrue(message(text), expectedClass.isAssignableFrom(targetClass)) } } } private def lineOf(element: PsiElement) = element.getContainingFile.getText.substring(0, element.getTextOffset).count(_ == '\n') + 1 private def format(text: String, message: String, line: Int) = { val lines = text.linesIterator.zipWithIndex.map(p => if (p._2 + 1 == line) p._1 + " // " + message else p._1) "\n\n" + lines.mkString("\n") + "\n" } }
glomie/my_template
src/main/java/com/temp/cube/output/OutputManager.java
package com.temp.cube.output; public class OutputManager { private static final ConsolePrint consolePrint = new ConsolePrint(); public static ConsolePrint useDefaultOutput() { return consolePrint; } }
programer-0/rocketmq-streams
rocketmq-streams-script/src/main/java/org/apache/rocketmq/streams/script/operator/impl/JPythonScriptOperator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.rocketmq.streams.script.operator.impl; import com.alibaba.fastjson.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.rocketmq.streams.common.context.AbstractContext; import org.apache.rocketmq.streams.common.context.IMessage; import org.apache.rocketmq.streams.common.context.Message; import org.apache.rocketmq.streams.script.context.FunctionContext; import org.apache.rocketmq.streams.script.operator.AbstractScriptOperator; import org.python.util.PythonInterpreter; /** * 实现思路,通过INNER_MESSAG 把message的jsonobject传给python,python中直接操作jsonobject */ public class JPythonScriptOperator extends AbstractScriptOperator { protected static final Log LOG = LogFactory.getLog(JPythonScriptOperator.class); protected transient PythonInterpreter interpreter; @Override protected boolean initConfigurable() { try { super.initConfigurable(); Properties props = new Properties(); props.put("python.console.encoding", "UTF-8"); props.put("python.security.respectJavaAccessibility", "false"); props.put("python.import.site", "false"); Properties preprops = System.getProperties(); PythonInterpreter.initialize(props, preprops, new String[] {}); // 实例化环境和代码执行 interpreter = new PythonInterpreter(); interpreter.exec("import sys"); registFunction(); } catch (Exception e) { LOG.error("jython init error " + getValue(), e); return false; } return true; } @Override public List<IMessage> doMessage(IMessage message, AbstractContext context) { interpreter.set(INNER_MESSAG, message.getMessageBody()); interpreter.exec(getValue()); List<IMessage> messages = new ArrayList<>(); messages.add(message); return messages; } public static void main(String[] args) { JPythonScriptOperator pythonScript = new JPythonScriptOperator(); pythonScript.setValue("_msg.put('age',18);"); pythonScript.init(); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "chris"); Message message = new Message(jsonObject); pythonScript.doMessage(message, new FunctionContext(message)); System.out.println(jsonObject); } @Override public List<String> getScriptsByDependentField(String fieldName) { throw new RuntimeException("can not support this method:getScriptsByDependentField"); } @Override public Map<String, List<String>> getDependentFields() { return null; } }
andrewseidl/chrono
src/chrono_vehicle/tracked_vehicle/ChTrackContactManager.cpp
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: <NAME> // ============================================================================= // // Classes for monitoring contacts of tracked vehicle subsystems. // // ============================================================================= #include "chrono_vehicle/tracked_vehicle/ChTrackContactManager.h" #include "chrono_vehicle/tracked_vehicle/ChTrackedVehicle.h" namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- ChTrackContactManager::ChTrackContactManager() : m_initialized(false), m_flags(0), m_collect(false), m_shoe_index_L(0), m_shoe_index_R(0) { } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChTrackContactManager::Process(ChTrackedVehicle* vehicle) { if (m_flags == 0) return; // Initialize the manager if not already done. if (!m_initialized) { m_sprocket_L = vehicle->GetTrackAssembly(LEFT)->GetSprocket(); m_sprocket_R = vehicle->GetTrackAssembly(RIGHT)->GetSprocket(); m_shoe_L = vehicle->GetTrackAssembly(LEFT)->GetTrackShoe(m_shoe_index_L); m_shoe_R = vehicle->GetTrackAssembly(RIGHT)->GetTrackShoe(m_shoe_index_R); m_idler_L = vehicle->GetTrackAssembly(LEFT)->GetIdler(); m_idler_R = vehicle->GetTrackAssembly(RIGHT)->GetIdler(); m_initialized = true; } // Clear lists m_sprocket_L_contacts.clear(); m_sprocket_R_contacts.clear(); m_shoe_L_contacts.clear(); m_shoe_R_contacts.clear(); m_idler_L_contacts.clear(); m_idler_R_contacts.clear(); // Traverse all system contacts and extract information. vehicle->GetSystem()->GetContactContainer()->ReportAllContacts(this); // Collect contact information data. //// TODO... if (m_collect) { m_csv << vehicle->GetChTime(); // Left sprocket m_csv << m_sprocket_L_contacts.size(); for (auto it = m_sprocket_L_contacts.begin(); it != m_sprocket_L_contacts.end(); ++it) { m_csv << m_sprocket_L->GetGearBody()->TransformPointParentToLocal(it->m_point); } m_csv << std::endl; } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- bool ChTrackContactManager::ReportContactCallback(const ChVector<>& pA, const ChVector<>& pB, const ChMatrix33<>& plane_coord, const double& distance, const ChVector<>& react_forces, const ChVector<>& react_torques, ChContactable* modA, ChContactable* modB) { ChTrackContactInfo info; // Ignore contacts with zero force. if (react_forces.IsNull()) return true; // Extract contacts on sprockets. if (IsFlagSet(TrackCollide::SPROCKET_LEFT)) { if (modA == m_sprocket_L->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_L_contacts.push_back(info); } if (modB == m_sprocket_L->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_L_contacts.push_back(info); } } if (IsFlagSet(TrackCollide::SPROCKET_RIGHT)) { if (modA == m_sprocket_R->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_R_contacts.push_back(info); } if (modB == m_sprocket_R->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_sprocket_R_contacts.push_back(info); } } // Extract contacts on track shoes (discard contacts with sprockets) if (IsFlagSet(TrackCollide::SHOES_LEFT)) { if (modA == m_shoe_L->GetShoeBody().get() && modB != m_sprocket_L->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_L_contacts.push_back(info); } if (modB == m_shoe_L->GetShoeBody().get() && modA != m_sprocket_L->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_L_contacts.push_back(info); } } if (IsFlagSet(TrackCollide::SHOES_RIGHT)) { if (modA == m_shoe_R->GetShoeBody().get() && modB != m_sprocket_R->GetGearBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_R_contacts.push_back(info); } if (modB == m_shoe_R->GetShoeBody().get() && modA != m_sprocket_R->GetGearBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_shoe_R_contacts.push_back(info); } } // Extract contacts on idler wheels. if (IsFlagSet(TrackCollide::IDLER_LEFT)) { if (modA == m_idler_L->GetWheelBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_L_contacts.push_back(info); } if (modB == m_idler_L->GetWheelBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_L_contacts.push_back(info); } } if (IsFlagSet(TrackCollide::IDLER_RIGHT)) { if (modA == m_idler_R->GetWheelBody().get()) { info.m_point = pA; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_R_contacts.push_back(info); } if (modB == m_idler_R->GetWheelBody().get()) { info.m_point = pB; info.m_csys = plane_coord; info.m_force = react_forces; info.m_torque = react_torques; m_idler_R_contacts.push_back(info); } } // Continue scanning contacts return true; } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChTrackContactManager::WriteContacts(const std::string& filename) { if (m_collect && m_flags != 0) m_csv.write_to_file(filename); } } // end namespace vehicle } // end namespace chrono
haydarai/rheem
rheem-platforms/rheem-spark/src/test/java/org/qcri/rheem/spark/operators/SparkDistinctOperatorTest.java
<reponame>haydarai/rheem package org.qcri.rheem.spark.operators; import org.junit.Assert; import org.junit.Test; import org.qcri.rheem.core.platform.ChannelInstance; import org.qcri.rheem.core.types.DataSetType; import org.qcri.rheem.spark.channels.RddChannel; import java.util.Arrays; import java.util.List; /** * Test suite for {@link SparkDistinctOperator}. */ public class SparkDistinctOperatorTest extends SparkOperatorTestBase { @Test public void testExecution() { // Prepare test data. List<Integer> inputData = Arrays.asList(0, 1, 1, 6, 2, 2, 6, 6); // Build the distinct operator. SparkDistinctOperator<Integer> distinctOperator = new SparkDistinctOperator<>( DataSetType.createDefaultUnchecked(Integer.class) ); // Set up the ChannelInstances. final ChannelInstance[] inputs = new ChannelInstance[]{this.createRddChannelInstance(inputData)}; final ChannelInstance[] outputs = new ChannelInstance[]{this.createRddChannelInstance()}; // Execute. this.evaluate(distinctOperator, inputs, outputs); // Verify the outcome. final List<Integer> result = ((RddChannel.Instance) outputs[0]).<Integer>provideRdd().collect(); Assert.assertEquals(4, result.size()); Assert.assertEquals(Arrays.asList(0, 1, 6, 2), result); } }
mzegar/node-rapids
modules/cudf/src/addon.cpp
<reponame>mzegar/node-rapids // Copyright (c) 2020-2021, NVIDIA CORPORATION. // // 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. #include "node_cudf/column.hpp" #include "node_cudf/groupby.hpp" #include "node_cudf/scalar.hpp" #include "node_cudf/table.hpp" #include "node_cudf/utilities/dtypes.hpp" #include <nv_node/addon.hpp> #include <nv_node/macros.hpp> #include <napi.h> struct node_cudf : public nv::EnvLocalAddon, public Napi::Addon<node_cudf> { node_cudf(Napi::Env const& env, Napi::Object exports) : EnvLocalAddon(env, exports) { DefineAddon(exports, { InstanceMethod("init", &node_cudf::InitAddon), InstanceValue("_cpp_exports", _cpp_exports.Value()), InstanceMethod<&node_cudf::find_common_type>("findCommonType"), InstanceValue("Column", InitClass<nv::Column>(env, exports)), InstanceValue("Table", InitClass<nv::Table>(env, exports)), InstanceValue("Scalar", InitClass<nv::Scalar>(env, exports)), InstanceValue("GroupBy", InitClass<nv::GroupBy>(env, exports)), }); } private: Napi::Value find_common_type(Napi::CallbackInfo const& info) { return nv::find_common_type(info); } }; NODE_API_ADDON(node_cudf);
10088/swc
crates/swc_ecma_minifier/tests/terser/compress/reduce_vars/cond_assign/output.mangleOnly.js
!(function() { var a; void 0 ? (a = 1) : 0; console.log(a); })();
huanghongxun/ACM
vijos/p1891_2.cpp
<filename>vijos/p1891_2.cpp<gh_stars>1-10 #include <cstdio> #include <cstring> #define inf 2147483647 #define FOR(i,j,k) for(i=j;i<=k;i++) #define ll long long using namespace std; ll read() { ll x = 0, f = 1; char ch = getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x * f; } template<int N, int M> class EdmondsKarp { private: ll h[N], v[M], w[M], p[M], c[M], cnt; ll n, m, ans, s, t; ll q[N * 4], pre[N], dis[N]; bool vis[M]; bool spfa() { memset(pre, -1, sizeof pre); int i, f = 0, r = 0; for(i = 0; i <= n; i ++) dis[i] = inf, vis[i] = 0; dis[s] = 0, q[r++] = s, vis[s] = 1; pre[s] = pre[t] = -1; while (f < r) { int u = q[f++]; for(i = h[u]; i != -1; i = p[i]) { if(w[i] && dis[v[i]] > dis[u] + c[i]){ dis[v[i]] = dis[u] + c[i]; pre[v[i]] = i ^ 1; if(!vis[v[i]]) { vis[v[i]] = 1; q[r++] = v[i]; } } } vis[u] = 0; } if(dis[t] == inf) return 0; return 1; } void end() { ll u, sum = inf; for(u = pre[t]; u >= 0; u = pre[v[u]]) sum = sum > w[u ^ 1] ? w[u ^ 1] : sum; for(u = pre[t]; u >= 0; u = pre[v[u]]) { w[u] += sum; w[u^1] -= sum; ans += sum * c[u^1]; } } public: void init(ll o, ll a, ll b) { n = o, s = a, t = b, cnt = 0; memset(h,-1,sizeof(h)); } void add(ll x, int y, ll ca, ll co) { v[cnt] = y, w[cnt] = ca, c[cnt] = co, p[cnt] = h[x], h[x] = cnt++; v[cnt] = x, w[cnt] = 0, c[cnt] = -co, p[cnt] = h[y], h[y] = cnt++; } ll run() { ans = 0; while(spfa()) end(); return ans; } }; ll c[1024]; ll build(int n, int k, ll *c) { int SS = 0, TT = 2 * n + 3, S = 1, T = 2 * n + 2, i; EdmondsKarp<1024, 131072> *g = new EdmondsKarp<1024, 131072>(); g->init(TT, SS, TT); g->add(SS, S, k, 0); g->add(T, TT, k, 0); FOR(i, 2, n + 1) g->add(S, i, 1, -c[i - 1]); FOR(i, n + 2, 2 * n + 1) g->add(i - n, i, 1, -c[i - 1]); FOR(i, n + 2, 2 * n + 1) g->add(i, T, 1, -c[i - 1 + n]); FOR(i, 2, 2 * n + 2) g->add(i - 1, i, k, 0); return -g->run(); } int main() { int n = read(), k = read(); for(int i=1;i<=3*n;i++) c[i] = read(); printf("%I64d", build(n, k, c)); return 0; }
sentinel-hub/customScripts
sentinel-3/enhanced_true_color/script.js
// Sentinel-3 - Enhanced natural colors // Author: <NAME> (Twitter: @annamaria_84, http://www.linkedin.com/in/annamaria-luongo-RS) // CC BY 4.0 International - https://creativecommons.org/licenses/by/4.0/ function stretch(val, min, max) { return (val-min)/(max-min); } var brightness = 1.0; // default value is 1.0 for land, brightness<=0.3 for clouds or snow/ice; var index = (B04-B08)/(B06+B09); // used for enhance sea visualization var band1 = brightness * (stretch(B09, 0, 0.25)-0.1*stretch(B14, 0, 0.1)); var band2 = brightness * (1.1*stretch(B06, 0, 0.25)-0.1* stretch(B14, 0, 0.1)); var band3 = brightness * (stretch(B04, 0, 0.25)-0.1*stretch(B14, 0, 0.1)+.01*stretch(index, 0.5, 1)); return [ band1, band2, band3];
tkf/compapp
src/compapp/plugins/__init__.py
<gh_stars>0 from .datastores import * from .recorders import * from .misc import * from .vcs import RecordVCS from .timing import RecordTiming from .programinfo import RecordProgramInfo from .sysinfo import RecordSysInfo from .metastore import MetaStore
kit-transue/software-emancipation-discover
model_server/gala/src/gString.cxx
<filename>model_server/gala/src/gString.cxx /************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 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. * * * * 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. * *************************************************************************/ //----------------------------------------------------------------------------- // gString.C // // Generic string class implementation. //----------------------------------------------------------------------------- #include "gString.h" #include <cstdarg> namespace std {}; using namespace std; //----------------------------------------------------------------------------- vchar gString::blank_[] = { 0 }; //----------------------------------------------------------------------------- gString::~gString (void) { if(ptr_) delete [] ptr_; } int gString::compare (const vchar* st) const { if (ptr_ && st) return vcharCompare (ptr_, st); else if (ptr_) return 1; else if (st) return -1; else return 0; } const gString& gString::operator = (const vchar *st) { put_value (st); return *this; } const gString& gString::operator += (const vchar *st) { if (st) { const int olen = length (); if (olen == 0) put_value (st); else if (*st) { const int nlen = vcharLength (st); vchar* nptr = new vchar [olen + nlen + 1]; if (ptr_) vcharCopyBounded (ptr_, nptr, olen); vcharCopyBounded (st, nptr + olen, nlen); nptr[olen + nlen] = '\0'; if(ptr_) delete [] ptr_; ptr_ = nptr; } } return *this; } const gString& gString::operator += (vchar c) { if (c) { vchar cc[2]; cc[0] = c; cc[1] = '\0'; operator += (cc); } return *this; } int gString::put_value (const vchar* st, int len) { vchar* temp = NULL; if (st) { if (len <= 0) len = (*st ? vcharLength (st) : 0); temp = new vchar [len + 1]; if (len > 0) vcharCopyBounded (st, temp, len); temp[len] = '\0'; } else len = 0; if(ptr_) delete [] ptr_; ptr_ = temp; return len; } int gString::put_value_scribed (vscribe* scr, int len) { vchar* temp = NULL; if (scr) { if (len <= 0) len = vcharLengthScribed (scr); if (len) { temp = new vchar [len + 1]; vcharCopyScribedBounded (scr, temp, len); temp[len] = '\0'; } else delete scr; } else len = 0; if(ptr_) delete [] ptr_; ptr_ = temp; return len; } int gString::vsprintf (const vchar* fmt, va_list ap) { return put_value_scribed (vcharScribeFormatVarargs ((vchar*) fmt, ap)); } int gString::sprintf (const vchar* fmt, ... ) { va_list ap; va_start (ap, fmt); int len = vsprintf (fmt, ap); va_end (ap); return len; } int gString::vsprintf_scribed (vscribe* fmt, va_list ap) { return put_value_scribed (vcharScribeFormatScribedVarargs (fmt, ap)); } int gString::sprintf_scribed (vscribe* fmt, ... ) { va_list ap; va_start (ap, fmt); int len = vsprintf_scribed (fmt, ap); va_end (ap); return len; } void gString::l_trim (void) { const int len = length(); for (int i = 0; (i < len) && vcharIsWhiteSpace (ptr_[i]); ++i) {} if (i > 0) vcharCopyBounded (ptr_ + i, ptr_, len - i + 1); } void gString::r_trim (void) { for (int i = length() - 1; (i >= 0) && vcharIsWhiteSpace (ptr_[i]); --i) ptr_[i] = '\0'; } void gString::trim (void) { l_trim (); r_trim (); }
sniperkit/xmq
plugin/benthos/lib/broker/common_test.go
// Copyright (c) 2014 <NAME> // // 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. package broker import ( "errors" "time" "github.com/Jeffail/benthos/lib/types" "github.com/Jeffail/benthos/lib/util/service/log" ) //------------------------------------------------------------------------------ var logConfig = log.LoggerConfig{ LogLevel: "NONE", } //------------------------------------------------------------------------------ // MockInputType implements the input.Type interface. type MockInputType struct { MsgChan chan types.Message ResChan <-chan types.Response } // StartListening sets the channel used for reading responses. func (m *MockInputType) StartListening(resChan <-chan types.Response) error { m.ResChan = resChan return nil } // MessageChan returns the messages channel. func (m *MockInputType) MessageChan() <-chan types.Message { return m.MsgChan } // CloseAsync does nothing. func (m MockInputType) CloseAsync() { close(m.MsgChan) } // WaitForClose does nothing. func (m MockInputType) WaitForClose(t time.Duration) error { select { case _, open := <-m.MsgChan: if open { return errors.New("received unexpected message") } case <-time.After(t): return types.ErrTimeout } return nil } //------------------------------------------------------------------------------ // MockOutputType implements the output.Type interface. type MockOutputType struct { ResChan chan types.Response MsgChan <-chan types.Message } // StartReceiving sets the read channel. This implementation is NOT thread safe. func (m *MockOutputType) StartReceiving(msgs <-chan types.Message) error { m.MsgChan = msgs return nil } // ResponseChan returns the errors channel. func (m *MockOutputType) ResponseChan() <-chan types.Response { return m.ResChan } // CloseAsync does nothing. func (m MockOutputType) CloseAsync() { close(m.ResChan) } // WaitForClose does nothing. func (m MockOutputType) WaitForClose(t time.Duration) error { select { case _, open := <-m.ResChan: if open { return errors.New("received unexpected message") } case <-time.After(t): return types.ErrTimeout } return nil } //------------------------------------------------------------------------------
XrosFade/ElonaFoobar
src/elona/random.cpp
#include "random.hpp" namespace elona { namespace detail { std::mt19937 engine{std::random_device{}()}; } // namespace detail } // namespace elona
selfrefactor/commit-message
packages/helpers-fn/src/exported/monitor.js
const { delay, toDecimal, piped, split, last, head, map, trim } = require('rambdax') const { ms } = require('string-fn') const { exec } = require('./exec') const { parseMonitorData } = require('./utils/parse-monitor-data') var osu = require('node-os-utils') async function getProcessUsage(){ const cpuUsage = await osu.cpu.usage() return cpuUsage } async function getMemoryUsage(){ const [freeMemoryData] = await exec({ cwd: __dirname, command: 'free', onLog: () => {} }) const freeMemory = piped( freeMemoryData, split('Mem:'), last, split('Swap:'), head, split(' '), map(trim), last, Number ) return toDecimal(freeMemory/1000000, 1) } class Monitor{ constructor(seconds = 5){ this.highestMemoryUsage = Infinity this.highestProcessUsage = 0 this.cycles = [] this.stopFlag = false this.initialState = {} this.tick = ms(`${seconds} seconds`) } async setInitialState(){ const [memoryUsage, processUsage] = await Promise.all([ getMemoryUsage(), getProcessUsage() ]) this.initialState = {memoryUsage, processUsage} } async applyStart(){ await delay(1000) while(!this.stopFlag){ await Promise.all([ this.onEveryTick(), delay(this.tick) ]) } } async start(){ await this.setInitialState() this.applyStart() } async onEveryTick(){ const [memoryUsage, processUsage] = await Promise.all([ getMemoryUsage(), getProcessUsage() ]) this.cycles.push({memoryUsage, processUsage}) if(memoryUsage < this.highestMemoryUsage){ this.highestMemoryUsage = memoryUsage } if(processUsage > this.highestProcessUsage){ this.highestProcessUsage = processUsage } } async stopMonitor(){ this.stopFlag = true await delay(this.tick) return { initialState: this.initialState, highestProcessUsage: this.highestProcessUsage, highestMemoryUsage: this.highestMemoryUsage, cycles: this.cycles } } async stop(){ const monitorData = await this.stopMonitor() return parseMonitorData(monitorData) } } exports.Monitor = Monitor exports.monitor = new Monitor() exports.getMemoryUsage = getMemoryUsage exports.getProcessUsage = getProcessUsage
ChampionCynthia/g-string_2013
sp/src/game/shared/gstring/cgstring_interaction.h
#ifndef CGSTRING_INTERACTION_H #define CGSTRING_INTERACTION_H #include "cbase.h" #include "gstring_player_shared_forward.h" class CGstringInteraction : public CBaseEntity { DECLARE_CLASS( CGstringInteraction, CBaseEntity ); DECLARE_NETWORKCLASS(); #ifdef GAME_DLL DECLARE_DATADESC(); #endif public: CGstringInteraction(); ~CGstringInteraction(); #ifdef GAME_DLL virtual void Precache(); virtual void Spawn(); virtual void Activate(); virtual int ObjectCaps( void ){ return BaseClass::ObjectCaps() & ~FCAP_ACROSS_TRANSITION; }; virtual int UpdateTransmitState(); void InputStartInteraction( inputdata_t &inputdata ); void OnObjectEvent( int iEventIndex ); void OnBodyEvent( int iEventIndex ); void OnBodyAnimationFinished(); #else //virtual void OnDataChanged( DataUpdateType_t type ); #endif private: #ifdef GAME_DLL string_t m_strFinalPositionName; string_t m_strInteractiveObjectName; string_t m_strPlayerSequenceName; string_t m_strObjectSequenceName; CHandle< CBaseEntity > m_hFinalPosition; CHandle< CGstringPlayer > m_hPlayer; bool m_bInteractionActive; COutputEvent m_PlayerEvents[ 5 ]; COutputEvent m_ObjectEvents[ 5 ]; COutputEvent m_InteractionStartEvent; COutputEvent m_InteractionEndEvent; #endif CNetworkHandle( CBaseAnimating, m_hInteractiveObject ); //CNetworkVar( bool, m_bCascadedShadowMappingEnabled ); }; #endif
rubyberlin/cfp-app
db/schema.rb
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20180111175100) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "comments", id: :serial, force: :cascade do |t| t.integer "proposal_id" t.integer "user_id" t.integer "parent_id" t.text "body" t.string "type" t.datetime "created_at" t.datetime "updated_at" t.index ["proposal_id"], name: "index_comments_on_proposal_id" t.index ["user_id"], name: "index_comments_on_user_id" end create_table "events", id: :serial, force: :cascade do |t| t.string "name" t.string "slug" t.string "url" t.string "contact_email" t.string "state", default: "draft" t.boolean "archived", default: false t.datetime "opens_at" t.datetime "closes_at" t.datetime "start_date" t.datetime "end_date" t.text "info" t.text "guidelines" t.text "settings" t.text "proposal_tags" t.text "review_tags" t.text "custom_fields" t.text "speaker_notification_emails", default: "---\n:accept: ''\n:reject: ''\n:waitlist: ''\n" t.datetime "created_at" t.datetime "updated_at" t.index ["slug"], name: "index_events_on_slug" end create_table "invitations", id: :serial, force: :cascade do |t| t.integer "proposal_id" t.integer "user_id" t.string "email" t.string "state", default: "pending" t.string "slug" t.datetime "created_at" t.datetime "updated_at" t.index ["proposal_id", "email"], name: "index_invitations_on_proposal_id_and_email", unique: true t.index ["proposal_id"], name: "index_invitations_on_proposal_id" t.index ["slug"], name: "index_invitations_on_slug", unique: true t.index ["user_id"], name: "index_invitations_on_user_id" end create_table "notifications", id: :serial, force: :cascade do |t| t.integer "user_id" t.string "message" t.string "target_path" t.datetime "read_at" t.datetime "created_at" t.datetime "updated_at" t.index ["user_id"], name: "index_notifications_on_user_id" end create_table "program_sessions", id: :serial, force: :cascade do |t| t.integer "event_id" t.integer "proposal_id" t.text "title" t.text "abstract" t.integer "track_id" t.integer "session_format_id" t.text "state", default: "draft" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.text "info" t.index ["event_id"], name: "index_program_sessions_on_event_id" t.index ["proposal_id"], name: "index_program_sessions_on_proposal_id" t.index ["session_format_id"], name: "index_program_sessions_on_session_format_id" t.index ["track_id"], name: "index_program_sessions_on_track_id" end create_table "proposals", id: :serial, force: :cascade do |t| t.integer "event_id" t.string "state", default: "submitted" t.string "uuid" t.string "title" t.integer "session_format_id" t.integer "track_id" t.text "abstract" t.text "details" t.text "pitch" t.text "last_change" t.text "confirmation_notes" t.text "proposal_data" t.datetime "updated_by_speaker_at" t.datetime "confirmed_at" t.datetime "created_at" t.datetime "updated_at" t.index ["event_id"], name: "index_proposals_on_event_id" t.index ["session_format_id"], name: "index_proposals_on_session_format_id" t.index ["track_id"], name: "index_proposals_on_track_id" t.index ["uuid"], name: "index_proposals_on_uuid", unique: true end create_table "ratings", id: :serial, force: :cascade do |t| t.integer "proposal_id" t.integer "user_id" t.integer "score" t.datetime "created_at" t.datetime "updated_at" t.index ["proposal_id"], name: "index_ratings_on_proposal_id" t.index ["user_id"], name: "index_ratings_on_user_id" end create_table "rooms", id: :serial, force: :cascade do |t| t.integer "event_id" t.string "name" t.string "room_number" t.string "level" t.string "address" t.integer "capacity" t.integer "grid_position" t.datetime "created_at" t.datetime "updated_at" t.index ["event_id"], name: "index_rooms_on_event_id" end create_table "session_formats", id: :serial, force: :cascade do |t| t.integer "event_id" t.string "name" t.string "description" t.integer "duration" t.boolean "public", default: true t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["event_id"], name: "index_session_formats_on_event_id" end create_table "speakers", id: :serial, force: :cascade do |t| t.integer "user_id" t.integer "event_id" t.integer "proposal_id" t.integer "program_session_id" t.string "speaker_name" t.string "speaker_email" t.text "bio" t.text "info" t.datetime "created_at" t.datetime "updated_at" t.index ["event_id"], name: "index_speakers_on_event_id" t.index ["program_session_id"], name: "index_speakers_on_program_session_id" t.index ["proposal_id"], name: "index_speakers_on_proposal_id" t.index ["user_id"], name: "index_speakers_on_user_id" end create_table "taggings", id: :serial, force: :cascade do |t| t.integer "proposal_id" t.string "tag" t.boolean "internal", default: false t.datetime "created_at" t.datetime "updated_at" t.index ["proposal_id"], name: "index_taggings_on_proposal_id" end create_table "teammates", id: :serial, force: :cascade do |t| t.integer "event_id" t.integer "user_id" t.string "role" t.string "email" t.string "state" t.string "token" t.datetime "invited_at" t.datetime "accepted_at" t.datetime "declined_at" t.datetime "created_at" t.datetime "updated_at" t.string "notification_preference", default: "all" t.string "mention_name" t.index ["event_id"], name: "index_teammates_on_event_id" t.index ["user_id"], name: "index_teammates_on_user_id" end create_table "time_slots", id: :serial, force: :cascade do |t| t.integer "program_session_id" t.integer "room_id" t.integer "event_id" t.integer "conference_day" t.time "start_time" t.time "end_time" t.text "title" t.text "description" t.text "presenter" t.datetime "created_at" t.datetime "updated_at" t.integer "track_id" t.index ["conference_day"], name: "index_time_slots_on_conference_day" t.index ["event_id"], name: "index_time_slots_on_event_id" t.index ["program_session_id"], name: "index_time_slots_on_program_session_id" t.index ["room_id"], name: "index_time_slots_on_room_id" t.index ["track_id"], name: "index_time_slots_on_track_id" end create_table "tracks", id: :serial, force: :cascade do |t| t.integer "event_id" t.string "name" t.string "description", limit: 250 t.text "guidelines" t.datetime "created_at" t.datetime "updated_at" t.index ["event_id"], name: "index_tracks_on_event_id" end create_table "users", id: :serial, force: :cascade do |t| t.string "name" t.string "email", default: "", null: false t.text "bio" t.boolean "admin", default: false t.string "provider" t.string "uid" t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.inet "current_sign_in_ip" t.datetime "last_sign_in_at" t.inet "last_sign_in_ip" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "unconfirmed_email" t.datetime "remember_created_at" t.datetime "created_at" t.datetime "updated_at" t.index ["confirmation_token"], name: "index_users_on_confirmation_token" t.index ["email"], name: "index_users_on_email" t.index ["reset_password_token"], name: "index_users_on_reset_password_token" t.index ["uid"], name: "index_users_on_uid" end add_foreign_key "session_formats", "events" end
lianwentao/huachengshequhuishenghuo
Model/zhangdanlishijilu/fukuanjilumodel.h
<filename>Model/zhangdanlishijilu/fukuanjilumodel.h // // fukuanjilumodel.h // HuiShengHuo2.0 // // Created by 晋中华晟 on 2018/3/23. // Copyright © 2018年 晋中华晟. All rights reserved. // #import <Foundation/Foundation.h> @interface fukuanjilumodel : NSObject @property (nonatomic,copy)NSString *time; @property (nonatomic,copy)NSString *price; @property (nonatomic,copy)NSString *biahao; @property (nonatomic,copy)NSString *name; @property (nonatomic,copy)NSString *house; @end
xidameng/micropython_amebaD
MicroPython_RTL8722/ports/rtl8722/amebad_vendor/sdk/component/common/drivers/ir/protocol/ir_led.c
<gh_stars>1-10 /** ********************************************************************************************************* * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ********************************************************************************************************** * @file ir_led.c * @brief This file provides driver of nec protocol encoding. * @details * @author elliot_chen * @date 2016-12-08 * @version v1.0 ********************************************************************************************************* */ /*============================================================================* * Header Files *============================================================================*/ #include "ir_led.h" /** @addtogroup IO_DEMO_APP IO_DEMO APP * @brief * @{ */ /** @defgroup IR_NEC_PROTOCOL IR NEC PROTOCOL * @brief Ir nec protocol implementation demo code * @{ */ /*============================================================================* * Macros *============================================================================*/ #define ABS_TIME(a,b) ((a>b) ? (a-b):(b-a)) /*============================================================================* * Constants *============================================================================*/ /*! * @ brief:LED structure. * @ note: Store parameters of led waveform. * @ Carrier frequency = 10MHz * @ duty factor = 1 * @ LSB is sent first ! */ const LED_ProtocolTypeDef LED_PROTOCOL = { 10000, /* Carrier freqency KHz*/ {PULSE_HIGH | 300, PULSE_LOW | 800}, /* log0Buf unit: ns*/ {PULSE_HIGH | 800, PULSE_LOW | 250}, /* log1Buf */ PULSE_LOW | 300000, /* stopBuf */ 30 /* tolerance percentage is 10% */ }; /*============================================================================* * Functions *============================================================================*/ /** * @brief unit convert. * @param time: time of waveform (ns). * @param carrier_cycle: cycle of carrier. * @retval vaule of data whose unit is cycle of carrier. */ static IR_DataType ConvertToCarrierCycle(uint32_t time, uint32_t freq) { return ((time & PULSE_HIGH) | ((time & IR_DATA_MSK) * freq / 1000000)); } /** * @brief check specify bit value of data. * @param a: data which want to check. * @param bit_pos: position of bit which want to check * @retval */ static uint8_t CheckBitStatus(uint32_t a, uint32_t bit_pos) { return ((a >> bit_pos) & 0x1); } /** * @brief Encode data to packet. * @param IR_DataStruct: pointer to struct which store NEC code. * @param IR_Protocol: pointer to specify IR protocol structure. * @retval None */ static IR_RETURN_Type LED_EncodePacket(IR_DataTypeDef *IR_DataStruct, LED_ProtocolTypeDef *IR_Protocol, int flag) { uint8_t codeWidth = 0; uint16_t index = 0; uint16_t bitPos = 0; uint16_t bufLen = 0; IR_DataType Log1[MAX_LOG_WAVFORM_SIZE]; IR_DataType Log0[MAX_LOG_WAVFORM_SIZE]; /* Error handle */ //if (IR_DataStruct->carrierFreq != IR_Protocol->carrierFreq) // { // return IR_FREQENCY_ERROR; // } /* Encoding logical 1 and logical 0 */ for (index = 0; index < MAX_LOG_WAVFORM_SIZE; index++) { Log1[index] = ConvertToCarrierCycle(IR_Protocol->log1Buf[index] , IR_DataStruct->carrierFreq); Log0[index] = ConvertToCarrierCycle(IR_Protocol->log0Buf[index], IR_DataStruct->carrierFreq); } /* Encoding command code */ for (index = 0; index < IR_DataStruct->codeLen; index++) { /* Decide coding width */ codeWidth = DATA_CODE_WIDTH; /* Encoding handle */ for (bitPos = 0; bitPos < codeWidth; bitPos++) { if (CheckBitStatus(IR_DataStruct->code[index], bitPos) == 0x01) { /* Logical 1 data */ IR_DataStruct->irBuf[bufLen] = Log1[0]; IR_DataStruct->irBuf[bufLen + 1] = Log1[1]; } else { /* Logical 0 data */ IR_DataStruct->irBuf[bufLen] = Log0[0]; IR_DataStruct->irBuf[bufLen + 1] = Log0[1]; } bufLen += MAX_LOG_WAVFORM_SIZE; } } /* Encode stop code */ if (IR_Protocol->stopBuf != 0 && flag == 1) { IR_DataStruct->irBuf[bufLen] = ConvertToCarrierCycle(IR_Protocol->stopBuf, IR_DataStruct->carrierFreq); bufLen++; } IR_DataStruct->bufLen = bufLen; return IR_SUCCEED; } /** * @brief Encode data of LED waveform. * @param data: user code. * @param IR_DataStruct: pointer to struct which store LED waveform. * @retval None */ IR_RETURN_Type IR_LEDEncode(uint32_t freqency, uint8_t *data, IR_DataTypeDef * IR_DataStruct, int flag) { IR_DataStruct->carrierFreq = freqency/1000; IR_DataStruct->codeLen = 3; IR_DataStruct->code[0] = data[0]; IR_DataStruct->code[1] = data[1]; IR_DataStruct->code[2] = data[2]; return LED_EncodePacket(IR_DataStruct, (LED_ProtocolTypeDef *)(&LED_PROTOCOL), flag); } /** @} */ /* End of group IR_LED */ /** @} */ /* End of group GPIO_OUTPUT_DEMO */ /******************* (C) COPYRIGHT 2016 Realtek Semiconductor Corporation *****END OF FILE****/
lwhiteley/angular-fullstack-custom
app/scripts/features/core/_app_core.js
<gh_stars>1-10 'use strict'; angular.module('app.core', ['lib.deps']);
FloaterTS/teme-fmi
pp/Lab8/p6.c
#include <stdio.h> #include <stdlib.h> int find_max(const int* v, int n) { int max = v[0]; for (int i = 1; i < n; ++i) { if (max < v[i]) { max = v[i]; } } return max; } int main() { FILE* f = fopen("p6.in", "r"); int n; fscanf(f, "%d", &n); int* v = (int*)malloc(sizeof(int) * n); for (int i = 0; i < n; ++i) { fscanf(f, "%d", v + i); } fclose(f); int max = find_max(v, n); int* pozitii = malloc(sizeof(int) * 0); int k = 0; for (int i = 0; i < n; ++i) { if (v[i] == max) { pozitii = realloc(pozitii, k + 1); pozitii[k] = i; ++k; } } free(v); printf("Pozitiile maximului sunt: \n"); for (int i = 0; i < k; ++i) { printf("%d ", pozitii[i]); } printf("\n"); free(pozitii); }
ideacrew/aca_entities
lib/aca_entities/enrollees/enrollee.rb
<reponame>ideacrew/aca_entities # frozen_string_literal: true module AcaEntities module Enrollees # entity for enrollee class Enrollee < Dry::Struct attribute :enrollee_demographics, AcaEntities::Enrollees::EnrolleeDemographics.meta(omittable: false) attribute :first_name, Types::String.meta(omittable: false) attribute :middle_name, Types::String.optional.meta(omittable: true) attribute :last_name, Types::String.meta(omittable: false) attribute :name_suffix, Types::String.optional.meta(omittable: true) attribute :hbx_member_id, Types::String.meta(omittable: false) attribute :premium_amount, Types::Float.meta(omittable: false) attribute :coverage_start, Types::Date.meta(omittable: false) attribute :coverage_end, Types::Date.optional.meta(omittable: true) attribute :coverage_status, Types::String.optional.meta(omittable: true) attribute :relationship_status_code, Types::String.meta(omittable: false) attribute :issuer_assigned_member_id, Types::String.optional.meta(omittable: true) attribute :issuer_assigned_policy_id, Types::String.optional.meta(omittable: true) attribute :is_subscriber, Types::Bool.meta(omittable: false) attribute :is_responsible_party, Types::Bool.meta(omittable: false) attribute :addresses, Types::Array .of(AcaEntities::Locations::Address) .optional .meta(omittable: true) attribute :emails, Types::Array .of(AcaEntities::Contacts::EmailContact) .optional .meta(omittable: true) attribute :phones, Types::Array .of(AcaEntities::Contacts::PhoneContact) .optional .meta(omittable: true) attribute :segments, Types::Array .of(AcaEntities::Enrollees::Segment) .optional .meta(omittable: true) def residential_address return if addresses.blank? addresses.detect do |address| address.kind == 'home' end end def mailing_address return if addresses.blank? addresses.detect do |address| address.kind == 'mailing' end end def home_phone return if phones.blank? phones.detect do |phone| phone.kind == 'home' end end end end end
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
python-packages/mne-python-0.10/mne/defaults.py
<filename>python-packages/mne-python-0.10/mne/defaults.py # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD (3-clause) from copy import deepcopy DEFAULTS = dict( color=dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m', emg='k', ref_meg='steelblue', misc='k', stim='k', resp='k', chpi='k', exci='k', ias='k', syst='k', seeg='k'), config_opts=dict(), units=dict(eeg='uV', grad='fT/cm', mag='fT', eog='uV', misc='AU', seeg='uV'), scalings=dict(mag=1e15, grad=1e13, eeg=1e6, eog=1e6, misc=1.0, seeg=1e4), scalings_plot_raw=dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6, ecg=5e-4, emg=1e-3, ref_meg=1e-12, misc=1e-3, stim=1, resp=1, chpi=1e-4, exci=1, ias=1, syst=1, seeg=1e-5), scalings_cov_rank=dict(mag=1e12, grad=1e11, eeg=1e5), ylim=dict(mag=(-600., 600.), grad=(-200., 200.), eeg=(-200., 200.), misc=(-5., 5.), seeg=(-200., 200.)), titles=dict(eeg='EEG', grad='Gradiometers', mag='Magnetometers', misc='misc', seeg='sEEG'), mask_params=dict(marker='o', markerfacecolor='w', markeredgecolor='k', linewidth=0, markeredgewidth=1, markersize=4), ) def _handle_default(k, v=None): """Helper to avoid dicts as default keyword arguments Use this function instead to resolve default dict values. Example usage:: scalings = _handle_default('scalings', scalings) """ this_mapping = deepcopy(DEFAULTS[k]) if v is not None: if isinstance(v, dict): this_mapping.update(v) else: for key in this_mapping.keys(): this_mapping[key] = v return this_mapping
oxelson/gempak
gempak/source/programs/gui/nsharp/file_browse_popup.c
<gh_stars>10-100 #include "gui.h" #include "sharp95.h" /* Convenience function to pup up file selection dialog */ void file_browse_popup (char *path, char *tmpl, Widget toplevel, void cbfunc(Widget, XtPointer, XtPointer) ) { static Widget load_filegem = NULL; XmString directory_str, pattern_str; if (!load_filegem) { load_filegem = XmCreateFileSelectionDialog (toplevel, "File Selection Window", NULL, 0); XtAddCallback (load_filegem, XmNokCallback, cbfunc, NULL); XtAddCallback (load_filegem, XmNcancelCallback, (XtCallbackProc) XtUnmanageChild, NULL); XtAddCallback (load_filegem, XmNokCallback, (XtCallbackProc) XtUnmanageChild, NULL); } XtManageChild (load_filegem); directory_str = XmStringCreateLocalized (path); pattern_str = XmStringCreateLocalized (tmpl); XtVaSetValues (load_filegem, XmNdirectory, directory_str, XmNpattern, pattern_str, NULL); XmStringFree (directory_str); XmStringFree (pattern_str); }
eti-nne/dtk
tst/dtkLog/dtkLoggerHandlersTest.h
// Version: $Id: aff4538297aa797c504eee186f0f7ccd29b7a1ba $ // // // Commentary: // // // Change Log: // // // Code: #pragma once #include <dtkTest> class dtkLoggerHandlersTestCase : public QObject { Q_OBJECT public: dtkLoggerHandlersTestCase(void); virtual ~dtkLoggerHandlersTestCase(void); private slots: void initTestCase(void); void init(void); private slots: void testLoggerHandlers(void); private slots: void cleanupTestCase(void); void cleanup(void); }; // // dtkLoggerHandlersTest.h ends here
vanadium-archive/travel
browser/src/util/define-class.js
// Copyright 2015 The Vanadium Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. var $ = require('./jquery'); /** * <p>Plays a similar role to other npm private encapsulation facilities, but * exposes private members on `this` via per-instance bindings. A class * definition can contain the following members: * <ul> * <li><code>init</code>: constructor/initializer function for an instance. It * will be called when the class is instantiated via <code>new</code>. Fields * can be initialized in this function. Private functions and events can also * be defined within this function. * <li><code>privates</code>: map of private functions or private static * constants, with access to other members via <code>this</code>. These * members are not publicly visible. This is equivalent to associating these * members explicitly within <code>init</code>. * <li><code>publics</code>: map of public functions, with access to other * members via <code>this</code>. These members are publicly visible. * <li><code>constants</code>: list of names of instance constants initialized * in <code>init</code> to be exposed. * <li><code>statics</code>: map of public static constants, accessible from * the private context, the public context, and on the constructor function. * <li><code>events</code>: list of event names, some of which can actually be * a singleton map with the event name and a string of flags, or a map of * event names to flags. Flags are those to * <a href="https://api.jquery.com/jQuery.Callbacks/">jQuery Callbacks</a>, * plus the "private" flag, which hides the event from the public interface * entirely, and the "public" flag, which exposes the event trigger to the * public interface. * </ul> * * <p>Furthermore, all functions and events are thus bound statically to the * appropriate instance, and so can be passed as callbacks without ad-hoc * proxying/binding. * * <p>Care should be taken not to be tempted to declare instance constants * within <code>private</code>, as any instantiations done on the initial * values is done at class definition time rather than class instantiation * time. (As such, using that mechanism to declare private static constants does * work.) */ module.exports = defineClass; function defineClass(def) { var constructor = function() { var ifc = this; var pthis = $.extend({ ifc: ifc //expose reflexive public interface for private use }, //extend in inverse precedence def.statics); if (def.publics) { polyBind(pthis, pthis, def.publics, false); } if (def.privates) { polyBind(pthis, pthis, def.privates, false); } if (def.events) { if ($.isArray(def.events)) { $.each(def.events, function(i, event) { if ($.type(event) === 'string') { pthis[event] = defineEvent(ifc, event); } else { defineEventsFromObject(pthis, ifc, event); } }); } else { defineEventsFromObject(pthis, ifc, def.events); } } if (def.statics) { $.extend(ifc, def.statics); } if (def.publics) { polyBind(ifc, pthis, def.publics, true); } if (def.init) { def.init.apply(pthis, arguments); } if (def.constants) { $.each(def.constants, function(i, constant) { ifc[constant] = pthis[constant]; }); } }; if (def.statics) { $.extend(constructor, def.statics); } // The function bodies aren't actually useful but the function objects provide // useful reflective properties. constructor.ifc = def.publics; return constructor; } defineClass.innerClass = function(def) { var init = def.init; def.init = function(outer, constructorArgs) { this.outer = outer; init.apply(this, constructorArgs); }; var InnerClass = defineClass(def); return function() { return new InnerClass(this, arguments); }; }; /** * Decorates a member function with like-signatured functions to be called * before and/or after the main invocation. */ defineClass.decorate = function(context, name, before, after) { var proto = context[name]; context[name] = function() { if (before) { before.apply(context, arguments); } var ret = proto.apply(context, arguments); if (after) { after.apply(context, arguments); } return ret; }; }; /** * Late-bind proxies to maximize flexibility at negligible performance cost. */ function lateBind(context, name) { return function() { return context[name].apply(context, arguments); }; } function polyBind(proxy, context, members, lateBinding) { $.each(members, $.isArray(members)? function() { proxy[this] = lateBinding? lateBind(context, this) : this.bind(context); } : function(name, member) { proxy[name] = lateBinding? lateBind(context, name) : member.bind(context); }); return proxy; } /** * Replaces "this" returns with proxy. */ function polyReflexiveLateBind(proxy, context, members) { $.each(members, function(i, name) { proxy[name] = function() { context[name].apply(context, arguments); return proxy; }; }); return proxy; } defineClass.event = defineEvent; function defineEvent(ifc, name, flags) { var dispatcher = $.Callbacks(flags); //Use polyBind on function that fires to add the callable syntactic sugar var callableDispatcher = polyBind(function() { dispatcher.fireWith.call(dispatcher, ifc, arguments); }, dispatcher, dispatcher, false); if (!(flags && flags.indexOf('private') > -1)) { if (flags && flags.indexOf('public') > -1) { ifc[name] = callableDispatcher; } else { var publicEvent = {}; /* We'll want the context to actually be callableDispatcher even though * the interface and functionality of dispatcher suffice so that we can * late-bind to the instance exposed to private this. */ polyBind(publicEvent, callableDispatcher, ['disabled', 'fired', 'has', 'locked'], true); polyReflexiveLateBind(publicEvent, callableDispatcher, ['add', 'disable', 'empty', 'lock', 'remove']); ifc[name] = publicEvent; } } return callableDispatcher; } function defineEventsFromObject(pthis, ifc, events) { $.each(events, function(event, flags) { pthis[event] = defineEvent(ifc, event, flags); }); }
AmrMKayid/KayAlgo
leetcode/arrays/check-if-n-and-its-double-exist.py
<filename>leetcode/arrays/check-if-n-and-its-double-exist.py class Solution: def checkIfExist(self, arr: List[int]) -> bool: for i, num in enumerate(arr): for j in range(i, len(arr)): if i != j and (num == arr[j] * 2 or arr[j] == num * 2): return True return False
nguyenan/api-server
core/src/main/java/com/wut/resources/OperationParameter.java
package com.wut.resources; import com.wut.model.Model; import com.wut.model.scalar.ScalarModel; public class OperationParameter { public static final OperationParameter ID = OperationParameter.create("id", ScalarModel.create(), true); private String name; private Model type; private boolean required; private boolean isPartOfScope; private OperationParameter(String name, Model type, boolean required, boolean isPartOfScope) { super(); this.name = name; this.type = type; this.required = required; this.isPartOfScope = isPartOfScope; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Model getType() { return type; } public void setType(Model type) { this.type = type; } public boolean isRequired() { return required; } public void setRequired(boolean required) { this.required = required; } public boolean isPartOfScope() { return isPartOfScope; } public void setPartOfScope(boolean isPartOfScope) { this.isPartOfScope = isPartOfScope; } public static OperationParameter create(String name, Model type, boolean isPartOfScope) { return new OperationParameter(name, type, true, isPartOfScope); } public static OperationParameter create(String name, Model type) { return new OperationParameter(name, type, true, false); } public static OperationParameter string(String name) { return create(name, ScalarModel.create()); } public OperationParameter optional() { setRequired(false); return this; } public static OperationParameter id(String name) { return create(name, ScalarModel.create()); // fix one day } }
rasael/jwrap
src/test/java/net/bervini/rasael/jwrap/api/BigDecimalWrapTest.java
<filename>src/test/java/net/bervini/rasael/jwrap/api/BigDecimalWrapTest.java /* * Copyright 2022-2022 <NAME> * * 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 net.bervini.rasael.jwrap.api; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import static net.bervini.rasael.jwrap.api.JWrap.$; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class BigDecimalWrapTest { public static final BigDecimal NULL_BIG_DECIMAL = null; public static final BigDecimal MINUS_FOUR = new BigDecimal(-4); public static final BigDecimal MINUS_THREE = new BigDecimal(-3); public static final BigDecimal MINUS_TWO = new BigDecimal(-2); public static final BigDecimal MINUS_ONE = new BigDecimal(-1); public static final BigDecimal PLUS_FOUR = new BigDecimal(4); public static final BigDecimal PLUS_THREE = new BigDecimal(3); public static final BigDecimal PLUS_TWO = new BigDecimal(2); public static final BigDecimal PLUS_ONE = new BigDecimal(1); public static final BigDecimal FOURTY_TWO = new BigDecimal(42); @Test void isPositive() { assertThat($(BigDecimal.ONE).isPositive()).isTrue(); assertThat($(BigDecimal.TEN).isPositive()).isTrue(); assertThat($(MINUS_ONE).isPositive()).isFalse(); assertThat($(BigDecimal.ZERO).isPositive()).isFalse(); assertThat($(NULL_BIG_DECIMAL).isPositive()).isFalse(); } @Test void isZero() { assertThat($(BigDecimal.ZERO).isZero()).isTrue(); assertThat($(BigDecimal.ONE).isZero()).isFalse(); assertThat($(BigDecimal.TEN).isZero()).isFalse(); assertThat($(MINUS_ONE).isZero()).isFalse(); assertThat($(NULL_BIG_DECIMAL).isZero()).isFalse(); } @Test void isOne() { assertThat($(BigDecimal.ONE).isOne()).isTrue(); assertThat($(BigDecimal.ZERO).isOne()).isFalse(); assertThat($(BigDecimal.TEN).isOne()).isFalse(); assertThat($(MINUS_ONE).isOne()).isFalse(); assertThat($(NULL_BIG_DECIMAL).isOne()).isFalse(); } @Test void isNegative() { assertThat($(MINUS_ONE).isNegative()).isTrue(); assertThat($(BigDecimal.ONE).isNegative()).isFalse(); assertThat($(BigDecimal.TEN).isNegative()).isFalse(); assertThat($(BigDecimal.ZERO).isNegative()).isFalse(); assertThat($(NULL_BIG_DECIMAL).isNegative()).isFalse(); } @Test void isEven() { assertThat($(MINUS_THREE).isEven()).isFalse(); assertThat($(MINUS_ONE).isEven()).isFalse(); assertThat($(BigDecimal.ONE).isEven()).isFalse(); assertThat($(PLUS_THREE).isEven()).isFalse(); assertThat($(MINUS_FOUR).isEven()).isTrue(); assertThat($(MINUS_TWO).isEven()).isTrue(); assertThat($(BigDecimal.ZERO).isEven()).isTrue(); assertThat($(PLUS_TWO).isEven()).isTrue(); assertThat($(PLUS_FOUR).isEven()).isTrue(); } @Test void isOdd() { assertThat($(MINUS_THREE).isOdd()).isTrue(); assertThat($(MINUS_ONE).isOdd()).isTrue(); assertThat($(BigDecimal.ONE).isOdd()).isTrue(); assertThat($(PLUS_THREE).isOdd()).isTrue(); assertThat($(MINUS_FOUR).isOdd()).isFalse(); assertThat($(MINUS_TWO).isOdd()).isFalse(); assertThat($(BigDecimal.ZERO).isOdd()).isFalse(); assertThat($(PLUS_TWO).isOdd()).isFalse(); assertThat($(PLUS_FOUR).isOdd()).isFalse(); } @Test void testReplaceNullWithZero() { assertThatThrownBy(() -> { int val = $(NULL_BIG_DECIMAL).intValue(); }).isInstanceOf(NullPointerException.class); assertThat($(NULL_BIG_DECIMAL).orZero().intValue()).isNotNull().isEqualTo(0); } @Test void conversions() { assertThat($(FOURTY_TWO).asDouble().get()).isEqualTo(42D); assertThat($(FOURTY_TWO).doubleValue()).isEqualTo(42D); assertThat($(FOURTY_TWO).asLong().get()).isEqualTo(42L); assertThat($(FOURTY_TWO).longValue()).isEqualTo(42L); assertThat($(FOURTY_TWO).asFloat().get()).isEqualTo(42f); assertThat($(FOURTY_TWO).floatValue()).isEqualTo(42f); assertThat($(FOURTY_TWO).asInt().get()).isEqualTo(42); assertThat($(FOURTY_TWO).intValue()).isEqualTo(42); assertThat($(FOURTY_TWO).asBigDecimal().isEqualTo(FOURTY_TWO)).isTrue(); } }
abimaelrsergio/Vendas_3_0
src/br/com/exemplo/vendas/apresentacao/service/ReservaService.java
<filename>src/br/com/exemplo/vendas/apresentacao/service/ReservaService.java package br.com.exemplo.vendas.apresentacao.service; import java.io.Serializable; import java.util.Date; import br.com.exemplo.vendas.apresentacao.delegate.ReservaBusinessDelegate; import br.com.exemplo.vendas.negocio.model.vo.ReservaVO; import br.com.exemplo.vendas.util.dto.ServiceDTO; import br.com.exemplo.vendas.util.exception.LayerException; public class ReservaService implements Serializable{ private static final long serialVersionUID = 1L; public Boolean inserirReserva(ReservaVO vo) throws LayerException { ServiceDTO requestDTO = new ServiceDTO(); ServiceDTO responseDTO = new ServiceDTO(); requestDTO.set("reservaVO", vo); responseDTO = ReservaBusinessDelegate.getInstance().inserirReserva(requestDTO); Boolean sucesso = (Boolean) responseDTO.get("resposta"); return sucesso; } public ServiceDTO listarReservas() throws LayerException { ServiceDTO responseDTO = new ServiceDTO(); responseDTO = ReservaBusinessDelegate.getInstance().selecionarTodosReserva(); return responseDTO; } public Boolean alterarReserva(ReservaVO vo) throws LayerException { ServiceDTO requestDTO = new ServiceDTO(); ServiceDTO responseDTO = new ServiceDTO(); requestDTO.set("reservaVO", vo); responseDTO = ReservaBusinessDelegate.getInstance().alterarReserva(requestDTO); Boolean sucesso = (Boolean) responseDTO.get("resposta"); return sucesso; } public Boolean excluirReserva(ReservaVO vo) throws LayerException { ServiceDTO requestDTO = new ServiceDTO(); ServiceDTO responseDTO = new ServiceDTO(); requestDTO.set("reservaVO", vo); responseDTO = ReservaBusinessDelegate.getInstance().excluirReserva(requestDTO); Boolean sucesso = (Boolean) responseDTO.get("resposta"); return sucesso; } }
mohammedhemaid/Random-Name-Picker
app/src/main/java/com/randomappsinc/studentpicker/grouping/GroupMakingActivity.java
package com.randomappsinc.studentpicker.grouping; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import com.joanzapata.iconify.IconDrawable; import com.joanzapata.iconify.fonts.IoniconsIcons; import com.randomappsinc.studentpicker.R; import com.randomappsinc.studentpicker.common.Constants; import com.randomappsinc.studentpicker.database.DataSource; import com.randomappsinc.studentpicker.models.ListInfo; import com.randomappsinc.studentpicker.models.NameDO; import com.randomappsinc.studentpicker.utils.NameUtils; import com.randomappsinc.studentpicker.utils.UIUtils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class GroupMakingActivity extends AppCompatActivity { @BindView(R.id.no_groups) TextView noGroups; @BindView(R.id.groups_list) RecyclerView groupsList; private GroupMakingSettings settings; private GroupMakingSettingsDialog settingsDialog; private int listId; private DataSource dataSource; private ListInfo listInfo; private GroupMakingAdapter groupsMakingListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.group_maker); ButterKnife.bind(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar() .setHomeAsUpIndicator(new IconDrawable(this, IoniconsIcons.ion_android_close) .colorRes(R.color.white) .actionBarSize()); listId = getIntent().getIntExtra(Constants.LIST_ID_KEY, 0); dataSource = new DataSource(this); setTitle(dataSource.getListName(listId)); listInfo = dataSource.getListInfo(listId); groupsMakingListAdapter = new GroupMakingAdapter(); groupsList.setAdapter(groupsMakingListAdapter); settings = dataSource.getGroupMakingSettings(listId, listInfo.getNumInstances()); settingsDialog = new GroupMakingSettingsDialog(this, settings); } @OnClick(R.id.make_groups) void makeGroups() { if (listInfo.getNumNames() == 0) { UIUtils.showLongToast(R.string.group_no_names_error_message, this); return; } List<List<NameDO>> listOfNamesPerGroup = NameUtils.createGroups( listInfo, settings.getNumOfNamesPerGroup(), settings.getNumOfGroups()); groupsMakingListAdapter.setData(listOfNamesPerGroup); noGroups.setVisibility(View.GONE); groupsList.setVisibility(View.VISIBLE); } @Override protected void onPause() { super.onPause(); dataSource.saveGroupMakingSettingState(listId, settings); } @Override public void finish() { super.finish(); overridePendingTransition(0, R.anim.slide_out_from_top); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.groups_menu, menu); UIUtils.loadMenuIcon(menu, R.id.settings, IoniconsIcons.ion_android_settings, this); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.settings: settingsDialog.show(); return true; } return super.onOptionsItemSelected(item); } }
gilvansfilho/quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/InjectionPointBean.java
package io.quarkus.arc.impl; import java.lang.reflect.Type; import java.util.Set; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.InjectionPoint; public class InjectionPointBean extends BuiltInBean<InjectionPoint> { private static final Set<Type> IP_TYPES = Set.of(InjectionPoint.class, Object.class); @Override public Set<Type> getTypes() { return IP_TYPES; } @Override public InjectionPoint get(CreationalContext<InjectionPoint> creationalContext) { return InjectionPointProvider.get(); } @Override public Class<?> getBeanClass() { return CurrentInjectionPointProvider.InjectionPointImpl.class; } }
etayluz/PersonalFinanceAssistant
app/utils/navHelpers.js
import R from 'ramda'; export const getParam = param => R.path(['state', 'params', param]); export const getParamOr = (param, def) => R.pathOr(def, ['state', 'params', param]); export const setParam = R.curry((param, nav, value) => nav.setParams({ [param]: value }));
MarioRuiz/slack-smart-bot
lib/slack/smart-bot/comm/get_users.rb
<filename>lib/slack/smart-bot/comm/get_users.rb<gh_stars>10-100 class SlackSmartBot def get_users() begin users = [] cursor = nil if config.simulate users = client.web_client.users_list else begin resp = client.web_client.users_list(limit: 1000, cursor: cursor) if resp.key?(:members) and resp[:members].is_a(Array) and resp[:members].size > 0 users << resp[:members] end cursor = resp.get_values(:next_cursor).values[-1] end until cursor.empty? users.flatten! end return users rescue Exception => stack @logger.warn stack end end end
rythm-net/SoftUni
Programming Basics with Java/T03 - Conditional Statements/src/exercise/Shopping.java
package exercise; import java.util.Scanner; public class Shopping { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double budget = Double.parseDouble(scanner.nextLine()); int videCards = Integer.parseInt(scanner.nextLine()); int processors = Integer.parseInt(scanner.nextLine()); int ram = Integer.parseInt(scanner.nextLine()); double videoCardsPrice = videCards * 250; double processorsPrice = videoCardsPrice * 0.35 * processors; double ramPrice = videoCardsPrice * 0.10 * ram; double totalSum = videoCardsPrice + processorsPrice + ramPrice; if(videCards > processors) { totalSum = totalSum - (totalSum * 0.15); } if(totalSum <= budget) { System.out.printf("You have %.2f leva left!", budget - totalSum); } else { System.out.printf("Not enough money! You need %.2f leva more!", totalSum - budget); } } }
hanbioinformatica/owe2a
week4RegularExpressions/RegularExpressionsIntroductie/extractingNames.py
<gh_stars>0 import re scientific_name = "<NAME>" m = re.search("([A-Z][a-z]*) ([a-z]+)", scientific_name) if m: genus = m.group(1) species = m.group(2) print("genus is " + genus + ", species is " + species)
cping/LGame
Java/Loon-Lite(PureJava)/Loon-Lite-Core/src/loon/event/TouchMake.java
<reponame>cping/LGame<gh_stars>100-1000 /** * Copyright 2008 - 2015 The Loon Game Engine 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. * * @project loon * @author cping * @email:<EMAIL> * @version 0.5 */ package loon.event; public class TouchMake { public static class Event extends loon.event.Event.XY { public static enum Kind { START(true, false), MOVE(false, false), END(false, true), CANCEL( false, true); public final boolean isStart, isEnd; Kind(boolean isStart, boolean isEnd) { this.isStart = isStart; this.isEnd = isEnd; } }; public final Kind kind; public final int id; public final float pressure; public final float size; public Event(int flags, double time, float x, float y, Kind kind, int id) { this(flags, time, x, y, kind, id, -1, -1); } public Event(int flags, double time, float x, float y, Kind kind, int id, float pressure, float size) { super(flags, time, x, y); this.kind = kind; this.id = id; this.pressure = pressure; this.size = size; } @Override protected String name() { return "Touch"; } @Override protected void addFields(StringBuilder builder) { super.addFields(builder); builder.append(", kind=").append(kind).append(", id=").append(id) .append(", pressure=").append(pressure).append(", size=") .append(size); } } }
sumonbis/compiler
src/test/boa/test/datagen/js/TestElelementGet.java
<gh_stars>10-100 package boa.test.datagen.js; import java.io.IOException; import org.junit.Test; public class TestElelementGet extends JavaScriptBaseTest { @Test public void elementGetTest1() throws IOException{ nodeTest( load("test/datagen/javascript/ElementGetNode.boa"), load("test/datagen/javascript/ElementGetNode.js")); } }
linminglu/Fgame
game/gm/command/handler/bodyshield_jinjiadan.go
package handler import ( "fgame/fgame/common/lang" bodyshieldservice "fgame/fgame/game/bodyshield/bodyshield" bodyshieldlogic "fgame/fgame/game/bodyshield/logic" "fgame/fgame/game/bodyshield/pbutil" playerbodyshield "fgame/fgame/game/bodyshield/player" "fgame/fgame/game/gm/command" gmcommandtypes "fgame/fgame/game/gm/command/types" "fgame/fgame/game/player" playerlogic "fgame/fgame/game/player/logic" "fgame/fgame/game/player/types" "fgame/fgame/game/scene/scene" "strconv" log "github.com/Sirupsen/logrus" ) func init() { command.Register(gmcommandtypes.CommandTypeJinJiaDan, command.CommandHandlerFunc(handleBodyShieldJinJiaDan)) } func handleBodyShieldJinJiaDan(p scene.Player, c *command.Command) (err error) { pl := p.(player.Player) if len(c.Args) <= 0 { playerlogic.SendSystemMessage(pl, lang.GMFormatWrong) return } jinJiaDanStr := c.Args[0] jinJiaDanLevel, err := strconv.ParseInt(jinJiaDanStr, 10, 64) if err != nil { log.WithFields( log.Fields{ "id": pl.GetId(), "jinJiaDanLevel": jinJiaDanLevel, "error": err, }).Warn("gm:处理设置护体盾食金甲丹等级,jinJiaDanLevel不是数字") playerlogic.SendSystemMessage(pl, lang.GMFormatWrong) err = nil return } tempTemplateObject := bodyshieldservice.GetBodyShieldService().GetBodyShieldJinJia(int32(jinJiaDanLevel)) //修改等级 if tempTemplateObject == nil { log.WithFields( log.Fields{ "id": pl.GetId(), "jinJiaDanLevel": jinJiaDanLevel, "error": err, }).Warn("gm:处理设置护体盾食金甲丹等级,jinJiaDanLevel模板不存在") playerlogic.SendSystemMessage(pl, lang.GMFormatWrong) return } manager := pl.GetPlayerDataManager(types.PlayerBShieldDataManagerType).(*playerbodyshield.PlayerBodyShieldDataManager) manager.GmSetBodyShieldJinJiaDanLevel(int32(jinJiaDanLevel)) //同步属性 bodyshieldlogic.BodyShieldPropertyChanged(pl) scBodyShieldJJDan := pbutil.BuildSCBodyShieldJJDan(int32(jinJiaDanLevel), 0) pl.SendMsg(scBodyShieldJJDan) return }
bianapis/sd-ecm-dcm-v2.0
src/main/java/org/bian/dto/CRECMDCMFulfillmentArrangementRetrieveInputModel.java
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceAnalysis; import org.bian.dto.CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceReportRecord; import javax.validation.Valid; /** * CRECMDCMFulfillmentArrangementRetrieveInputModel */ public class CRECMDCMFulfillmentArrangementRetrieveInputModel { private Object eCMDCMFulfillmentArrangementRetrieveActionTaskRecord = null; private String eCMDCMFulfillmentArrangementRetrieveActionRequest = null; private CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceReportRecord eCMDCMFulfillmentArrangementInstanceReportRecord = null; private CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceAnalysis eCMDCMFulfillmentArrangementInstanceAnalysis = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return eCMDCMFulfillmentArrangementRetrieveActionTaskRecord **/ public Object getECMDCMFulfillmentArrangementRetrieveActionTaskRecord() { return eCMDCMFulfillmentArrangementRetrieveActionTaskRecord; } public void setECMDCMFulfillmentArrangementRetrieveActionTaskRecord(Object eCMDCMFulfillmentArrangementRetrieveActionTaskRecord) { this.eCMDCMFulfillmentArrangementRetrieveActionTaskRecord = eCMDCMFulfillmentArrangementRetrieveActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports) * @return eCMDCMFulfillmentArrangementRetrieveActionRequest **/ public String getECMDCMFulfillmentArrangementRetrieveActionRequest() { return eCMDCMFulfillmentArrangementRetrieveActionRequest; } public void setECMDCMFulfillmentArrangementRetrieveActionRequest(String eCMDCMFulfillmentArrangementRetrieveActionRequest) { this.eCMDCMFulfillmentArrangementRetrieveActionRequest = eCMDCMFulfillmentArrangementRetrieveActionRequest; } /** * Get eCMDCMFulfillmentArrangementInstanceReportRecord * @return eCMDCMFulfillmentArrangementInstanceReportRecord **/ public CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceReportRecord getECMDCMFulfillmentArrangementInstanceReportRecord() { return eCMDCMFulfillmentArrangementInstanceReportRecord; } public void setECMDCMFulfillmentArrangementInstanceReportRecord(CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceReportRecord eCMDCMFulfillmentArrangementInstanceReportRecord) { this.eCMDCMFulfillmentArrangementInstanceReportRecord = eCMDCMFulfillmentArrangementInstanceReportRecord; } /** * Get eCMDCMFulfillmentArrangementInstanceAnalysis * @return eCMDCMFulfillmentArrangementInstanceAnalysis **/ public CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceAnalysis getECMDCMFulfillmentArrangementInstanceAnalysis() { return eCMDCMFulfillmentArrangementInstanceAnalysis; } public void setECMDCMFulfillmentArrangementInstanceAnalysis(CRECMDCMFulfillmentArrangementRetrieveInputModelECMDCMFulfillmentArrangementInstanceAnalysis eCMDCMFulfillmentArrangementInstanceAnalysis) { this.eCMDCMFulfillmentArrangementInstanceAnalysis = eCMDCMFulfillmentArrangementInstanceAnalysis; } }