repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
agarun/algorithms
games/mastermind/mastermind.rb
<gh_stars>0 class Code PEGS = { RED: "R", GREEN: "G", BLUE: "B", YELLOW: "Y", ORANGE: "O", PURPLE: "P" } attr_reader :pegs def self.parse(code) code = code.upcase.chars if valid_code?(code) Code.new(code) else raise "The code had invalid characters. Choose from #{PEGS.values.join}" end end def self.valid_code?(code) code.all? { |peg| PEGS.values.include?(peg) } && code.size == 4 end def self.random self.new( Array.new(4) { PEGS.values.sample } ) end def initialize(pegs) @pegs = pegs end def exact_matches(code) (0...code.pegs.size).reduce(0) do |exact, idx| self.pegs[idx] == code.pegs[idx] ? exact + 1 : exact end end def near_matches(code) code1 = self.pegs.dup code2 = code.pegs.dup total = 0 (0...code1.size).each do |idx| if code1.include?(code2[idx]) total += 1 code1[code1.index(code2[idx])] = '0' # mark it so it can't be matched again end end total - exact_matches(code) # near = total matches - exact matches end # allows you to use `[]` syntax directly on an instance, using `pegs` getter def [](peg_index) pegs[peg_index] end def ==(code) code.is_a?(Code) && pegs == code.pegs end end class Game TURNS = 10 attr_reader :secret_code, :turns, :guess def initialize(secret_code = Code.random) @secret_code = secret_code @turns = TURNS end def get_guess print "\n >> " Code.parse(gets.chomp) rescue puts "Valid inputs are 4 characters long and can include #{Code::PEGS.values.join(", ")}." retry end def play welcome_message play_turn until over? end_message end def play_turn @guess = get_guess @turns -= 1 display_matches(guess) end def over? # there was a guess made AND all 4 pegs match OR no turns left !guess.nil? && (guess.exact_matches(secret_code) == 4 || turns.zero?) end def display_matches(code) puts <<~MATCHES Your guess is #{code.pegs.join.upcase} and you have #{turns} turns remaining! Your code had #{code.near_matches(secret_code)} near matches and #{code.exact_matches(secret_code)} exact matches. MATCHES end private def welcome_message print <<~WELCOME Welcome to Mastermind! We'll play with red, green, blue, yellow, orange, and purple pegs, & 10 turns max. Enter a sequence of four valid colors to get started. For example, enter 'RGBY' to denote red, green, blue, & yellow pegs. Order matters! WELCOME end def end_message puts <<~GAMEOVER #{"Nice! You got it." if turns > 0} Game over! The solution was #{secret_code.pegs.join.upcase}. Game took #{(turns - 10).abs} turns. GAMEOVER end end if $PROGRAM_NAME == __FILE__ Game.new.play end
johannah/balloon-learning-environment
balloon_learning_environment/utils/sampling_test.py
# coding=utf-8 # Copyright 2022 The Balloon Learning Environment 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. """Tests for balloon_learning_environment.utils.sampling.""" from absl.testing import absltest from absl.testing import parameterized from balloon_learning_environment.env.balloon import standard_atmosphere from balloon_learning_environment.utils import sampling from balloon_learning_environment.utils import units import jax class SamplingTest(parameterized.TestCase): def setUp(self): super().setUp() # Deterministic PRNG state. Tests MUST NOT rely on a specific seed. self.prng_key = jax.random.PRNGKey(123) self.atmosphere = standard_atmosphere.Atmosphere(jax.random.PRNGKey(0)) def test_sample_location_with_seed_gives_deterministic_lat_lng(self): location1 = sampling.sample_location(self.prng_key) location2 = sampling.sample_location(self.prng_key) self.assertEqual(location1, location2) def test_sample_location_gives_valid_lat_lng(self): latlng = sampling.sample_location(self.prng_key) # We only allow locations near the equator self.assertBetween(latlng.lat().degrees, -10.0, 10.0) # We don't allow locations near the international date line self.assertBetween(latlng.lng().degrees, -175.0, 175.0) def test_sample_time_with_seed_gives_deterministic_time(self): t1 = sampling.sample_time(self.prng_key) t2 = sampling.sample_time(self.prng_key) self.assertEqual(t1, t2) def test_sample_time_gives_time_within_range(self): # Pick a 1 hour segment to give a small valid range for testing begin_range = units.datetime(year=2020, month=1, day=1, hour=1) end_range = units.datetime(year=2020, month=1, day=1, hour=2) t = sampling.sample_time( self.prng_key, begin_range=begin_range, end_range=end_range) self.assertBetween(t, begin_range, end_range) def test_sample_pressure_with_seed_gives_deterministic_pressure(self): p1 = sampling.sample_pressure(self.prng_key, self.atmosphere) p2 = sampling.sample_pressure(self.prng_key, self.atmosphere) self.assertEqual(p1, p2) def test_sample_pressure_gives_pressure_within_range(self): p = sampling.sample_pressure(self.prng_key, self.atmosphere) self.assertBetween(p, 5000, 14000) def test_sample_upwelling_infrared_is_within_range(self): ir = sampling.sample_upwelling_infrared(self.prng_key) self.assertBetween(ir, 100.0, 350.0) @parameterized.named_parameters( dict(testcase_name='logit_normal', distribution_type='logit_normal'), dict(testcase_name='inverse_lognormal', distribution_type='inverse_lognormal')) def test_sample_upwelling_infrared_is_within_range_nondefault( self, distribution_type): ir = sampling.sample_upwelling_infrared(self.prng_key, distribution_type=distribution_type) self.assertBetween(ir, 100.0, 350.0) def test_sample_upwelling_infrared_invalid_distribution_type(self): with self.assertRaises(ValueError): sampling.sample_upwelling_infrared(self.prng_key, distribution_type='invalid') if __name__ == '__main__': absltest.main()
LimHanGyeol/study
java-vendingmachine/src/test/java/Junit5Test.java
<reponame>LimHanGyeol/study<filename>java-vendingmachine/src/test/java/Junit5Test.java import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import static org.assertj.core.api.Assertions.assertThat; public class Junit5Test { @Test void defaultTest() { assertThat(true).isTrue(); } @ParameterizedTest @ValueSource(ints = {1, 2, 3, 4, 5}) void parameterizedTest(int value) { assertThat(value).isEqualTo(value); } }
uk-gov-mirror/hmcts.blob-router-service
src/main/java/uk/gov/hmcts/reform/blobrouter/data/rejectedenvelope/RejectedEnvelope.java
package uk.gov.hmcts.reform.blobrouter.data.rejectedenvelope; import uk.gov.hmcts.reform.blobrouter.data.events.ErrorCode; import java.util.UUID; public class RejectedEnvelope { public final UUID envelopeId; public final String container; public final String fileName; public final ErrorCode errorCode; public final String errorDescription; public RejectedEnvelope( UUID envelopeId, String container, String fileName, ErrorCode errorCode, String errorDescription ) { this.envelopeId = envelopeId; this.container = container; this.fileName = fileName; this.errorCode = errorCode; this.errorDescription = errorDescription; } }
c3sr/tensorflow
master_service.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: master_service.proto package tensorflow import ( context "context" fmt "fmt" proto "github.com/gogo/protobuf/proto" grpc "google.golang.org/grpc" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package func init() { proto.RegisterFile("master_service.proto", fileDescriptor_9a501bcba839fe29) } var fileDescriptor_9a501bcba839fe29 = []byte{ // 387 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x93, 0xbd, 0x4e, 0xf3, 0x30, 0x14, 0x86, 0x9b, 0xe1, 0xeb, 0x27, 0x99, 0x56, 0x95, 0x02, 0x03, 0x04, 0xc9, 0xfd, 0x61, 0x26, 0x95, 0x60, 0x65, 0x6a, 0x61, 0xa3, 0xa8, 0xa4, 0x4c, 0x5d, 0x90, 0x9b, 0x1e, 0x8a, 0x21, 0xb5, 0x83, 0xed, 0x00, 0x97, 0xc1, 0xfd, 0x70, 0x03, 0x8c, 0x1d, 0x19, 0x51, 0x7b, 0x23, 0x28, 0x4d, 0xd2, 0xd8, 0x21, 0xed, 0x7a, 0x9e, 0xd7, 0x8f, 0xf2, 0x3a, 0x3e, 0xe8, 0x60, 0x4e, 0xa4, 0x02, 0x71, 0x2f, 0x41, 0xbc, 0x52, 0x1f, 0xdc, 0x50, 0x70, 0xc5, 0xed, 0x86, 0x02, 0x26, 0xb9, 0x78, 0x08, 0xf8, 0x9b, 0x3b, 0x13, 0xa1, 0xef, 0xd4, 0x92, 0x58, 0x82, 0xcf, 0x3e, 0xab, 0xa8, 0x3e, 0x58, 0x0f, 0x46, 0xc9, 0x31, 0xfb, 0x0e, 0xd5, 0xfb, 0x02, 0x88, 0x82, 0x11, 0x48, 0x49, 0x39, 0xb3, 0x5b, 0xae, 0xa6, 0x30, 0x90, 0x07, 0x2f, 0x11, 0x48, 0xe5, 0xb4, 0x77, 0x24, 0x64, 0xc8, 0x99, 0x5c, 0x5b, 0xaf, 0xde, 0x15, 0xb0, 0x69, 0xa9, 0xd5, 0x40, 0xa5, 0xd6, 0x42, 0x22, 0xb5, 0x8e, 0x51, 0x63, 0x48, 0x84, 0xa2, 0x24, 0xf0, 0x22, 0x36, 0x02, 0x15, 0x85, 0x76, 0x47, 0x3f, 0x55, 0x80, 0x99, 0xf9, 0x64, 0x67, 0x26, 0x75, 0xf7, 0xd0, 0xff, 0x78, 0xa6, 0x20, 0xb4, 0x1d, 0x3d, 0x9f, 0x0e, 0x33, 0xd7, 0x71, 0x29, 0x4b, 0x1d, 0xb7, 0xa8, 0xd6, 0x0f, 0xb8, 0xdc, 0x5c, 0x65, 0xd3, 0xb8, 0x28, 0x8d, 0x64, 0xb6, 0xd6, 0xf6, 0x40, 0xaa, 0xbc, 0x41, 0x7b, 0xd7, 0x54, 0xaa, 0x4b, 0x88, 0x7f, 0x96, 0xb4, 0xb1, 0x7e, 0x40, 0x03, 0x99, 0xb0, 0xb9, 0x95, 0xa7, 0xbe, 0x0b, 0xf4, 0xcf, 0x03, 0x09, 0xca, 0x3e, 0x34, 0x8a, 0xc4, 0xa3, 0xcc, 0x71, 0x54, 0x42, 0xf2, 0x82, 0x03, 0xf2, 0x0c, 0x7d, 0x12, 0x04, 0x64, 0x12, 0x80, 0x59, 0x50, 0x27, 0xa5, 0x05, 0xcd, 0x40, 0x5e, 0xd0, 0x8b, 0xd8, 0xc6, 0x88, 0x0b, 0xf7, 0x5b, 0x14, 0x36, 0xb7, 0xf2, 0xfc, 0x8d, 0x78, 0x10, 0x00, 0x91, 0xf9, 0x57, 0x76, 0xcc, 0x42, 0x06, 0x2c, 0x7d, 0x23, 0x7f, 0x32, 0x89, 0xbb, 0xc7, 0xbe, 0x96, 0xd8, 0x5a, 0x2c, 0xb1, 0xf5, 0xb3, 0xc4, 0xd6, 0xc7, 0x0a, 0x57, 0x16, 0x2b, 0x5c, 0xf9, 0x5e, 0xe1, 0x0a, 0x72, 0xb8, 0x98, 0xe9, 0x86, 0x29, 0x95, 0x4a, 0x44, 0x4c, 0xd1, 0x39, 0xf4, 0xf6, 0x8d, 0x85, 0x1b, 0xc6, 0x7b, 0x28, 0x87, 0xd6, 0xb8, 0x3d, 0xa3, 0xea, 0x31, 0x9a, 0xb8, 0x3e, 0x9f, 0x77, 0x05, 0xa1, 0xa7, 0xa1, 0xe0, 0x4f, 0xe0, 0xab, 0x6e, 0x6e, 0x99, 0x54, 0xd7, 0x4b, 0x7b, 0xfe, 0x1b, 0x00, 0x00, 0xff, 0xff, 0xce, 0xd6, 0x49, 0x4d, 0xeb, 0x03, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // MasterServiceClient is the client API for MasterService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MasterServiceClient interface { // Creates a session. CreateSession(ctx context.Context, in *CreateSessionRequest, opts ...grpc.CallOption) (*CreateSessionResponse, error) // Extends a session. ExtendSession(ctx context.Context, in *ExtendSessionRequest, opts ...grpc.CallOption) (*ExtendSessionResponse, error) // Prepares future partial run calls. PartialRunSetup(ctx context.Context, in *PartialRunSetupRequest, opts ...grpc.CallOption) (*PartialRunSetupResponse, error) // Drives the graph computation. RunStep(ctx context.Context, in *RunStepRequest, opts ...grpc.CallOption) (*RunStepResponse, error) // Closes a session. CloseSession(ctx context.Context, in *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionResponse, error) // List the devices usable by the master. ListDevices(ctx context.Context, in *ListDevicesRequest, opts ...grpc.CallOption) (*ListDevicesResponse, error) // Close and abandon all existing sessions. Ongoing computations // will no longer affect fresh ones via the resources in containers listed in // the ResetRequest. See ResetRequest for more details. Reset(ctx context.Context, in *ResetRequest, opts ...grpc.CallOption) (*ResetResponse, error) // Registers a callable for execution with RunCallable. MakeCallable(ctx context.Context, in *MakeCallableRequest, opts ...grpc.CallOption) (*MakeCallableResponse, error) // Executes a callable registered with MakeCallable. RunCallable(ctx context.Context, in *RunCallableRequest, opts ...grpc.CallOption) (*RunCallableResponse, error) // Frees resources associated with a callable registered with MakeCallable. ReleaseCallable(ctx context.Context, in *ReleaseCallableRequest, opts ...grpc.CallOption) (*ReleaseCallableResponse, error) } type masterServiceClient struct { cc *grpc.ClientConn } func NewMasterServiceClient(cc *grpc.ClientConn) MasterServiceClient { return &masterServiceClient{cc} } func (c *masterServiceClient) CreateSession(ctx context.Context, in *CreateSessionRequest, opts ...grpc.CallOption) (*CreateSessionResponse, error) { out := new(CreateSessionResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/CreateSession", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) ExtendSession(ctx context.Context, in *ExtendSessionRequest, opts ...grpc.CallOption) (*ExtendSessionResponse, error) { out := new(ExtendSessionResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/ExtendSession", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) PartialRunSetup(ctx context.Context, in *PartialRunSetupRequest, opts ...grpc.CallOption) (*PartialRunSetupResponse, error) { out := new(PartialRunSetupResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/PartialRunSetup", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) RunStep(ctx context.Context, in *RunStepRequest, opts ...grpc.CallOption) (*RunStepResponse, error) { out := new(RunStepResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/RunStep", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) CloseSession(ctx context.Context, in *CloseSessionRequest, opts ...grpc.CallOption) (*CloseSessionResponse, error) { out := new(CloseSessionResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/CloseSession", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) ListDevices(ctx context.Context, in *ListDevicesRequest, opts ...grpc.CallOption) (*ListDevicesResponse, error) { out := new(ListDevicesResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/ListDevices", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) Reset(ctx context.Context, in *ResetRequest, opts ...grpc.CallOption) (*ResetResponse, error) { out := new(ResetResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/Reset", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) MakeCallable(ctx context.Context, in *MakeCallableRequest, opts ...grpc.CallOption) (*MakeCallableResponse, error) { out := new(MakeCallableResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/MakeCallable", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) RunCallable(ctx context.Context, in *RunCallableRequest, opts ...grpc.CallOption) (*RunCallableResponse, error) { out := new(RunCallableResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/RunCallable", in, out, opts...) if err != nil { return nil, err } return out, nil } func (c *masterServiceClient) ReleaseCallable(ctx context.Context, in *ReleaseCallableRequest, opts ...grpc.CallOption) (*ReleaseCallableResponse, error) { out := new(ReleaseCallableResponse) err := c.cc.Invoke(ctx, "/tensorflow.grpc.MasterService/ReleaseCallable", in, out, opts...) if err != nil { return nil, err } return out, nil } // MasterServiceServer is the server API for MasterService service. type MasterServiceServer interface { // Creates a session. CreateSession(context.Context, *CreateSessionRequest) (*CreateSessionResponse, error) // Extends a session. ExtendSession(context.Context, *ExtendSessionRequest) (*ExtendSessionResponse, error) // Prepares future partial run calls. PartialRunSetup(context.Context, *PartialRunSetupRequest) (*PartialRunSetupResponse, error) // Drives the graph computation. RunStep(context.Context, *RunStepRequest) (*RunStepResponse, error) // Closes a session. CloseSession(context.Context, *CloseSessionRequest) (*CloseSessionResponse, error) // List the devices usable by the master. ListDevices(context.Context, *ListDevicesRequest) (*ListDevicesResponse, error) // Close and abandon all existing sessions. Ongoing computations // will no longer affect fresh ones via the resources in containers listed in // the ResetRequest. See ResetRequest for more details. Reset(context.Context, *ResetRequest) (*ResetResponse, error) // Registers a callable for execution with RunCallable. MakeCallable(context.Context, *MakeCallableRequest) (*MakeCallableResponse, error) // Executes a callable registered with MakeCallable. RunCallable(context.Context, *RunCallableRequest) (*RunCallableResponse, error) // Frees resources associated with a callable registered with MakeCallable. ReleaseCallable(context.Context, *ReleaseCallableRequest) (*ReleaseCallableResponse, error) } func RegisterMasterServiceServer(s *grpc.Server, srv MasterServiceServer) { s.RegisterService(&_MasterService_serviceDesc, srv) } func _MasterService_CreateSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateSessionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).CreateSession(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/CreateSession", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).CreateSession(ctx, req.(*CreateSessionRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_ExtendSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ExtendSessionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).ExtendSession(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/ExtendSession", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).ExtendSession(ctx, req.(*ExtendSessionRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_PartialRunSetup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(PartialRunSetupRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).PartialRunSetup(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/PartialRunSetup", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).PartialRunSetup(ctx, req.(*PartialRunSetupRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_RunStep_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RunStepRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).RunStep(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/RunStep", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).RunStep(ctx, req.(*RunStepRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_CloseSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CloseSessionRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).CloseSession(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/CloseSession", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).CloseSession(ctx, req.(*CloseSessionRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_ListDevices_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListDevicesRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).ListDevices(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/ListDevices", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).ListDevices(ctx, req.(*ListDevicesRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_Reset_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ResetRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).Reset(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/Reset", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).Reset(ctx, req.(*ResetRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_MakeCallable_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(MakeCallableRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).MakeCallable(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/MakeCallable", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).MakeCallable(ctx, req.(*MakeCallableRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_RunCallable_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(RunCallableRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).RunCallable(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/RunCallable", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).RunCallable(ctx, req.(*RunCallableRequest)) } return interceptor(ctx, in, info, handler) } func _MasterService_ReleaseCallable_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ReleaseCallableRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(MasterServiceServer).ReleaseCallable(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/tensorflow.grpc.MasterService/ReleaseCallable", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(MasterServiceServer).ReleaseCallable(ctx, req.(*ReleaseCallableRequest)) } return interceptor(ctx, in, info, handler) } var _MasterService_serviceDesc = grpc.ServiceDesc{ ServiceName: "tensorflow.grpc.MasterService", HandlerType: (*MasterServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "CreateSession", Handler: _MasterService_CreateSession_Handler, }, { MethodName: "ExtendSession", Handler: _MasterService_ExtendSession_Handler, }, { MethodName: "PartialRunSetup", Handler: _MasterService_PartialRunSetup_Handler, }, { MethodName: "RunStep", Handler: _MasterService_RunStep_Handler, }, { MethodName: "CloseSession", Handler: _MasterService_CloseSession_Handler, }, { MethodName: "ListDevices", Handler: _MasterService_ListDevices_Handler, }, { MethodName: "Reset", Handler: _MasterService_Reset_Handler, }, { MethodName: "MakeCallable", Handler: _MasterService_MakeCallable_Handler, }, { MethodName: "RunCallable", Handler: _MasterService_RunCallable_Handler, }, { MethodName: "ReleaseCallable", Handler: _MasterService_ReleaseCallable_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "master_service.proto", }
yanbutan/lit-test-repo-ts
node_modules/playwright/lib/client/android.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AndroidWebView = exports.AndroidInput = exports.AndroidSocket = exports.AndroidDevice = exports.Android = void 0; var _fs = _interopRequireDefault(require("fs")); var _utils = require("../utils/utils"); var _events = require("./events"); var _browserContext = require("./browserContext"); var _channelOwner = require("./channelOwner"); var _timeoutSettings = require("../utils/timeoutSettings"); var _waiter = require("./waiter"); var _events2 = require("events"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) Microsoft 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. */ class Android extends _channelOwner.ChannelOwner { static from(android) { return android._object; } constructor(parent, type, guid, initializer) { super(parent, type, guid, initializer); this._timeoutSettings = void 0; this._timeoutSettings = new _timeoutSettings.TimeoutSettings(); } setDefaultTimeout(timeout) { this._timeoutSettings.setDefaultTimeout(timeout); this._channel.setDefaultTimeoutNoReply({ timeout }); } async devices() { return this._wrapApiCall(async channel => { const { devices } = await channel.devices(); return devices.map(d => AndroidDevice.from(d)); }); } } exports.Android = Android; class AndroidDevice extends _channelOwner.ChannelOwner { static from(androidDevice) { return androidDevice._object; } constructor(parent, type, guid, initializer) { super(parent, type, guid, initializer); this._timeoutSettings = void 0; this._webViews = new Map(); this.input = void 0; this.input = new AndroidInput(this); this._timeoutSettings = new _timeoutSettings.TimeoutSettings(parent._timeoutSettings); this._channel.on('webViewAdded', ({ webView }) => this._onWebViewAdded(webView)); this._channel.on('webViewRemoved', ({ pid }) => this._onWebViewRemoved(pid)); } _onWebViewAdded(webView) { const view = new AndroidWebView(this, webView); this._webViews.set(webView.pid, view); this.emit(_events.Events.AndroidDevice.WebView, view); } _onWebViewRemoved(pid) { const view = this._webViews.get(pid); this._webViews.delete(pid); if (view) view.emit(_events.Events.AndroidWebView.Close); } setDefaultTimeout(timeout) { this._timeoutSettings.setDefaultTimeout(timeout); this._channel.setDefaultTimeoutNoReply({ timeout }); } serial() { return this._initializer.serial; } model() { return this._initializer.model; } webViews() { return [...this._webViews.values()]; } async webView(selector, options) { const webView = [...this._webViews.values()].find(v => v.pkg() === selector.pkg); if (webView) return webView; return this.waitForEvent('webview', { ...options, predicate: view => view.pkg() === selector.pkg }); } async wait(selector, options) { await this._wrapApiCall(async channel => { await channel.wait({ selector: toSelectorChannel(selector), ...options }); }); } async fill(selector, text, options) { await this._wrapApiCall(async channel => { await channel.fill({ selector: toSelectorChannel(selector), text, ...options }); }); } async press(selector, key, options) { await this.tap(selector, options); await this.input.press(key); } async tap(selector, options) { await this._wrapApiCall(async channel => { await channel.tap({ selector: toSelectorChannel(selector), ...options }); }); } async drag(selector, dest, options) { await this._wrapApiCall(async channel => { await channel.drag({ selector: toSelectorChannel(selector), dest, ...options }); }); } async fling(selector, direction, options) { await this._wrapApiCall(async channel => { await channel.fling({ selector: toSelectorChannel(selector), direction, ...options }); }); } async longTap(selector, options) { await this._wrapApiCall(async channel => { await channel.longTap({ selector: toSelectorChannel(selector), ...options }); }); } async pinchClose(selector, percent, options) { await this._wrapApiCall(async channel => { await channel.pinchClose({ selector: toSelectorChannel(selector), percent, ...options }); }); } async pinchOpen(selector, percent, options) { await this._wrapApiCall(async channel => { await channel.pinchOpen({ selector: toSelectorChannel(selector), percent, ...options }); }); } async scroll(selector, direction, percent, options) { await this._wrapApiCall(async channel => { await channel.scroll({ selector: toSelectorChannel(selector), direction, percent, ...options }); }); } async swipe(selector, direction, percent, options) { await this._wrapApiCall(async channel => { await channel.swipe({ selector: toSelectorChannel(selector), direction, percent, ...options }); }); } async info(selector) { return await this._wrapApiCall(async channel => { return (await channel.info({ selector: toSelectorChannel(selector) })).info; }); } async screenshot(options = {}) { return await this._wrapApiCall(async channel => { const { binary } = await channel.screenshot(); const buffer = Buffer.from(binary, 'base64'); if (options.path) await _fs.default.promises.writeFile(options.path, buffer); return buffer; }); } async close() { return this._wrapApiCall(async channel => { await channel.close(); this.emit(_events.Events.AndroidDevice.Close); }); } async shell(command) { return this._wrapApiCall(async channel => { const { result } = await channel.shell({ command }); return Buffer.from(result, 'base64'); }); } async open(command) { return this._wrapApiCall(async channel => { return AndroidSocket.from((await channel.open({ command })).socket); }); } async installApk(file, options) { return this._wrapApiCall(async channel => { await channel.installApk({ file: await loadFile(file), args: options && options.args }); }); } async push(file, path, options) { return this._wrapApiCall(async channel => { await channel.push({ file: await loadFile(file), path, mode: options ? options.mode : undefined }); }); } async launchBrowser(options = {}) { return this._wrapApiCall(async channel => { const contextOptions = await (0, _browserContext.prepareBrowserContextParams)(options); const { context } = await channel.launchBrowser(contextOptions); return _browserContext.BrowserContext.from(context); }); } async waitForEvent(event, optionsOrPredicate = {}) { return this._wrapApiCall(async channel => { const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate); const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate; const waiter = _waiter.Waiter.createForEvent(this, event); waiter.rejectOnTimeout(timeout, `Timeout while waiting for event "${event}"`); if (event !== _events.Events.AndroidDevice.Close) waiter.rejectOnEvent(this, _events.Events.AndroidDevice.Close, new Error('Device closed')); const result = await waiter.waitForEvent(this, event, predicate); waiter.dispose(); return result; }); } } exports.AndroidDevice = AndroidDevice; class AndroidSocket extends _channelOwner.ChannelOwner { static from(androidDevice) { return androidDevice._object; } constructor(parent, type, guid, initializer) { super(parent, type, guid, initializer); this._channel.on('data', ({ data }) => this.emit(_events.Events.AndroidSocket.Data, Buffer.from(data, 'base64'))); this._channel.on('close', () => this.emit(_events.Events.AndroidSocket.Close)); } async write(data) { return this._wrapApiCall(async channel => { await channel.write({ data: data.toString('base64') }); }); } async close() { return this._wrapApiCall(async channel => { await channel.close(); }); } } exports.AndroidSocket = AndroidSocket; async function loadFile(file) { if ((0, _utils.isString)(file)) return _fs.default.promises.readFile(file, { encoding: 'base64' }).toString(); return file.toString('base64'); } class AndroidInput { constructor(device) { this._device = void 0; this._device = device; } async type(text) { return this._device._wrapApiCall(async channel => { await channel.inputType({ text }); }); } async press(key) { return this._device._wrapApiCall(async channel => { await channel.inputPress({ key }); }); } async tap(point) { return this._device._wrapApiCall(async channel => { await channel.inputTap({ point }); }); } async swipe(from, segments, steps) { return this._device._wrapApiCall(async channel => { await channel.inputSwipe({ segments, steps }); }); } async drag(from, to, steps) { return this._device._wrapApiCall(async channel => { await channel.inputDrag({ from, to, steps }); }); } } exports.AndroidInput = AndroidInput; function toSelectorChannel(selector) { const { checkable, checked, clazz, clickable, depth, desc, enabled, focusable, focused, hasChild, hasDescendant, longClickable, pkg, res, scrollable, selected, text } = selector; const toRegex = value => { if (value === undefined) return undefined; if (value instanceof RegExp) return value.source; return '^' + value.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d') + '$'; }; return { checkable, checked, clazz: toRegex(clazz), pkg: toRegex(pkg), desc: toRegex(desc), res: toRegex(res), text: toRegex(text), clickable, depth, enabled, focusable, focused, hasChild: hasChild ? { selector: toSelectorChannel(hasChild.selector) } : undefined, hasDescendant: hasDescendant ? { selector: toSelectorChannel(hasDescendant.selector), maxDepth: hasDescendant.maxDepth } : undefined, longClickable, scrollable, selected }; } class AndroidWebView extends _events2.EventEmitter { constructor(device, data) { super(); this._device = void 0; this._data = void 0; this._pagePromise = void 0; this._device = device; this._data = data; } pid() { return this._data.pid; } pkg() { return this._data.pkg; } async page() { if (!this._pagePromise) this._pagePromise = this._fetchPage(); return this._pagePromise; } async _fetchPage() { return this._device._wrapApiCall(async channel => { const { context } = await channel.connectToWebView({ pid: this._data.pid, sdkLanguage: 'javascript' }); return _browserContext.BrowserContext.from(context).pages()[0]; }); } } exports.AndroidWebView = AndroidWebView;
alonmm/VCSamples
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/DirectWrite vertical text sample (Windows 8)/C++/FlowSink.h
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved // // Contents: Source interface for where text is allowed to flow. // //---------------------------------------------------------------------------- #pragma once class DECLSPEC_UUID("7712E74A-C7E0-4664-B58E-854394F2ACB4") FlowLayoutSink : public ComBase<QiListSelf<FlowLayoutSink, QiList<IUnknown>>> { public: FlowLayoutSink(Microsoft::WRL::ComPtr<IDWriteFactory> dwriteFactory): m_dwriteFactory(dwriteFactory), m_textAnalyzer() { } void Reset(); void Prepare(UINT32 glyphCount); void SetGlyphRun( float x, float y, UINT32 glyphCount, const UINT16* glyphIndices, const float* glyphAdvances, const DWRITE_GLYPH_OFFSET* glyphOffsets, Microsoft::WRL::ComPtr<IDWriteFontFace> fontFace, float fontEmSize, UINT8 glyphOrientation, bool isReversed, bool isSideways ); void DrawGlyphRuns( Microsoft::WRL::ComPtr<ID2D1DeviceContext> deviceContext, Microsoft::WRL::ComPtr<IDWriteRenderingParams> renderingParams, Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> textColor ) const; protected: // This glyph run is based off DWRITE_GLYPH_RUN // and is trivially convertable to it, but stores // pointers as relative indices instead instead // of raw pointers, which makes it more useful for // storing in a vector. Additionally, it stores // the x, y coordinate. struct CustomGlyphRun { CustomGlyphRun() : fontFace(), fontEmSize(), glyphStart(), glyphCount(), glyphOrientation(), isSideways(), isReversed(), x(), y() { } CustomGlyphRun(const CustomGlyphRun& b) { memcpy(this, &b, sizeof(*this)); fontFace = SafeAcquire(b.fontFace); } CustomGlyphRun& operator =(const CustomGlyphRun& b) { if (this != &b) { // Define assignment operator in terms of destructor and // placement new constructor, paying heed to self assignment. this->~CustomGlyphRun(); new(this) CustomGlyphRun(b); } return *this; } IDWriteFontFace* fontFace; float fontEmSize; float x; float y; UINT32 glyphStart; UINT32 glyphCount; UINT8 glyphOrientation; bool isSideways; bool isReversed; void Convert( const UINT16* glyphIndices, // [glyphCount] const float* glyphAdvances, // [glyphCount] const DWRITE_GLYPH_OFFSET* glyphOffsets, // [glyphCount] OUT DWRITE_GLYPH_RUN* glyphRun ) const; }; std::vector<CustomGlyphRun> m_glyphRuns; std::vector<UINT16> m_glyphIndices; std::vector<float> m_glyphAdvances; std::vector<DWRITE_GLYPH_OFFSET> m_glyphOffsets; Microsoft::WRL::ComPtr<IDWriteFactory> m_dwriteFactory; mutable Microsoft::WRL::ComPtr<IDWriteTextAnalyzer1> m_textAnalyzer; };
ciprian-radu/rent-a-car
application/entities/src/test/java/ro/ciprianradu/rentacar/entity/EntityTest.java
<gh_stars>1-10 package ro.ciprianradu.rentacar.entity; import java.util.Objects; import java.util.UUID; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Unit tests for {@link Entity} */ class EntityTest { @Test void test_Entity_nullEntity_throwsException() { Assertions.assertThrows(IllegalArgumentException.class, () -> new Entity((Entity) null)); } @Test void test_Entity_nullID_throwsException() { Assertions.assertThrows(IllegalArgumentException.class, () -> new Entity((String) null)); } @Test void test_Entity_ID_instantiates() { Assertions.assertNotNull(new Entity(UUID.randomUUID().toString())); } @Test void test_equals_null_returnsFalse() { Entity entity = new Entity(); Assertions.assertFalse(entity.equals(null)); } @Test void test_equals_otherClass_returnsFalse() { Entity entity = new Entity(); Assertions.assertFalse(entity.equals(Integer.valueOf(0))); } @Test void test_equals_isReflexive() { Entity entity = new Entity(); Assertions.assertTrue(entity.equals(entity)); } @Test void test_equals_isSymmetric() { Entity entity1 = new Entity(); Entity entity2 = new Entity(entity1); Assertions.assertTrue(entity1.equals(entity2)); Assertions.assertTrue(entity2.equals(entity1)); } @Test void test_equals_isTransitive() { Entity entity1 = new Entity(); Entity entity2 = new Entity(entity1); Entity entity3 = new Entity(entity2); Assertions.assertTrue(entity1.equals(entity2)); Assertions.assertTrue(entity2.equals(entity3)); Assertions.assertTrue(entity1.equals(entity3)); } @Test void test_hashCode_returnsIdHash() { Entity entity = new Entity(); Assertions.assertEquals(Objects.hash(entity.getId()), entity.hashCode()); } @Test void test_toString_returnsId() { Entity entity = new Entity(); Assertions.assertEquals("Entity{id=" + entity.getId().toString() + "}", entity.toString()); } }
LeviOfficalDriftingRealmsDev/DriftingRealmsWorldEditor
Include/ToolBar.hpp
<gh_stars>0 #pragma once #include "Precomp.hpp" #include "ElementBrowser.hpp" #include "TabHeader.hpp" #include "TriggerTool.hpp" #include "GameElementsTool.hpp" #include "NavigationMeshTool.hpp" class ToolBar : public clan::GUIComponent{ public: ToolBar(GUIComponent *owner, Rect f, clan::Callback_1<bool, const clan::InputEvent &> *call_back) : GUIComponent (owner){ this->set_geometry(f); func_render().set(this,&ToolBar::on_render); // header = new ::TabHeader(this,Rect(f.left+8,get_geometry().top,f.right-2,get_geometry().top+35)); rect = f; header = new ::TabHeader(this,Rect(6,0,rect.get_width()-5,35)); func_input().set(this,&ToolBar::on_input); parent = owner; this->call_back = call_back; set_focus_policy(focus_refuse); } ~ToolBar(){ } void add_game_elements_tool(Vec2f *vec){ header->AddTab("game elements", new GameElementsTool(this,Rectf(6,42,rect.get_width()-4,rect.get_height()-46),vec)); } void add_trigger_builder(Vec2f *vec){ // header->AddTab("triggers builder", new TriggerToolBrowser(this,Rectf(rect.left + 6,rect.top + 42,rect.right-4,rect.bottom-46),vec,call_back)); header->AddTab("triggers builder", new TriggerToolBrowser(this,Rectf(6,42,rect.get_width()-4,rect.get_height()-46),vec,call_back)); } void add_component_builder(Vec2f *vec){ // header->AddTab("component builder", new ElementBrowser(this,Rectf(rect.left + 6,rect.top + 42,rect.right-4,rect.bottom-46),vec,call_back)); header->AddTab("component builder", new ElementBrowser(this,Rectf(6,42,rect.get_width()-4,rect.get_height()-46),vec,call_back)); } void add_navigation_mesh_tool(Vec2f *vec){ header->AddTab("navigation", new NavigationMeshTool(this,Rectf(6,42,rect.get_width()-4,rect.get_height()-46),vec)); } void on_render(Canvas &canvas, const Rect &clip_rect) { const int width = rect.get_width(); const int height = rect.get_height(); canvas.fill_rect(Rect(0,0,width,height),Colorf(20,20,20,255)); canvas.fill_rect(Rect(0,0,1,height),GLOBAL_VARS::green); canvas.fill_rect(Rect(4,0,5,height),GLOBAL_VARS::green); canvas.fill_rect(Rect(5,37,width,38),GLOBAL_VARS::green); canvas.fill_rect(Rect(5,40,width,41),GLOBAL_VARS::green); header->request_repaint(); //! the header may need to tell the tool bar to expand if it needs more room if(header->expand_by != 0){ rect = Rectf(rect.left - header->expand_by,rect.top,rect.right,rect.bottom); set_geometry(rect); // header->resize(Rect(rect.left+6,10,rect.get_width()-7,10+35)); header->resize(Rect(6,0,rect.get_width()-5,35),rect.get_height()-46); header->expand_by = 0; } } void resize(Rect f){ rect = f; set_geometry(f); } bool on_input(const clan::InputEvent &e){ static bool is_dragging = false; if(IsPressed(e) && e.id == InputCode::mouse_left && e.mouse_pos.x < 8){ is_dragging = true; capture_mouse(true); }else if(e.type == InputEvent::Type::released && e.id == InputCode::mouse_left){ is_dragging = false; capture_mouse(false); }else{ // call_back->invoke(e); } if(is_dragging){ rect = Rectf(rect.left + e.mouse_pos.x - 4,rect.top,rect.right,rect.bottom); set_geometry(rect); // header->resize(Rect(rect.left+6,10,rect.get_width()-7,10+35)); header->resize(Rect(6,0,rect.get_width()-5,35),rect.get_height()-46); } return true; } ::TabHeader *header; Rect rect; clan::GUIComponent *parent; Callback_1<bool, const clan::InputEvent &> *call_back; };
imdairies/imd-farm-solutions
src/main/java/com/imd/util/ConfigurationManager.java
package com.imd.util; import java.util.HashMap; import org.joda.time.LocalTime; public class ConfigurationManager { private static HashMap<String, Object> orgConfigurations = null; private static HashMap<String, Object> globalConfigurations = null; private static HashMap<String, Object> sessionConfigurations = null; public Object getOrganizationConfigurationValue(String key) { if (orgConfigurations == null) { orgConfigurations = new HashMap<String, Object> (); loadOrganizationConfigurationsIfNeeded(); } return orgConfigurations.get(key); } public Object getGlobalConfigurationValue(String key) { if (globalConfigurations == null) { globalConfigurations = new HashMap<String, Object> (); loadGlobalConfigurationsIfNeeded(); } return globalConfigurations.get(key); } public Object getSessionConfigurationValue(String key) { if (sessionConfigurations == null) { sessionConfigurations = new HashMap<String, Object> (); loadUserSessionConfigurationsIfNeeded(); } return sessionConfigurations.get(key); } public Object setOrganizationConfigurationValue(String key, Object value) { if (orgConfigurations == null) { orgConfigurations = new HashMap<String, Object> (); loadOrganizationConfigurationsIfNeeded(); } return orgConfigurations.put(key,value); } private void loadUserSessionConfigurationsIfNeeded() { if (sessionConfigurations.isEmpty()) { sessionConfigurations.put(Util.ConfigKeys.ORG_ID, "IMD"); sessionConfigurations.put(Util.ConfigKeys.USER_ID, "KASHIF"); sessionConfigurations.put(Util.ConfigKeys.USER_NAME, "<NAME>"); sessionConfigurations.put(Util.ConfigKeys.LANG_CD, "URD"); } } public void reLoadUserSessionConfigurations() { if (sessionConfigurations == null) sessionConfigurations = new HashMap<String, Object> (); else sessionConfigurations.clear(); loadUserSessionConfigurationsIfNeeded(); } private void loadGlobalConfigurationsIfNeeded() { if (globalConfigurations.isEmpty()) { globalConfigurations.put(Util.ConfigKeys.UTC_TIMEZONE, Util.UTC_TIMEZONE); globalConfigurations.put(Util.ConfigKeys.LANG_CD, Util.LanguageCode.ENG); globalConfigurations.put(Util.ConfigKeys.ORG_ID, "IMD"); } } public void reLoadGlobalConfigurations() { if (globalConfigurations == null) globalConfigurations = new HashMap<String, Object> (); else globalConfigurations.clear(); loadGlobalConfigurationsIfNeeded(); } private void loadOrganizationConfigurationsIfNeeded() { if (orgConfigurations.isEmpty()) { orgConfigurations.put(Util.ConfigKeys.ORG_ID, "IMD"); orgConfigurations.put(Util.ConfigKeys.LANG_CD, "URD"); orgConfigurations.put(Util.ConfigKeys.FARM_TIMEZONE, Util.FARM_TIMEZONE); orgConfigurations.put(Util.ConfigKeys.VOL_UNIT, Util.VOL_UNIT); orgConfigurations.put(Util.ConfigKeys.MILKING_FREQUENCY, (short)3); orgConfigurations.put(Util.ConfigKeys.FIRST_MILKING_TIME, new LocalTime(4,0,0)); orgConfigurations.put(Util.ConfigKeys.FIRST_MILKING_TIME, new LocalTime(12,0,0)); orgConfigurations.put(Util.ConfigKeys.FIRST_MILKING_TIME, new LocalTime(20,0,0)); orgConfigurations.put(Util.ConfigKeys.TOKEN_EXPIRY_MINUTES, (int)30/*expires after 30 minutes of inactivity*/); } } public void reLoadOrganizationConfigurations() { if (orgConfigurations == null) orgConfigurations = new HashMap<String, Object> (); else orgConfigurations.clear(); loadOrganizationConfigurationsIfNeeded(); } public void setSessionConfigurationValue(String key, String value) { sessionConfigurations.put(key, value); } }
RuedigerLudwig/advent2018
src/main/scala/savinien/aoc18/day22/CaveService.scala
<reponame>RuedigerLudwig/advent2018 package savinien.aoc18 package day22 import common.* import zio.* case class CaveService(input: AdventInput.Service) extends SingleDay.Service: override def part1 = for data <- input.getData map <- CaveService.fromString(data) yield AdventNumResult(map.riskFactor) override def part2 = for data <- input.getData map <- CaveService.fromString(data) yield AdventNumResult(map.bestPath) object CaveService: val fromString = ZioParse.parseAllToZio(Cave.parser)
FAD95/NEXT.JS-Course
node_modules/@iconify/icons-mdi/src/bottle-soda.js
let data = { "body": "<path d=\"M15 11v9a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-9a2 2 0 0 1 .6-1.42C11.1 7.89 11 4 11 4h-1V2h4v2h-1s-.1 3.89 1.4 5.58A2 2 0 0 1 15 11z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; export default data;
PacktPublishing/Mastering-IPython-4
Chapter 7/code9.py
<reponame>PacktPublishing/Mastering-IPython-4<filename>Chapter 7/code9.py from nvd3 import scatterChart %load_ext rpy2.ipython from rpy2.robjects import pandas2ri pandas2ri.activate() from rpy2.robjects import r import pandas df_cars = pandas2ri.ri2py(r['mtcars']) wt = df_cars['wt'] mpg = df_cars['mpg'] kwargs = {'shape': 'circle', 'size': '1'} chart = scatterChart(name='Weight vs MPG', height=400, width=800, y_axis_scale_min='0', show_legend='False') chart.add_serie(name="Cars", x=wt, y=mpg, **kwargs) output_file = open('nvd3-2.html', 'w') chart.buildhtml() output_file.write(chart.htmlcontent) output_file.close()
rsn8887/mame2003-plus-libretro
src/machine/8254pit.c
#include "driver.h" /*#include <stdio.h>*/ #include "machine/8254pit.h" void pit8254_init (pit8254_interface *intf) { } void pit8254_w (int which, int offset, int data) { switch (offset) { case 0: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d write %d to timer1\n",which, data); break; case 1: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d write %d to timer2\n",which, data); break; case 2: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d write %d to timer3\n",which, data); break; case 3: { int sc=(data>>6)&3; int rw=(data>>4)&3; int mode=(data>>1)&0x07; int bcd=data&0x01; log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d write %02x to control : ", which, data); log_cb(RETRO_LOG_DEBUG, LOGPRE "*** SC=%d RW=%d MODE=%d BCD=%d\n",sc, rw, mode, bcd); } break; } } int pit8254_r (int which, int offset) { switch (offset) { case 0: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d read from timer1\n", which); break; case 1: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d read from timer2\n", which); break; case 2: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d read from timer3\n", which); break; case 3: log_cb(RETRO_LOG_DEBUG, LOGPRE "PIT8254#%d read from control\n", which); break; } return 0; } /* Port handler wrappers. */ WRITE_HANDLER( pit8254_0_w ) { pit8254_w(0, offset, data); } WRITE_HANDLER( pit8254_0_counter1_w ) { pit8254_w(0, 0, data); } WRITE_HANDLER( pit8254_0_counter2_w ) { pit8254_w(0, 1, data); } WRITE_HANDLER( pit8254_0_counter3_w ) { pit8254_w(0, 2, data); } WRITE_HANDLER( pit8254_0_control_w ) { pit8254_w(0, 3, data); } WRITE_HANDLER( pit8254_1_w ) { pit8254_w(1, 0, data); } WRITE_HANDLER( pit8254_1_counter1_w ) { pit8254_w(1, 0, data); } WRITE_HANDLER( pit8254_1_counter2_w ) { pit8254_w(1, 1, data); } WRITE_HANDLER( pit8254_1_counter3_w ) { pit8254_w(1, 2, data); } WRITE_HANDLER( pit8254_1_control_w ) { pit8254_w(1, 3, data); } READ_HANDLER( pit8254_0_r ) { return pit8254_r(0, offset); } READ_HANDLER( pit8254_0_counter1_r ) { return pit8254_r(0, 0); } READ_HANDLER( pit8254_0_counter2_r ) { return pit8254_r(0, 1); } READ_HANDLER( pit8254_0_counter3_r ) { return pit8254_r(0, 2); } READ_HANDLER( pit8254_0_control_r ) { return pit8254_r(0, 3); } READ_HANDLER( pit8254_1_r ) { return pit8254_r(1, offset); } READ_HANDLER( pit8254_1_counter1_r ) { return pit8254_r(1, 0); } READ_HANDLER( pit8254_1_counter2_r ) { return pit8254_r(1, 1); } READ_HANDLER( pit8254_1_counter3_r ) { return pit8254_r(1, 2); } READ_HANDLER( pit8254_1_control_r ) { return pit8254_r(1, 3); }
ph-jo/runelite
runescape-client/src/main/java/class324.java
<reponame>ph-jo/runelite import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("le") public class class324 { @ObfuscatedName("o") @ObfuscatedSignature( signature = "Lfe;" ) @Export("timer") static Timer timer; }
benoit-dubreuil/template-repo-cpp-full-ecosystem
conf/script/src/build_system/cmd/setup/_priv/cli/colorize.py
__all__ = ['colorize_header_label', 'colorize_label', 'colorize_path'] import colorama from ext.utils.path import * def colorize_header_label(header: str) -> str: return colorama.Fore.LIGHTCYAN_EX + header + colorama.Style.RESET_ALL def colorize_label(label: str) -> str: return colorama.Fore.CYAN + label + colorama.Style.RESET_ALL def colorize_path(path_info: TUnion_PathLike) -> str: return colorama.Fore.LIGHTBLACK_EX + str(path_info) + colorama.Style.RESET_ALL
kmamal/node-sdl
tests/keyboard.test.js
<gh_stars>10-100 const sdl = require('..') const window = sdl.video.createWindow() window.on('keyDown', ({ scancode, key }) => { console.log({ scancode, key, _scancode: key && sdl.keyboard.getScancode(key), _key: sdl.keyboard.getKey(scancode), }) })
LiorKogan/RedisGraph
src/execution_plan/ops/op.c
/* * Copyright 2018-2020 Redis Labs Ltd. and Contributors * * This file is available under the Redis Labs Source Available License Agreement */ #include "op.h" #include "RG.h" #include "../../util/rmalloc.h" #include "../../util/simple_timer.h" /* Forward declarations */ Record ExecutionPlan_BorrowRecord(struct ExecutionPlan *plan); rax *ExecutionPlan_GetMappings(const struct ExecutionPlan *plan); void ExecutionPlan_ReturnRecord(struct ExecutionPlan *plan, Record r); void OpBase_Init(OpBase *op, OPType type, const char *name, fpInit init, fpConsume consume, fpReset reset, fpToString toString, fpClone clone, fpFree free, bool writer, const struct ExecutionPlan *plan) { op->type = type; op->name = name; op->plan = plan; op->stats = NULL; op->parent = NULL; op->childCount = 0; op->children = NULL; op->parent = NULL; op->stats = NULL; op->op_initialized = false; op->modifies = NULL; op->writer = writer; // Function pointers. op->init = init; op->consume = consume; op->reset = reset; op->toString = toString; op->clone = clone; op->free = free; op->profile = NULL; } inline Record OpBase_Consume(OpBase *op) { return op->consume(op); } int OpBase_Modifies(OpBase *op, const char *alias) { if(!op->modifies) op->modifies = array_new(const char *, 1); array_append(op->modifies, alias); /* Make sure alias has an entry associated with it * within the record mapping. */ rax *mapping = ExecutionPlan_GetMappings(op->plan); void *id = raxFind(mapping, (unsigned char *)alias, strlen(alias)); if(id == raxNotFound) { id = (void *)raxSize(mapping); raxInsert(mapping, (unsigned char *)alias, strlen(alias), id, NULL); } return (intptr_t)id; } int OpBase_AliasModifier(OpBase *op, const char *modifier, const char *alias) { rax *mapping = ExecutionPlan_GetMappings(op->plan); void *id = raxFind(mapping, (unsigned char *)modifier, strlen(modifier)); ASSERT(id != raxNotFound); // Make sure to not introduce the same modifier twice. if(raxInsert(mapping, (unsigned char *)alias, strlen(alias), id, NULL)) { array_append(op->modifies, alias); } return (intptr_t)id; } bool OpBase_ChildrenAware(OpBase *op, const char *alias, int *idx) { for (int i = 0; i < op->childCount; i++) { OpBase *child = op->children[i]; if(op->plan == child->plan && child->modifies != NULL) { uint count = array_len(child->modifies); for (uint i = 0; i < count; i++) { if(strcmp(alias, child->modifies[i]) == 0) { if(idx) { rax *mapping = ExecutionPlan_GetMappings(op->plan); void *rec_idx = raxFind(mapping, (unsigned char *)alias, strlen(alias)); *idx = (intptr_t)rec_idx; } return true; } } } if(OpBase_ChildrenAware(child, alias, idx)) return true; } return false; } bool OpBase_Aware(OpBase *op, const char *alias, int *idx) { rax *mapping = ExecutionPlan_GetMappings(op->plan); void *rec_idx = raxFind(mapping, (unsigned char *)alias, strlen(alias)); if(idx) *idx = (intptr_t)rec_idx; return (rec_idx != raxNotFound); } void OpBase_PropagateFree(OpBase *op) { if(op->free) op->free(op); for(int i = 0; i < op->childCount; i++) OpBase_PropagateFree(op->children[i]); } void OpBase_PropagateReset(OpBase *op) { if(op->reset) { OpResult res = op->reset(op); ASSERT(res == OP_OK); } for(int i = 0; i < op->childCount; i++) OpBase_PropagateReset(op->children[i]); } static void _OpBase_StatsToString(const OpBase *op, sds *buff) { *buff = sdscatprintf(*buff, " | Records produced: %d, Execution time: %f ms", op->stats->profileRecordCount, op->stats->profileExecTime); } void OpBase_ToString(const OpBase *op, sds *buff) { int bytes_written = 0; if(op->toString) op->toString(op, buff); else *buff = sdscatprintf(*buff, "%s", op->name); if(op->stats) _OpBase_StatsToString(op, buff); } Record OpBase_Profile(OpBase *op) { double tic [2]; // Start timer. simple_tic(tic); Record r = op->profile(op); // Stop timer and accumulate. op->stats->profileExecTime += simple_toc(tic); if(r) op->stats->profileRecordCount++; return r; } bool OpBase_IsWriter(OpBase *op) { return op->writer; } void OpBase_UpdateConsume(OpBase *op, fpConsume consume) { ASSERT(op != NULL); /* If Operation is profiled, update profiled function. * otherwise update consume function. */ if(op->profile != NULL) op->profile = consume; else op->consume = consume; } inline Record OpBase_CreateRecord(const OpBase *op) { return ExecutionPlan_BorrowRecord((struct ExecutionPlan *)op->plan); } Record OpBase_CloneRecord(Record r) { Record clone = ExecutionPlan_BorrowRecord((struct ExecutionPlan *)r->owner); Record_Clone(r, clone); return clone; } inline OPType OpBase_Type(const OpBase *op) { ASSERT(op != NULL); return op->type; } inline void OpBase_DeleteRecord(Record r) { ExecutionPlan_ReturnRecord(r->owner, r); } OpBase *OpBase_Clone(const struct ExecutionPlan *plan, const OpBase *op) { if(op->clone) return op->clone(plan, op); return NULL; } void OpBase_Free(OpBase *op) { // Free internal operation if(op->free) op->free(op); if(op->children) rm_free(op->children); if(op->modifies) array_free(op->modifies); if(op->stats) rm_free(op->stats); rm_free(op); }
zhangxinngang/pmd
pmd-core/src/main/java/net/sourceforge/pmd/cache/ChecksumAware.java
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.cache; import net.sourceforge.pmd.annotation.InternalApi; /** * Interface defining an object that has a checksum The checksum is a * fingerprint of the object's configuration, and *MUST* change if anything * changed on the object. It differs from a {@code hashCode()} in that a * {@code hashCode()} may not take all fields into account, but a checksum must * do so. * * @deprecated This is internal API, will be hidden with 7.0.0 */ @Deprecated @InternalApi public interface ChecksumAware { /** * Retrieves the current instance checksum * * @return The current checksum */ long getChecksum(); }
d-kahara/store_manager_api
app/tests/v1/base_test.py
"""This class will contain test configurations""" import json import unittest from run import app from ...data import Data from instance.config import app_config reg_endpoint = "api/v1/auth/register" #Login endpoint login_endpoint = "api/v1/auth/login" class BaseTestCase(unittest.TestCase): """Base Tests""" user_data = { "email": "<EMAIL>", "password": "<PASSWORD>", "admin": False } admin_user_data_reg = { "email": "<EMAIL>", "password": "<PASSWORD>", "admin": True } admin_user_data = { "email": "<EMAIL>", "password": "<PASSWORD>", "admin": True } def create_app(self): app.config.from_object(app_config["testing"]) app.config.from_pyfile('config.py') return app def setUp(self): app.testing = True self.app = app.test_client() def tearDown(self): Data.products.clear() Data.sales.clear() Data.users.clear() def create_test_user(self): user_response = self.app.post(reg_endpoint, data=json.dumps(self.user_data), content_type='application/json') self.assertEqual(user_response.status_code, 201) # registered user login login_response = self.app.post(login_endpoint, data=json.dumps(self.user_data), content_type='application/json') data = json.loads(login_response.data.decode()) self.assertTrue(data['Authorization']) self.assertEqual(login_response.status_code, 200) return data def create_admin_test_user(self): user_response = self.app.post(reg_endpoint, data=json.dumps(self.admin_user_data_reg), content_type='application/json') self.assertEqual(user_response.status_code, 201) # registered user login login_response = self.app.post(login_endpoint, data=json.dumps(self.admin_user_data), content_type='application/json') data = json.loads(login_response.data.decode()) self.assertTrue(data['Authorization']) self.assertEqual(login_response.status_code, 200) return data
tails5555/Our_Title_Academy_2018_Server
UserAPI/src/main/java/io/kang/service/domain_service/implement_object/UserServiceImpl.java
package io.kang.service.domain_service.implement_object; import io.kang.domain.User; import io.kang.dto.UserDTO; import io.kang.enumeration.Type; import io.kang.repository.UserRepository; import io.kang.service.domain_service.interfaces.UserService; import io.kang.util.Encryption; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public List<UserDTO> findAll() { return userRepository.findAll() .stream().map(user -> UserDTO.builtToDTO(user)) .collect(Collectors.toList()); } @Override public List<UserDTO> findByUserType(final Type type) { return userRepository.findByUserType(type) .stream().map(user -> UserDTO.builtToDTO(user)) .collect(Collectors.toList()); } @Override public List<UserDTO> findByNicknameContains(final String nickname) { return userRepository.findByNicknameContains(nickname) .stream().map(user -> UserDTO.builtToDTO(user)) .collect(Collectors.toList()); } @Override public UserDTO getOne(final Long id) { if(userRepository.existsById(id)) return UserDTO.builtToDTO(userRepository.getOne(id)); else return null; } @Override public UserDTO findById(final Long id) { Optional<User> tmpUser = userRepository.findById(id); if(tmpUser.isPresent()) return UserDTO.builtToDTO(tmpUser.get()); else return null; } @Override public UserDTO findByLoginId(final String loginId) { Optional<User> tmpUser = userRepository.findByLoginId(loginId); if(tmpUser.isPresent()) return UserDTO.builtToDTO(tmpUser.get()); else return null; } @Override public UserDTO create(final UserDTO userDTO) { User tmpUser = UserDTO.builtToDomain(userDTO); UserDTO createUser = UserDTO.builtToDTO(userRepository.save(tmpUser)); if(createUser.getId() != null) return createUser; else return null; } @Override public UserDTO update(final UserDTO userDTO) { User tmpUser = UserDTO.builtToDomain(userDTO); UserDTO updateUser = UserDTO.builtToDTO(userRepository.save(tmpUser)); return updateUser; } @Override public void deleteById(final Long id) { userRepository.deleteById(id); } @Override public void deleteByLoginId(final String loginId) { userRepository.deleteByLoginId(loginId); } @Override public boolean existsById(final Long id) { return userRepository.existsById(id); } @Override public long count() { return userRepository.count(); } }
BloomTech-Labs/labs9-employee-scheduler
client/src/components/EmployeeCard/Availability.js
<reponame>BloomTech-Labs/labs9-employee-scheduler import React, { Component } from 'react' import PropTypes from 'prop-types' import styled from '@emotion/styled' import system from '../../design/theme' import CardContainer from '../common/CardContainer' import { formatHours, utcDayToLocal } from '../../utils' const weekdays = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ] // this component should render the employee's weekly availability. It, in the future, will also have the ability to turn into a form to update such info. class Availability extends Component { render() { const { availabilities } = this.props // the below should not render if there is no data being pass to it. This is not working though... return availabilities === [] ? null : ( <CardContainer avail id="avails"> {/* display the employee's weekly availability (e.g. Mon, weds. 8am to 5pm) in the employees directory, the supervisor should be able to select days and use a timepicker to alter this. */} <h6>Employee Availability</h6> {availabilities && availabilities // only displays the days the employee is available .map(({ id, day, start_time, end_time, off }) => ( //temporarily adds ids tp the DOM for easy access for testing <Avails key={id}> <p>{weekdays[utcDayToLocal({ day, time: start_time })]}</p> <span> {off ? 'unavailable' : `${formatHours(start_time)} - ${formatHours(end_time)}`} </span> </Avails> ))} </CardContainer> ) } } export default Availability Availability.propTypes = { // adding propTypes here availabilities: PropTypes.arrayOf( PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]) ) } const Avails = styled.div` display: flex; flex-flow: row nowrap; align-items: center; justify-content: space-between; width: 100%; margin-bottom: 5px; padding-bottom: 5px; border-bottom: 1px solid ${system.color.neutral}; :last-child { border-bottom: none; padding-bottom: 0; } p { font-weight: bold; font-size: ${system.fontSizing.sm}; color: ${system.color.lightgrey}; } span { color: ${system.color.bodytext}; font-size: ${system.fontSizing.s}; } `
hao-wang/Montage
js-test-suite/testsuite/2cca943741787722c4019614a9cb4f39.js
load("201224b0d1c296b45befd2285e95dd42.js"); // |jit-test| error: log is not defined if (!this.Promise) throw new Error('log is not defined'); var g = newGlobal(); var dbg = new Debugger(g); dbg.onPromiseSettled = function (g) { log += 's'; throw "foopy"; }; g.settlePromiseNow(new g.Promise(function (){}));
samphin/finish-projects
PomeloOrder/wallet-user-server/src/main/java/com/ryit/walletuserserver/service/WalletMenuService.java
<gh_stars>1-10 package com.ryit.walletuserserver.service; import com.ryit.commons.entity.pojo.WalletMenu; import com.ryit.commons.entity.vo.WalletMenuVo; import java.util.List; /** * @author: zhangweixun * @Date: 2019/9/21 0021下午 3:13 */ public interface WalletMenuService { /** * 添加菜单 * * @param walletMenu * @return */ Integer insertWalletMenu(WalletMenu walletMenu); /** * 修改菜单 * * @param walletMenu * @return */ Integer updateWalletMenu(WalletMenu walletMenu); /** * 删除菜单 * * @param menuId * @return */ Integer deleteWalletMenu(Long menuId); /** * 查询菜单列表 * * @return */ List<WalletMenuVo> queryMenuList(); /** * 查询菜单详情 * * @param menuId * @return */ WalletMenu queryMenuById(Long menuId); /** * 查询用户的菜单列表 * * @param userId * @return */ List<WalletMenuVo> queryUserMenuList(Long userId); }
moqmar/wekan
server/publications/swimlanes.js
<reponame>moqmar/wekan<gh_stars>1-10 Meteor.methods({ moveSwimlane(swimlaneId, toBoardId) { check(swimlaneId, String); check(toBoardId, String); const swimlane = Swimlanes.findOne(swimlaneId); const fromBoard = Boards.findOne(swimlane.boardId); const toBoard = Boards.findOne(toBoardId); if (swimlane && toBoard) { swimlane.lists().forEach(list => { const toList = Lists.findOne({ boardId: toBoardId, title: list.title, archived: false, }); let toListId; if (toList) { toListId = toList._id; } else { toListId = Lists.insert({ title: list.title, boardId: toBoardId, type: list.type, archived: false, wipLimit: list.wipLimit, }); } Cards.find({ listId: list._id, swimlaneId, }).forEach(card => { card.move(toBoardId, swimlaneId, toListId); }); }); Swimlanes.update(swimlaneId, { $set: { boardId: toBoardId, }, }); // make sure there is a default swimlane fromBoard.getDefaultSwimline(); return true; } return false; }, });
colohr/wwi
components/struct/logic/load.es6
<reponame>colohr/wwi window.fxy.exports('struct',(struct,fxy)=>{ struct.library = {folder:window.components.struct.path} //load load() //exports struct.load = { get actions(){ return load_actions }, get index(){ return get_index }, get ui(){ return load_ui }, get url(){ return get_url } } //shared actions function get_index(index){ return window.components[index].struct } function get_url(...paths){ return fxy.file.url(struct.library.url,'external',...paths) } function load(){ fxy.port.eval(fxy.file.url(window.components.struct.path,'logic/Interface.es6')).then(Interface=>struct.Interface = Interface) return null } function load_actions(item,type){ if(fxy.is.text(item)) item = {file:item} if(!fxy.is.text(type)) type = 'text' return new Promise((success,error)=>{ let name = struct.Actions.get_name(item.file,item.name) let action = struct.Actions.get(name) if(action) return success(action) return window.fetch(item.file).then(x=>x[type]()).then(content=>{ if(fxy.is.text(content)) item.content = content else if(fxy.is.array(content)) item = content[0] else item = content return success(struct.Actions.get(name,item)) }).catch(error) }) } function load_ui(){ return new Promise((success,error)=>{ if('UI' in struct) return success(struct.UI) return fxy.port.eval(fxy.file.url(struct.library.folder,'external/UI.es6')) .then(UI=>struct.UI = UI) .then(success).catch(error) }) } })
olevitt/sugoi-api
sugoi-api-services/src/main/java/fr/insee/sugoi/services/controller/v2/ConfigController.java
package fr.insee.sugoi.services.controller.v2; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import fr.insee.sugoi.services.mapper.RealmViewMapper; import fr.insee.sugoi.services.view.RealmView; import fr.insee.sugoi.sugoiapicore.service.ConfigService; @RestController @RequestMapping(value = { "/v2/config", "/config" }) public class ConfigController { @Autowired private ConfigService configService; @Autowired private RealmViewMapper realmViewMapper; @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, value = "/realm/{id}") public RealmView getRealm(@PathVariable("id") String id) { return realmViewMapper.mapperHandly(configService.getRealm(id)); } @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }, value = "/realms") public List<RealmView> getRealms() { return configService.getRealms().stream().map(realm -> realmViewMapper.mapperHandly(realm)) .collect(Collectors.toList()); } }
anmolnar/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/cluster/reset/ClusterResetState.java
package com.sequenceiq.cloudbreak.core.flow2.cluster.reset; import com.sequenceiq.flow.core.FlowState; import com.sequenceiq.flow.core.RestartAction; import com.sequenceiq.cloudbreak.core.flow2.restart.FillInMemoryStateStoreRestartAction; public enum ClusterResetState implements FlowState { INIT_STATE, CLUSTER_RESET_FAILED_STATE, CLUSTER_RESET_STATE, CLUSTER_RESET_FINISHED_STATE, CLUSTER_RESET_START_CLUSTER_MANAGER_FINISHED_STATE, FINAL_STATE; private final Class<? extends RestartAction> restartAction = FillInMemoryStateStoreRestartAction.class; @Override public Class<? extends RestartAction> restartAction() { return restartAction; } }
katarineaid/admin-BGS-E
back-server/services/auth/isAuthenticated.js
module.exports = function isAuthenticated(model, config) { return async function(params) { return await firstFunction(params, model, config); }; }; async function firstFunction(params, model, config) { let isAuth = await model.auth.isAuthenticated(params); return isAuth; }
ulisse1996/JAORM
jaorm-processor/src/test/resources/queries/QueryWithStream.java
<reponame>ulisse1996/JAORM package io.test; import io.github.ulisse1996.jaorm.annotation.Query; import io.test.SimpleEntity; import java.util.stream.Stream; public interface QueryWithStream { @Query(sql = "SELECT * FROM E WHERE ONE = ?") Stream<SimpleEntity> selectAll(String one); }
WhitmoreLakeTroBots/2019-DeepSpace
src/main/java/org/usfirst/frc3668/DeepSpace/commands/cmdGraspHatch.java
<filename>src/main/java/org/usfirst/frc3668/DeepSpace/commands/cmdGraspHatch.java<gh_stars>0 package org.usfirst.frc3668.DeepSpace.commands; import org.usfirst.frc3668.DeepSpace.Robot; import org.usfirst.frc3668.DeepSpace.Settings; import edu.wpi.first.wpilibj.command.Command; public class cmdGraspHatch extends Command { public static final int hatchSlowThreshold = 100; public static final double hatchSlowScalar = 0.75; public static final int hatchWindow = 5; public static final int hatchClosedTics = 450; public static final int hatchOpenTics = 0; boolean bDone = false; double throttle; double targetTics; double initTics; double deltaSignum; public cmdGraspHatch(double throttle, double targetTics) { this.throttle = throttle; this.targetTics = targetTics; requires(Robot.subHead); } public cmdGraspHatch(double throttle){ this.throttle = throttle; } // Called just before this Command runs the first time @Override protected void initialize() { bDone = false; initTics = Robot.subHead.getHatchEncoder(); if(initTics > hatchClosedTics / 2){ targetTics = hatchOpenTics; } else { targetTics = hatchClosedTics; } deltaSignum = Math.signum(targetTics - initTics); System.err.println("starting to move hatch thing " + targetTics); } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { double currentTics = Robot.subHead.getHatchEncoder(); double throttle = 0; double deltaTics = targetTics - currentTics; deltaSignum = Math.signum(deltaTics); if (deltaSignum > 0) { throttle = Settings.hatchThrottle; } else { throttle = -Settings.hatchThrottle; } if (Math.abs(deltaTics) <= hatchSlowThreshold) { throttle = throttle * hatchSlowScalar; } else if (Math.abs(initTics - currentTics)<= hatchSlowThreshold){ throttle = throttle * hatchSlowScalar; } System.err.println("Current Encoder Tics: " + currentTics); Robot.subHead.setHatchMotor(throttle); if (currentTics > targetTics - hatchWindow && currentTics < targetTics + hatchWindow) { System.err.println("ending hatch movement"); bDone = true; } } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return bDone; } // Called once after isFinished returns true @Override protected void end() { Robot.subHead.setHatchMotor(0); bDone = false; } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { Robot.subHead.setHatchMotor(0); } }
sachinshrestha483/AlgoDS
src/problems/medium/Combination.java
package problems.medium; import java.util.ArrayList; import java.util.List; /** * Created by sherxon on 6/3/17. */ public class Combination { private static void exec(List<List<Integer>> list, boolean[] b, int k, int i) { if (k < 0) { return; } if (k == 0) { List<Integer> l = new ArrayList<>(); for (int j = 1; j < b.length; j++) { if (b[j]) { l.add(j); } } list.add(l); } for (int j = i; j < b.length; j++) { if (!b[j]) { b[j] = true; exec(list, b, k - 1, j); b[j] = false; } } } public List<List<Integer>> combine(int n, int k) { List<List<Integer>> list = new ArrayList<>(); if (k <= 0 || k > n) { return list; } boolean[] b = new boolean[n + 1]; exec(list, b, k, 1); return list; } }
rapydo/do
controller/commands/tuning_modules/backend.py
<reponame>rapydo/do def tuning(ram: int, cpu: int) -> None: print(f"GUNICORN_MAX_NUM_WORKERS: {1 + 2 * cpu}")
ShnitzelKiller/polyfit
include/polyvec/regularity/collapse_opposite_short_segments.hpp
#pragma once #include <polyvec/core/macros.hpp> #include <polyvec/core/types.hpp> #include <polyvec/regularity/construct_regularity_graph.hpp> NAMESPACE_BEGIN(polyvec) NAMESPACE_BEGIN(Regularity) void collapse_opposite_short_segments( const polyfit::mat2x& B, polyfit::vecXi& P, const polyfit::Regularity::RegularityInformation& RE, const bool circular ); NAMESPACE_END(Regularity) NAMESPACE_END(polyvec)
clayne/CyberpunkSaveEditor
source/tools/rtti_dumper_dll/mem.hpp
<reponame>clayne/CyberpunkSaveEditor #pragma once #include <inttypes.h> #include <vector> #include <algorithm> #include <redx/core/utils.hpp> // maybe these utils could go in a mini lib.. namespace dumper { struct address_range { uintptr_t start = 0; uintptr_t end = 0; size_t size() const { return end - start; } operator bool() const { return start < end; } bool operator==(const address_range& rhs) const { return start == rhs.start && end == rhs.end; } }; inline std::vector<uintptr_t> find_pattern_in(const address_range& range, std::string pattern, std::string mask = "") { const uint8_t* needle = reinterpret_cast<unsigned char*>(pattern.data()); std::vector<uintptr_t> ret = redx::sse2_strstr_masked(range.start, range.size(), needle, pattern.size(), mask.c_str()); std::transform(std::begin(ret), std::end(ret), std::begin(ret), [](uintptr_t x) { return x; }); return ret; } } // namespace dumper
shaojiankui/iOS10-Runtime-Headers
PrivateFrameworks/CoreRC.framework/CoreCECDeviceProvider.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/CoreRC.framework/CoreRC */ @interface CoreCECDeviceProvider : CoreCECDevice { unsigned short _deckStatusRequestMask; unsigned char _sendFromAddress; unsigned int _userControlFollowerSafetyTimeoutGeneration; struct { CoreCECDevice *sender; struct CECUserControl { unsigned char command; union CECUICommandOperand { struct CECChannelIdentifier { unsigned int channelNumberFormat : 6; unsigned int majorChannelNumber : 10; unsigned int minorChannelNumber : 16; } channelIdentifier; unsigned char playMode; unsigned char broadcastType; unsigned char mediaNumber; unsigned char avInput; unsigned char audioInput; unsigned char soundPresentationControl; } operand; } control; bool isValid; } _userControlFollowerState; unsigned int _userControlInitiatorRepetitionTimeoutGeneration; struct { unsigned char destination; struct CECUserControl { unsigned char command; union CECUICommandOperand { struct CECChannelIdentifier { unsigned int channelNumberFormat : 6; unsigned int majorChannelNumber : 10; unsigned int minorChannelNumber : 16; } channelIdentifier; unsigned char playMode; unsigned char broadcastType; unsigned char mediaNumber; unsigned char avInput; unsigned char audioInput; unsigned char soundPresentationControl; } operand; } control; bool isValid; } _userControlInitiatorState; } @property (nonatomic, readonly) unsigned short deckStatusRequestMask; @property (nonatomic) unsigned char sendFromAddress; + (bool)supportsSecureCoding; - (bool)abortTo:(unsigned char)arg1 error:(id*)arg2; - (bool)activeSource:(id*)arg1; - (id)busProvider; - (bool)cecVersion:(unsigned char)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (Class)classForCoder; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (void)dealloc; - (bool)deckControlCommandWithMode:(unsigned long long)arg1 target:(id)arg2 error:(id*)arg3; - (bool)deckControlPlayWithMode:(unsigned long long)arg1 target:(id)arg2 error:(id*)arg3; - (bool)deckControlRefreshStatus:(id)arg1 requestType:(unsigned long long)arg2 error:(id*)arg3; - (bool)deckControlSetDeckStatus:(unsigned long long)arg1 error:(id*)arg2; - (bool)deckControlWithMode:(unsigned long long)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (unsigned short)deckStatusRequestMask; - (bool)deckStatusWithInfo:(unsigned long long)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)deviceVendorID:(unsigned int)arg1 error:(id*)arg2; - (void)didAddToBus:(id)arg1; - (void)didChangePowerStatus:(unsigned long long)arg1; - (void)didNotHandleMessage:(id)arg1 unsupportedOperand:(bool)arg2; - (void)didReceiveMessage:(id)arg1 fromDevice:(id)arg2; - (void)didRemoveFromBus:(id)arg1; - (void)error:(id)arg1 handlingMessage:(id)arg2 fromDevice:(id)arg3; - (id)extendedPropertyForKey:(id)arg1 error:(id*)arg2; - (bool)featureAbort:(unsigned char)arg1 reason:(unsigned char)arg2 to:(unsigned char)arg3 error:(id*)arg4; - (id)filterActiveSourceMessage:(id)arg1; - (id)filterCECVersionMessage:(id)arg1 toDevice:(id)arg2; - (id)filterDeckStatusMessage:(id)arg1 toDevice:(id)arg2; - (id)filterDeviceVendorIDMessage:(id)arg1; - (id)filterInactiveSourceMessage:(id)arg1 toDevice:(id)arg2; - (id)filterMessage:(id)arg1 fromDevice:(id)arg2; - (id)filterMessage:(id)arg1 toDevice:(id)arg2; - (id)filterReportPhysicalAddressMessage:(id)arg1; - (id)filterReportPowerStatusMessage:(id)arg1 toDevice:(id)arg2; - (id)filterRoutingChangeMessage:(id)arg1; - (id)filterRoutingInformationMessage:(id)arg1; - (id)filterSetMenuLanguageMessage:(id)arg1; - (id)filterSetOSDNameMessage:(id)arg1 toDevice:(id)arg2; - (id)filterSetStreamPathMessage:(id)arg1; - (id)filterSetSystemAudioModeMessage:(id)arg1 toDevice:(id)arg2; - (id)filterSystemAudioModeStatusMessage:(id)arg1 toDevice:(id)arg2; - (bool)getCECVersionTo:(unsigned char)arg1 error:(id*)arg2; - (bool)getMenuLanguageTo:(unsigned char)arg1 error:(id*)arg2; - (bool)getRemoteControlDestination:(id*)arg1 logicalAddress:(unsigned char*)arg2 forTargetDevice:(id)arg3 command:(unsigned char)arg4 error:(id*)arg5; - (bool)giveDeckStatusWithRequest:(unsigned char)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)giveDevicePowerStatusTo:(unsigned char)arg1 error:(id*)arg2; - (bool)giveDeviceVendorIDTo:(unsigned char)arg1 error:(id*)arg2; - (bool)giveOSDNameTo:(unsigned char)arg1 error:(id*)arg2; - (bool)givePhysicalAddressTo:(unsigned char)arg1 error:(id*)arg2; - (bool)giveSystemAudioModeStatusTo:(unsigned char)arg1 error:(id*)arg2; - (void)handleDeckControlMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleDeckControlPlayMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleDeviceSelected; - (void)handleFeatureAbortMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGetCECVersionMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGetMenuLanguageMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGiveDeckStatusMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGiveDevicePowerStatusMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGiveDeviceVendorIDMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGiveOSDNameMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleGivePhysicalAddressMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleMenuRequest:(id)arg1 fromDevice:(id)arg2; - (void)handleMessage:(id)arg1 fromDevice:(id)arg2 broadcast:(bool)arg3; - (void)handleRequestActiveSourceMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleSetStreamPathMessage:(id)arg1; - (void)handleSetSystemAudioModeMessage:(id)arg1 fromDevice:(id)arg2; - (bool)handleUserControl:(struct CECUserControl { unsigned char x1; union CECUICommandOperand { struct CECChannelIdentifier { unsigned int x_1_2_1 : 6; unsigned int x_1_2_2 : 10; unsigned int x_1_2_3 : 16; } x_2_1_1; unsigned char x_2_1_2; unsigned char x_2_1_3; unsigned char x_2_1_4; unsigned char x_2_1_5; unsigned char x_2_1_6; unsigned char x_2_1_7; } x2; })arg1 pressed:(bool)arg2 fromDevice:(id)arg3 abortReason:(unsigned char*)arg4; - (void)handleUserControlPressedMessage:(id)arg1 fromDevice:(id)arg2; - (void)handleUserControlReleasedMessage:(id)arg1 fromDevice:(id)arg2; - (void)hibernationChanged:(bool)arg1; - (bool)imageViewOnTo:(unsigned char)arg1 error:(id*)arg2; - (bool)inactiveSourceTo:(unsigned char)arg1 error:(id*)arg2; - (id)initWithBus:(id)arg1 local:(bool)arg2; - (id)initWithCoder:(id)arg1; - (id)initWithDevice:(id)arg1; - (bool)makeActiveSourceWithTVMenus:(bool)arg1 error:(id*)arg2; - (bool)menuStatus:(unsigned char)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)oneTouchPlayWithMenu:(bool)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)performStandbyWithTargetDevice:(id)arg1 error:(id*)arg2; - (bool)playWithMode:(unsigned long long)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)pollTo:(unsigned char)arg1 error:(id*)arg2; - (void)refreshActiveSource; - (bool)refreshProperties:(id)arg1 ofDevice:(id)arg2 error:(id*)arg3; - (void)refreshSystemAudioModeStatus; - (bool)reportPhysicalAddress:(id*)arg1; - (bool)reportPowerStatus:(unsigned char)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)requestActiveSource:(id*)arg1; - (bool)resignActiveSource:(id*)arg1; - (bool)routingChangeOriginalAddress:(unsigned long long)arg1 newAddress:(unsigned long long)arg2 error:(id*)arg3; - (bool)routingInformationPhysicalAddress:(unsigned long long)arg1 error:(id*)arg2; - (bool)sendActiveSourceStatus:(bool)arg1 error:(id*)arg2; - (void)sendDeckStatusToDevice:(id)arg1; - (void)sendFeatureAbort:(unsigned char)arg1 forMessage:(id)arg2; - (unsigned char)sendFromAddress; - (bool)sendHIDEvent:(id)arg1 target:(id)arg2 error:(id*)arg3; - (bool)sendMessage:(id)arg1 error:(id*)arg2; - (bool)sendMessage:(id)arg1 withRetryCount:(unsigned char)arg2 error:(id*)arg3; - (bool)setExtendedProperty:(id)arg1 forKey:(id)arg2 error:(id*)arg3; - (bool)setMenuLanguage:(struct CECLanguage { unsigned char x1[3]; })arg1 error:(id*)arg2; - (bool)setOSDName:(struct CECOSDName { unsigned char x1; unsigned char x2[14]; })arg1 to:(unsigned char)arg2 error:(id*)arg3; - (void)setSendFromAddress:(unsigned char)arg1; - (bool)setStreamPathPhysicalAddress:(unsigned long long)arg1 error:(id*)arg2; - (bool)setSystemAudioControlEnabled:(bool)arg1 error:(id*)arg2; - (bool)standbyTo:(unsigned char)arg1 error:(id*)arg2; - (bool)systemAudioModeRequest:(unsigned long long)arg1 error:(id*)arg2; - (bool)systemAudioModeRequest:(unsigned char)arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)textViewOnTo:(unsigned char)arg1 error:(id*)arg2; - (void)trackMessage:(id)arg1 fromDevice:(id)arg2; - (void)trackMessage:(id)arg1 toDevice:(id)arg2; - (void)userControlCancelFollowerSafetyTimeout; - (void)userControlCancelInitiatorRepetitionTimeout; - (void)userControlFollowerSafetyTimeoutExpired; - (void)userControlFollowerSynthesizeRelease; - (void)userControlInitiatorRepetitionTimeoutExpired; - (bool)userControlPressed:(struct CECUserControl { unsigned char x1; union CECUICommandOperand { struct CECChannelIdentifier { unsigned int x_1_2_1 : 6; unsigned int x_1_2_2 : 10; unsigned int x_1_2_3 : 16; } x_2_1_1; unsigned char x_2_1_2; unsigned char x_2_1_3; unsigned char x_2_1_4; unsigned char x_2_1_5; unsigned char x_2_1_6; unsigned char x_2_1_7; } x2; })arg1 to:(unsigned char)arg2 error:(id*)arg3; - (bool)userControlReleasedTo:(unsigned char)arg1 error:(id*)arg2; - (void)userControlScheduleFollowerSafetyTimeout; - (void)userControlScheduleInitiatorRepetitionTimeout; - (void)willRemoveFromBus:(id)arg1; @end
zhangshixu209/qiaoyang
src/main/java/com/chmei/nzbcommon/cmutil/BeanUtil.java
package com.chmei.nzbcommon.cmutil; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class BeanUtil { private static SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); private static Logger logger = LoggerFactory.getLogger(BeanUtil.class); /** 私有构造器 **/ private BeanUtil() { } /** * 将String转换成Date对象 * * @param date * @return Date对象 */ public static Date parse(String date) { String method = "parse"; try { return isEmpty(date) ? null : dateFormat.parse(date); } catch (ParseException e) { logger.error(method, "convert String 2 Date Error.", date, e); } return null; } /** * 将Date 对象转换成String * * @param date * @return */ public static String format(Date date) { return date == null ? "" : dateFormat.format(date); } /** * 判断字符串是否为空 * * @param value * @return */ public static boolean isEmpty(String value) { return (value == null || "".equals(value.trim())); } /** * 判断字符串是否不为空 * * @param value * @return */ public static boolean isNotEmpty(String value) { return !isEmpty(value); } /** * 通过反射获取值 */ public static Object getValueFromField(Field field, String name, String value) { Object object = value; String type = field.getType().getSimpleName(); if (isEmpty(value) && ("short,int,Integer,long,double,float".contains(type))) { value = "0"; } if ("short".equalsIgnoreCase(type)) { // Short object = Short.valueOf(value); } else if ("char".equals(type) || "Character".equals(type)) { // Character if (!BeanUtil.isEmpty(value)) { object = value.charAt(0); } } else if ("int".equals(type) || "Integer".equals(type)) { // Integer object = Integer.valueOf(value); } else if ("long".equalsIgnoreCase(type)) { // Long object = Long.valueOf(value); } else if ("byte".equalsIgnoreCase(type)) { // Byte object = Byte.valueOf(value); } else if ("float".equalsIgnoreCase(type)) { // Float object = Float.valueOf(value); } else if ("double".equalsIgnoreCase(type)) { // Double object = Double.valueOf(value); } else if ("boolean".equalsIgnoreCase(type)) { // Boolean object = Boolean.valueOf(value); } else if ("Date".equals(type)) { // Date object = BeanUtil.parse(value); } else if ("byte[]".equalsIgnoreCase(type)) { // byte[] object = ConvertUtil.string2Bytes(value); } return object; } /** * 通过反射获取值 */ public static Object getValueFromField(Object object, Field field) { try { Object value = field.get(object); String type = field.getType().getSimpleName(); /* * if ("short".equalsIgnoreCase(type)) { // Short value = * Short.valueOf(value); } else if * ("char".equals(type)||"Character".equals(type)) { // char value = * field.getChar(object); } else if * ("int".equals(type)||"Integer".equals(type)) { // int value = * field.getInt(object); } else if ("long".equalsIgnoreCase(type)) { * // long value = field.getLong(object); } else if * ("byte".equalsIgnoreCase(type)) { // byte value = * field.getByte(object); } else if ("float".equalsIgnoreCase(type)) * { // float value = field.getFloat(object); } else if * ("double".equalsIgnoreCase(type)) { // double value = * field.getDouble(object); } else if * ("boolean".equalsIgnoreCase(type)) { // boolean value = * field.getBoolean(object); } else */ if ("Date".equals(type)) { // Date value = BeanUtil.format((Date) value); } else if ("byte[]".equalsIgnoreCase(type)) { // byte[] if (value != null) { value = ConvertUtil.bytes2String((byte[]) value); } } else if ("String".equalsIgnoreCase(type)) { if (value == null) { value = ""; } } else { value = field.get(object); } return value; } catch (Exception e) { throw new RuntimeException(e); } } /** * 获取所有父类的属性列表 */ public static Field[] getSuperFields(Class<?> subCls, List<Field> subFields) { Class<?> superClass = subCls.getSuperclass(); subFields = new ArrayList<Field>(subFields); if (superClass != null && superClass != Object.class) { Field[] superFields = superClass.getDeclaredFields(); subFields.addAll(Arrays.asList(superFields)); if (superClass.getSuperclass() != Object.class) { getSuperFields(superClass, subFields);// 递归调用 } } return subFields.toArray(new Field[subFields.size()]); } /** * 转换Map<String,Object> 转换成T对应的对象 * * @param 需要转换的结果类型 */ public static <T> T convertMap2Bean(Map<String, Object> bean, Class<T> clz) { if (bean == null) { return null; } try { T t = clz.newInstance(); Field[] fields = t.getClass().getDeclaredFields(); fields = BeanUtil.getSuperFields(clz, Arrays.asList(fields));// 获取父类的属性列表 for (Field field : fields) { String key = field.getName();// 获取属性名 String value = (String) bean.get(key); if (value == null || "null".equals(value)) { continue; }// 如果对应属性的值,bean中不存在,返回继续遍历 boolean visiable = field.isAccessible(); field.setAccessible(Boolean.TRUE); Object object = BeanUtil.getValueFromField(field, key, value); field.set(t, object); field.setAccessible(visiable); } return t; } catch (Exception e) { throw new RuntimeException(e); } } /** * 将对象转换成Map<String,Object> * * @param 需要转换的对象 */ public static Map<String, Object> convertBean2Map(Object object) { if (object == null) { return null; } Map<String, Object> bean = new HashMap<String, Object>(); try { Field[] fields = object.getClass().getDeclaredFields(); fields = getSuperFields(object.getClass(), Arrays.asList(fields)); for (Field field : fields) { String key = field.getName(); // 非序列号 && 非静态属性 if (!"serialVersionUID".equals(key) && !Modifier.isStatic(field.getModifiers())) { boolean visible = field.isAccessible(); field.setAccessible(Boolean.TRUE); Object value = BeanUtil.getValueFromField(object, field); field.setAccessible(visible); bean.put(key.trim(), value); } } return bean; } catch (Exception e) { throw new RuntimeException(e); } } public static List<Map<String, Object>> convertBeans2List(Object... objects) { if (objects == null) { return null; } List<Map<String, Object>> beans = new ArrayList<Map<String, Object>>(); for (Object object : objects) { Map<String, Object> bean = BeanUtil.convertBean2Map(object); if (bean != null && bean.size() != 0) { beans.add(bean); } } return beans; } public static <T> List<T> convertList2Beans( List<Map<String, Object>> lists, Class<T> clz) { if (lists == null || lists.size() == 0) { return null; } List<T> results = new ArrayList<T>(); for (Map<String, Object> map : lists) { T t = convertMap2Bean(map, clz); if (t != null) { results.add(t); } } return results; } /** * 将对象转换成Map<String,Object> * <p>不进行数据类型转换,不包含null字段 * <p>李新杰 * @param 需要转换的对象 */ public static Map<String, Object> convertBeanToMap(Object object) { return convertBeanToMap(object, false); } /** * 将对象转换成Map<String,Object> * <p>不进行数据类型转换 * <p>李新杰 * @param 需要转换的对象 */ public static Map<String, Object> convertBeanToMap(Object object, boolean includeNull) { Map<String, Object> bean = new HashMap<String, Object>(); if (object == null) { return bean; } try { Field[] fields = object.getClass().getDeclaredFields(); fields = getSuperFields(object.getClass(), Arrays.asList(fields)); for (Field field : fields) { String key = field.getName(); // 非序列号 && 非静态属性 if (!"serialVersionUID".equals(key) && !Modifier.isStatic(field.getModifiers())) { field.setAccessible(true); Object value = field.get(object); if (value != null) { bean.put(key, value); } else if (includeNull) { bean.put(key, value); } } } return bean; } catch (Exception e) { throw new RuntimeException(e); } } }
philuu12/PYTHON_4_NTWK_ENGRS
wk7_hw/library/ex3_add_vlan_arista.py
#!/usr/bin/env python # Symbolically linked to this real file: /home/pluu/ANSIBLE/library/ex3_add_vlan_arista.py import pyeapi from ansible.module_utils.basic import * def check_vlan_exists(eapi_conn, vlan_id): ''' Check if the given VLAN exists Return either vlan_name or False ''' vlan_id = str(vlan_id) cmd = 'show vlan id {}'.format(vlan_id) try: response = eapi_conn.enable(cmd) check_vlan = response[0]['result']['vlans'] return check_vlan[vlan_id]['name'] except (pyeapi.eapilib.CommandError, KeyError): pass return False def configure_vlan(eapi_conn, vlan_id, vlan_name=None): cmd = ['vlan {}'.format(vlan_id)] if vlan_name: cmd.append('name {}'.format(vlan_name)) return eapi_conn.config(cmd) def check_if_system_state_would_be_changed(old_vlan_name, new_vlan_name): if old_vlan_name: # VLAN name needs to be set if new vlan name different from old vlan name if new_vlan_name is not None and new_vlan_name != old_vlan_name: return True else: return False else: # Vlan does not exist return True # =========================================== def main(): module = AnsibleModule( argument_spec = dict( arista_sw=dict(required=True), vlan_id=dict(required=True), vlan_name=dict(required=False), ), supports_check_mode=True ) vlan_id = module.params['vlan_id'] vlan_name = module.params.get('vlan_name') arista_sw = module.params.get('arista_sw') eapi_conn = pyeapi.connect_to(arista_sw) check_vlan = check_vlan_exists(eapi_conn, vlan_id) if module.check_mode: # Check if any changes would be made but don't actually make those changes module.exit_json(changed= check_if_system_state_would_be_changed(check_vlan, vlan_name)) if check_vlan: # VLAN name needs to be set if vlan_name is not None and vlan_name != check_vlan: configure_vlan(eapi_conn, vlan_id, vlan_name) module.exit_json(msg="VLAN already exists, VLAN name set.", changed=True) else: module.exit_json(msg="VLAN already exists, no action.", changed=False) else: # Vlan does not exist configure_vlan(eapi_conn, vlan_id, vlan_name) module.exit_json(msg="Add VLAN including vlan_name (if present)", changed=True) #---------------------------------------- if __name__ == "__main__": main()
tavaresdong/courses-notes
uw_cse333/exs/ex4/ex4.c
#include "GetPrime.h" #include <stdio.h> #include <inttypes.h> #include <stdlib.h> int main(int argc, char **argv) { for(int ind = 1; ind <= 10; ++ind) printf("%llu ", GetPrime(ind)); return EXIT_SUCCESS; }
hYdos/Create
src/main/java/com/simibubi/create/content/curiosities/tools/ExtendoGripRenderHandler.java
package com.simibubi.create.content.curiosities.tools; import com.jozufozu.flywheel.core.PartialModel; import com.jozufozu.flywheel.util.transform.MatrixTransformStack; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import com.simibubi.create.AllBlockPartials; import com.simibubi.create.AllItems; import com.simibubi.create.foundation.utility.AnimationTickHolder; import net.minecraft.client.Minecraft; import net.minecraft.client.player.AbstractClientPlayer; import net.minecraft.client.player.LocalPlayer; import net.minecraft.client.renderer.ItemInHandRenderer; import net.minecraft.client.renderer.entity.player.PlayerRenderer; import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.HumanoidArm; import net.minecraft.util.Mth; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.RenderHandEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; @EventBusSubscriber(value = Dist.CLIENT) public class ExtendoGripRenderHandler { public static float mainHandAnimation; public static float lastMainHandAnimation; public static PartialModel pose = AllBlockPartials.DEPLOYER_HAND_PUNCHING; public static void tick() { lastMainHandAnimation = mainHandAnimation; mainHandAnimation *= Mth.clamp(mainHandAnimation, 0.8f, 0.99f); pose = AllBlockPartials.DEPLOYER_HAND_PUNCHING; if (!AllItems.EXTENDO_GRIP.isIn(getRenderedOffHandStack())) return; ItemStack main = getRenderedMainHandStack(); if (main.isEmpty()) return; if (!(main.getItem() instanceof BlockItem)) return; if (!Minecraft.getInstance() .getItemRenderer() .getModel(main, null, null, 1) // PORT: scale .isGui3d()) return; pose = AllBlockPartials.DEPLOYER_HAND_HOLDING; } @SubscribeEvent public static void onRenderPlayerHand(RenderHandEvent event) { ItemStack heldItem = event.getItemStack(); Minecraft mc = Minecraft.getInstance(); LocalPlayer player = mc.player; boolean rightHand = event.getHand() == InteractionHand.MAIN_HAND ^ player.getMainArm() == HumanoidArm.LEFT; ItemStack offhandItem = getRenderedOffHandStack(); boolean notInOffhand = !AllItems.EXTENDO_GRIP.isIn(offhandItem); if (notInOffhand && !AllItems.EXTENDO_GRIP.isIn(heldItem)) return; PoseStack ms = event.getMatrixStack(); MatrixTransformStack msr = MatrixTransformStack.of(ms); AbstractClientPlayer abstractclientplayerentity = mc.player; RenderSystem.setShaderTexture(0, abstractclientplayerentity.getSkinTextureLocation()); float flip = rightHand ? 1.0F : -1.0F; float swingProgress = event.getSwingProgress(); boolean blockItem = heldItem.getItem() instanceof BlockItem; float equipProgress = blockItem ? 0 : event.getEquipProgress() / 4; ms.pushPose(); if (event.getHand() == InteractionHand.MAIN_HAND) { if (1 - swingProgress > mainHandAnimation && swingProgress > 0) mainHandAnimation = 0.95f; float animation = Mth.lerp(AnimationTickHolder.getPartialTicks(), ExtendoGripRenderHandler.lastMainHandAnimation, ExtendoGripRenderHandler.mainHandAnimation); animation = animation * animation * animation; ms.translate(flip * (0.64000005F - .1f), -0.4F + equipProgress * -0.6F, -0.71999997F + .3f); ms.pushPose(); msr.rotateY(flip * 75.0F); ms.translate(flip * -1.0F, 3.6F, 3.5F); msr.rotateZ(flip * 120) .rotateX(200) .rotateY(flip * -135.0F); ms.translate(flip * 5.6F, 0.0F, 0.0F); msr.rotateY(flip * 40.0F); ms.translate(flip * 0.05f, -0.3f, -0.3f); PlayerRenderer playerrenderer = (PlayerRenderer) mc.getEntityRenderDispatcher() .getRenderer(player); if (rightHand) playerrenderer.renderRightHand(event.getMatrixStack(), event.getBuffers(), event.getLight(), player); else playerrenderer.renderLeftHand(event.getMatrixStack(), event.getBuffers(), event.getLight(), player); ms.popPose(); // Render gun ms.pushPose(); ms.translate(flip * -0.1f, 0, -0.3f); ItemInHandRenderer firstPersonRenderer = mc.getItemInHandRenderer(); TransformType transform = rightHand ? TransformType.FIRST_PERSON_RIGHT_HAND : TransformType.FIRST_PERSON_LEFT_HAND; firstPersonRenderer.renderItem(mc.player, notInOffhand ? heldItem : offhandItem, transform, !rightHand, event.getMatrixStack(), event.getBuffers(), event.getLight()); if (!notInOffhand) { ForgeHooksClient.handleCameraTransforms(ms, mc.getItemRenderer() .getModel(offhandItem, null, null, 1), transform, !rightHand);// PORT: scale ms.translate(flip * -.05f, .15f, -1.2f); ms.translate(0, 0, -animation * 2.25f); if (blockItem && mc.getItemRenderer() .getModel(heldItem, null, null, 1) // PORT: scale .isGui3d()) { msr.rotateY(flip * 45); ms.translate(flip * 0.15f, -0.15f, -.05f); ms.scale(1.25f, 1.25f, 1.25f); } firstPersonRenderer.renderItem(mc.player, heldItem, transform, !rightHand, event.getMatrixStack(), event.getBuffers(), event.getLight()); } ms.popPose(); } ms.popPose(); event.setCanceled(true); } private static ItemStack getRenderedMainHandStack() { return Minecraft.getInstance().getItemInHandRenderer().mainHandItem; } private static ItemStack getRenderedOffHandStack() { return Minecraft.getInstance().getItemInHandRenderer().offHandItem; } }
Nasdan/phone-catalog
frontend/src/pages/phones/list/components/index.js
export * from './header'; export * from './list';
lsytj0413/fyllo
pkg/segment/builder/builder.go
// Copyright (c) 2018 <NAME> // // Licensed under the MIT License // you may not use this file except in complicance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // 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 builder import ( "fmt" "strings" "github.com/lsytj0413/fyllo/pkg/errors" "github.com/lsytj0413/fyllo/pkg/segment" "github.com/lsytj0413/fyllo/pkg/segment/mem" "github.com/lsytj0413/fyllo/pkg/segment/mysql" ) // AvailableProviders supported by the segment provider builder. var AvailableProviders = []string{ mysql.ProviderName, mem.ProviderName, } // AvailableProvidersDescription is string readable description for providers list var AvailableProvidersDescription string // Options for builder type Options struct { ProviderName string ProviderArgs string } // Builder for build segment provider type Builder interface { // Build will return segment.Provider implement specfied by the ProviderName Build() (segment.Provider, error) } // NewBuilder return Builder instance func NewBuilder(options *Options) (Builder, error) { found := false for _, name := range AvailableProviders { if name == options.ProviderName { found = true break } } if !found { return nil, errors.NewError(errors.EcodeProviderNotImplement, fmt.Sprintf("Invalid Segment ProviderName[%s], Avaliable: %s", options.ProviderName, AvailableProvidersDescription)) } return &builder{ options: options, }, nil } type builder struct { options *Options } func (b *builder) Build() (segment.Provider, error) { switch b.options.ProviderName { case mysql.ProviderName: return createMysqlProvider(b.options) case mem.ProviderName: return createMemProvider(b.options) } return nil, errors.NewError(errors.EcodeProviderNotImplement, fmt.Sprintf("Invalid Segment ProviderName[%s], Avaliable: %s", b.options.ProviderName, AvailableProvidersDescription)) } var createMysqlProvider = func(option *Options) (segment.Provider, error) { return mysql.NewProvider(&mysql.Options{ Args: option.ProviderArgs, }) } var createMemProvider = func(option *Options) (segment.Provider, error) { return mem.NewProvider(&mem.Options{ Args: option.ProviderArgs, }) } func init() { AvailableProvidersDescription = "[" + strings.Join(AvailableProviders, ", ") + "]" }
vitimachado/bexsit
src/components/card/vote-buttons.js
<filename>src/components/card/vote-buttons.js import React, { useEffect, useState } from 'react'; import './card.css'; import Tooltip from '@material-ui/core/Tooltip'; import Button from '@material-ui/core/Button'; import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp'; import KeyboardArrowDownIcon from '@material-ui/icons/KeyboardArrowDown'; import { useSelector } from 'react-redux'; import { refreshHome, voteQuestion } from '../../store/actions'; export const Vote = ({votesObj}) => { const [votes, setVotes] = useState(votesObj.votes); const [vote, setVote] = useState("votesObj.vote"); const user = useSelector(state => state.users.user); //console.log('arrayCards', votesObj); useEffect(() => { let ups = user && user.votes && user.votes.ups ? user.votes.ups : []; let downs = user && user.votes && user.votes.downs ? user.votes.downs : []; if(ups && ups.includes(votesObj.id)) setVote('up'); else if(downs && downs && downs.includes(votesObj.id)) setVote('down'); setVotes(votesObj.votes); //console.log('uuuuuuuuuuuuuuuuuuuuuuuu answersData', votesObj, user); }, [votesObj, user]) let changeVote = (e, voteNew) => { //console.log(e.type, voteNew, user); //console.log(votesObj, votesObj.id); //console.log(votesObj.votes); let { ups, downs } = user.votes; if(voteNew == 'up') { votesObj.votes = votesObj.votes+1; if(vote === 'down') { votesObj.votes = votesObj.votes+1; downs = downs.filter(e => e !== votesObj.id); } ups = [ ...ups, votesObj.id ]; } else { votesObj.votes = votesObj.votes-1; if(vote === 'up') { votesObj.votes = votesObj.votes-1; ups = ups.filter(e => e !== votesObj.id); } downs = [ ...downs, votesObj.id ]; } user.votes = {ups, downs}; voteQuestion({ ...votesObj, user }).then(async (res) => { //console.log('handleLikeAnswer user', res); if(res && res.data && !res.error ) { refreshHome({ votesObj: votesObj.id, userId: votesObj.userId }); } }); } return ( <div className="textAlignCenter"> <Button style={{minWidth: 0}} className={vote === 'up' ? "vote-selected green-vote" : ""} onMouseUp={(e) => changeVote(e, 'up')}> <Tooltip title="Vote +" aria-label="Vote +"><KeyboardArrowUpIcon /></Tooltip> </Button> <strong>{votes}</strong> <Button style={{minWidth: 0}} className={vote === 'down' ? "vote-selected red-vote" : ""} onMouseUp={(e) => changeVote(e, 'down')}> <Tooltip title="Vote -" aria-label="Vote -"><KeyboardArrowDownIcon /></Tooltip> </Button> </div> ) }
nolbuzanis/Impressions
client/src/components/Player.js
import React from 'react'; import './Player.css'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { playSong } from '../actions'; //Tippy.js import tippy from 'tippy.js'; import 'tippy.js/dist/tippy.css'; class Player extends React.Component { state = { paused: true, album: null, deviceId: null, songId: null, shuffle: false, repeat: false }; componentDidMount() { if (window.loadedSpotifyPlayer && !this.player) { this.initializePlayer(); } window.addEventListener('load', this.initializePlayer); } initializePlayer = () => { if (window.Spotify !== null) { console.log('Initializing...'); this.player = new window.Spotify.Player({ name: 'Impressions', getOAuthToken: cb => { cb(this.props.auth.accessToken); } }); // Error handling this.player.on('initialization_error', e => { console.error(e); }); this.player.on('authentication_error', e => { console.error(e); return <Redirect to='/dashboard' />; }); this.player.on('account_error', e => { console.error(e); }); this.player.on('playback_error', e => { console.error(e); }); // Playback status updates this.player.on('player_state_changed', state => { this.onStateChanged(state); }); // Ready this.player.addListener('ready', ({ device_id }) => { console.log('Ready with Device ID', device_id); this.setState({ deviceId: device_id }); this.props.getActiveDevice(device_id); }); // Not Ready this.player.addListener('not_ready', ({ device_id }) => { console.log('Device ID has gone offline', device_id); this.setState({ deviceId: device_id }); }); this.player.connect(); } }; //Handle players state to update our own component level state onStateChanged = state => { // If no longer listening to music, return if (state === null) { return; } const currentTrack = state.track_window.current_track; const trackName = currentTrack.name; const album = currentTrack.album; const artistName = currentTrack.artists .map(artist => { return artist.name; }) .join(','); const songId = currentTrack.linked_from.id || currentTrack.id; const { paused, duration, position } = state; this.setState({ songId, trackName, album, artistName, paused, duration, position }); }; togglePlaySong = () => { // If song is already playing/ paused if (this.state.trackName) { this.player.togglePlay(); } else { // If shuffle is selected if (this.state.shuffle) { this.playRandomSong(); return; } // Play song from beginning this.props.playSong( this.props.auth.accessToken, this.state.deviceId, this.props.spotify.library[0].uri ); } }; findCurrentIndex = () => { for (const [ i, song ] of this.props.spotify.audioFeatures.allsongs.entries()) { if (this.state.songId === song.id) { return i; } } }; renderSongFeatures = () => { // No song currently playing if (!this.state.songId) { return null; } const index = this.findCurrentIndex(); var { a, d, e, v } = this.props.spotify.audioFeatures.allsongs[index]; a = Math.round(a * 100); d = Math.round(d * 100); e = Math.round(e * 100); v = Math.round(v * 100); const colors = { acousticness: '#999AFF', danceability: '#FF6666', energy: '#FFA401', valence: '#3E98C7' }; //Tooltips tippy('#acousticness', { content: 'acousticness' }); tippy('#danceability', { content: 'danceability' }); tippy('#energy', { content: 'energy' }); tippy('#valence', { content: 'valence' }); return ( <ul> <li id='acousticness' style={{ background: colors.acousticness }}> {' '} {a} </li> <li id='danceability' style={{ background: colors.danceability }}> {' '} {d} </li> <li id='energy' style={{ background: colors.energy }}> {e} </li> <li id='valence' style={{ background: colors.valence }}> {' '} {v} </li> </ul> ); }; previousTrack = () => { // If current song is the first one in the library, start it again if (!this.props.spotify.library[this.findCurrentIndex() - 1]) { this.props.playSong( this.props.auth.accessToken, this.state.deviceId, this.props.spotify.library[0].uri ); return; } // If no song is currently playing if (!this.state.trackName) { this.togglePlaySong(); return; } const uri = this.props.spotify.library[this.findCurrentIndex() - 1].uri; this.props.playSong(this.props.auth.accessToken, this.state.deviceId, uri); }; playRandomSong = () => { const randIndex = Math.floor( Math.random() * this.props.spotify.library.length ); this.props.playSong( this.props.auth.accessToken, this.state.deviceId, this.props.spotify.library[randIndex].uri ); }; nextTrack = () => { // If shuffle is true: if (this.state.shuffle) { this.playRandomSong(); return; } // If current song is the last one in the library, play from beginning if (!this.props.spotify.library[this.findCurrentIndex() + 1]) { this.props.playSong( this.props.auth.accessToken, this.state.deviceId, this.props.spotify.library[0].uri ); return; } // If no song is currently playing if (!this.state.trackName) { this.togglePlaySong(); return; } const uri = this.props.spotify.library[this.findCurrentIndex() + 1].uri; this.props.playSong(this.props.auth.accessToken, this.state.deviceId, uri); }; toggleShuffle = () => { // If false, set true if (!this.state.shuffle) { this.setState({ shuffle: true }); return; } this.setState({ shuffle: false }); }; render() { return ( <div className='fixed-bottom player'> <div className='currently-playing' style={{ display: `${this.state.trackName ? 'inherit' : 'none'}` }} > <div className='album-artwork' style={{ background: `url(${ this.state.album ? `${this.state.album.images[1].url}` : '' })` }} ></div> <div className='song-info'> <p className='song-name'>{this.state.trackName}</p> <p>{this.state.artistName}</p> </div> </div> <ul className='player-controls'> <li> <button className='player-link' onClick={() => { this.toggleShuffle(); }} > <i className='material-icons' style={{ color: `${this.state.shuffle ? '#0074D9' : ''}` }} > shuffle </i> </button> </li> <li> <button className='player-link' onClick={() => this.previousTrack()} > <i className='material-icons'>skip_previous</i> </button> </li> <li> <button className='player-link' onClick={() => this.togglePlaySong()} > <i className='material-icons'> {this.state.paused ? 'play_arrow' : 'pause'} </i> </button> </li> <li> <button className='player-link' onClick={() => this.nextTrack()}> <i className='material-icons'>skip_next</i> </button> </li> <li> <button className='player-link'> <i className='material-icons'>repeat</i> </button> </li> </ul> <div className='song-features'>{this.renderSongFeatures()}</div> </div> ); } } const mapStateToProps = state => { return { auth: state.auth, spotify: state.spotify }; }; export default connect( mapStateToProps, { playSong } )(Player);
NatickYT/CraftTweaker
Common/src/gametest/java/com/blamejared/crafttweaker/gametest/test/api/util/InstantiationUtilTest.java
<gh_stars>1-10 package com.blamejared.crafttweaker.gametest.test.api.util; import com.blamejared.crafttweaker.api.util.InstantiationUtil; import com.blamejared.crafttweaker.gametest.CraftTweakerGameTest; import com.blamejared.crafttweaker.gametest.CraftTweakerGameTestHolder; import com.blamejared.crafttweaker.gametest.TestModifier; import com.blamejared.crafttweaker.gametest.test.stub.ClassWithFieldAndConstructor; import com.blamejared.crafttweaker.gametest.test.stub.ClassWithOnlyConstructor; import com.blamejared.crafttweaker.gametest.test.stub.ClassWithOnlyField; import com.blamejared.crafttweaker.gametest.test.stub.ClassWithoutFieldOrConstructor; import net.minecraft.gametest.framework.GameTest; import net.minecraft.gametest.framework.GameTestHelper; @SuppressWarnings("ConstantConditions") @CraftTweakerGameTestHolder public class InstantiationUtilTest implements CraftTweakerGameTest { @GameTest(template = "crafttweaker:empty") @TestModifier(implicitSuccession = true) public void testThatPublicStaticFieldIsUsedIfPresent(GameTestHelper helper) { final ClassWithOnlyField instance = InstantiationUtil.getOrCreateInstance(ClassWithOnlyField.class); assertThat(instance) .isNotNull(); assertThat(instance.getClass()) .isEqualTo(ClassWithOnlyField.class); assertWithMessage("getOrCreateInstance must return field content") .that(instance) .isEqualTo(ClassWithOnlyField.INSTANCE); } @GameTest(template = "crafttweaker:empty") @TestModifier(implicitSuccession = true) public void testThatPublicConstructorIsUsedIfPresent(GameTestHelper helper) { final ClassWithOnlyConstructor instance = InstantiationUtil.getOrCreateInstance(ClassWithOnlyConstructor.class); assertThat(instance) .isNotNull(); assertThat(instance.getClass()) .isEqualTo(ClassWithOnlyConstructor.class); } @GameTest(template = "crafttweaker:empty") @TestModifier(implicitSuccession = true) public void testThatPublicStaticFieldIsPreferredOverConstructor(GameTestHelper helper) { final ClassWithFieldAndConstructor instance = InstantiationUtil.getOrCreateInstance(ClassWithFieldAndConstructor.class); assertThat(instance) .isNotNull(); assertThat(instance.getClass()) .isEqualTo(ClassWithFieldAndConstructor.class); assertWithMessage("getOrCreateInstance must return field content") .that(instance) .isEqualTo(ClassWithFieldAndConstructor.INSTANCE); } @GameTest(template = "crafttweaker:empty") @TestModifier(implicitSuccession = true) public void testThatMethodReturnsNullWhenNeitherFieldNorConstructorArePresent(GameTestHelper helper) { final ClassWithoutFieldOrConstructor instance = InstantiationUtil.getOrCreateInstance(ClassWithoutFieldOrConstructor.class); assertThat(instance) .isNull(); } }
friskit-china/leetcode-cn-repo
leetcode/leetcode_0167_easy_two_sum_ii_input_array_is_sorted/v01.java
package leetcode.leetcode_0167_easy_two_sum_ii_input_array_is_sorted; public class v01 { static class Solution { public int[] twoSum(int[] numbers, int target) { int i = 0; int j = numbers.length - 1; while (true){ if (numbers[i] + numbers[j] < target){ i += 1; }else if(numbers[i] + numbers[j] > target){ j -= 1; }else{ // numbers[i] + numbers[j] == target return new int[]{i + 1, j + 1}; } } } } public static void main(String[] argv){ int[] result = new Solution().twoSum(new int[]{2, 7, 11, 15}, 9); System.out.println(result[0] + " " + result[1]); } }
AlbertHello/CommonDataStructure
LeetCode/LeetCode/算法/_190_Reverse_Bits.h
// // _190_Reverse_Bits.h // LeetCode // // Created by 58 on 2020/12/28. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface _190_Reverse_Bits : NSObject @end NS_ASSUME_NONNULL_END
PacktPublishing/Secret-Recipes-of-the-Python-Ninja
Chapter05/gen_comprehension_loop.py
<reponame>PacktPublishing/Secret-Recipes-of-the-Python-Ninja<filename>Chapter05/gen_comprehension_loop.py for i in g:
threepointone/built-devtools
front_end/panels/elements/ImagePreviewPopover.js
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as Components from '../../ui/legacy/components/utils/utils.js'; import * as UI from '../../ui/legacy/legacy.js'; /** * ImagePreviewPopover sets listeners on the container element to display * an image preview if needed. The image URL comes from the event (mouseover) target * in a propery identified by HrefSymbol. To enable preview for any child element * set the property HrefSymbol. */ export class ImagePreviewPopover { getLinkElement; getDOMNode; popover; constructor(container, getLinkElement, getDOMNode) { this.getLinkElement = getLinkElement; this.getDOMNode = getDOMNode; this.popover = new UI.PopoverHelper.PopoverHelper(container, this.handleRequest.bind(this)); this.popover.setHasPadding(true); this.popover.setTimeout(0, 100); } handleRequest(event) { const link = this.getLinkElement(event); if (!link) { return null; } const href = elementToURLMap.get(link); if (!href) { return null; } return { box: link.boxInWindow(), hide: undefined, show: async (popover) => { const node = this.getDOMNode(link); if (!node) { return false; } const precomputedFeatures = await Components.ImagePreview.ImagePreview.loadDimensionsForNode(node); const preview = await Components.ImagePreview.ImagePreview.build(node.domModel().target(), href, true, { imageAltText: undefined, precomputedFeatures }); if (preview) { popover.contentElement.appendChild(preview); } return Boolean(preview); }, }; } hide() { this.popover.hidePopover(); } static setImageUrl(element, url) { elementToURLMap.set(element, url); return element; } static getImageURL(element) { return elementToURLMap.get(element); } } const elementToURLMap = new WeakMap(); //# sourceMappingURL=ImagePreviewPopover.js.map
LeonardoFerraz25/Trybe-exercicios
Fundamentos/bloco-4/dia4.3/ex002.js
let word = 'Trybe'; let reverse =[]; for(let i = word.length-1; i >= 0; i--){ reverse += word[i]; } console.log(reverse);
brushknight/homebrew-core
Formula/vlang.rb
class Vlang < Formula desc "V programming language" homepage "https://vlang.io" # NOTE: Keep this in sync with V compiler below when updating url "https://github.com/vlang/v/archive/0.2.2.tar.gz" sha256 "9152eec96d2eeb575782cf138cb837f315e48c173878857441d98ba679e3a9bf" license "MIT" livecheck do url :stable regex(/^v?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "c6d2d50296fdad67fb6ea868b8b530e8979db42575679fc8ffd1a1757f530147" sha256 cellar: :any_skip_relocation, big_sur: "9be25862e7c69582ef1c8ee312e10e76988e5247439657f704078f56a5f6abc3" sha256 cellar: :any_skip_relocation, catalina: "d4e2bde9c42995a3c348f1ede4a78fa579a22b601144cc0b8adeb009d310c1b7" sha256 cellar: :any_skip_relocation, mojave: "0fe9d3b759400cee1a53c10f1a913a541d2f2f151822ff82454e953796c931cf" sha256 cellar: :any_skip_relocation, x86_64_linux: "cb13270e51de665c0253e5c0f900bf88fcc24f870326ef6e1face32d7b6111fb" end resource "vc" do # For every vlang release there is a matching commit of the V compiler in the format # "[v:master] {short SHA of the vlang release commit} - {vlang version number}". # The sources of this V compiler commit need to be used here url "https://github.com/vlang/vc.git", revision: "31dd14b7927f154682437be1f2fbeed36c59ea2b" end def install resource("vc").stage do system ENV.cc, "-std=gnu11", "-w", "-o", buildpath/"v", "v.c", "-lm" end system "./v", "self" libexec.install "cmd", "thirdparty", "v", "v.mod", "vlib" bin.install_symlink libexec/"v" pkgshare.install "examples" end test do cp pkgshare/"examples/hello_world.v", testpath system bin/"v", "-o", "test", "hello_world.v" assert_equal "Hello, World!", shell_output("./test").chomp end end
DACH-NY/dazl-client
python/tests/unit/test_simple_client_api.py
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import logging from dazl import simple_client from .blocking_setup import blocking_setup from .dars import PostOffice def test_simple_client_api(sandbox): party = blocking_setup(sandbox, PostOffice) logging.info("Creating client...") with simple_client(url=sandbox, party=party) as client: client.ready() logging.info("Submitting...") client.create("Main:PostmanRole", {"postman": party}) logging.info("getting contracts") contracts = client.find_active("*") logging.info("got the contracts") assert 1 == len(contracts)
jalenng/icare-mini
src/preferences/tabs/Appearance.js
<reponame>jalenng/icare-mini /** * @file The "Appearance" tab in Preferences * @author jalenng */ /* eslint-disable no-undef */ import React from 'react' import { Stack, Text, Toggle, ChoiceGroup } from '@fluentui/react' import { StackProps } from '../../SharedProps' const themeOptions = [ { key: 'system', text: 'System default ', iconProps: { iconName: 'Personalize' } }, { key: 'light', text: 'Light', iconProps: { iconName: 'Sunny' } }, { key: 'dark', text: 'Dark', iconProps: { iconName: 'ClearNight' } } ] export default class extends React.Component { constructor (props) { super(props) this.state = store.preferences.getAll().appearance } componentDidMount () { // Update this component's state when preferences are updated store.preferences.eventSystem.on('changed', () => { this.updateState() }) } updateState () { this.setState(store.preferences.getAll().appearance) } render () { return ( <Stack id='appearance' {...StackProps.level1}> <Stack {...StackProps.level2}> <Text variant='xLarge' block> Appearance </Text> <ChoiceGroup label='Theme' styles={{ dropdown: { width: 300 } }} selectedKey={this.state.theme} options={themeOptions} onChange={(event, selection) => { store.preferences.set('appearance.theme', selection.key) }} /> <Toggle label='Show the main window above other windows' onText='On' offText='Off' checked={this.state.alwaysOnTop} onChange={(event, checked) => { store.preferences.set('appearance.alwaysOnTop', checked) }} /> </Stack> </Stack> ) } }
raceup/yolo
app/src/it/raceup/yolo/models/data/Parser.java
<reponame>raceup/yolo<filename>app/src/it/raceup/yolo/models/data/Parser.java package it.raceup.yolo.models.data; import it.raceup.yolo.error.ExceptionType; import it.raceup.yolo.error.YoloException; import it.raceup.yolo.utils.Misc; import java.util.ArrayList; import java.util.Arrays; public class Parser { private static final int index_diff_1[] = new int[]{ 0x283, 0x284, 0x287, 0x288 }; private static final int index_diff_2[] = new int[]{ 0x285, 0x286, 0x289, 0x28A }; private static final double TORQUE_CURRENT = 107.2 / 16384; private final int id; private final byte[] data; private final ArrayList<Raw> parsedData = new ArrayList<>(); private int motorId; public Parser(int id, byte[] data) { this.id = id; this.data = data; parse(); } public Parser(CanMessage message) { this(message.getId(), message.data); } private void parse() { motorId = parseMotorId(); try { parseValues(); } catch (Exception e) { new YoloException("cannot parse " + Arrays.toString(data), e, ExceptionType.KVASER).print(); } } private int parseMotorId() { for (int i = 0; i < 4; i++) { if (id == index_diff_1[i] || id == index_diff_2[i]) { return i; } } return 0; } public int getMotorId() { return motorId; } public void parseValues() { if (getValueType() == 1) { readMotor1(); } else { readMotor2(); } } private void readMotor1() { parsedData.add( new Raw( Misc.getBit(data[1], 0), getMotorId(), Type.SYSTEM_READY ) ); parsedData.add( new Raw( Misc.getBit(data[1], 1), getMotorId(), Type.ERROR ) ); parsedData.add( new Raw( Misc.getBit(data[1], 2), getMotorId(), Type.WARNING ) ); parsedData.add( new Raw( Misc.getBit(data[1], 3), getMotorId(), Type.QUIT_DC_ON ) ); parsedData.add( new Raw( Misc.getBit(data[1], 4), getMotorId(), Type.DC_ON ) ); parsedData.add( new Raw( Misc.getBit(data[1], 5), getMotorId(), Type.QUIT_INVERTER_ON ) ); parsedData.add( new Raw( Misc.getBit(data[1], 6), getMotorId(), Type.INVERTER_ON ) ); parsedData.add( new Raw( Misc.getBit(data[1], 7), getMotorId(), Type.DERATING ) ); parsedData.add( new Raw( data[2] | data[3] << 8, getMotorId(), Type.ACTUAL_VELOCITY ) ); parsedData.add( new Raw( (data[4] | data[5] << 8) * TORQUE_CURRENT, getMotorId(), Type.TORQUE_CURRENT ) ); parsedData.add( new Raw( data[6] | data[7] << 8, getMotorId(), Type.MAGNETIZING_CURRENT ) ); } private void readMotor2() { parsedData.add( new Raw( (data[0] | data[1] << 8) / 10, getMotorId(), Type.TEMPERATURE_MOTOR ) ); parsedData.add( new Raw( (data[2] | data[3] << 8) / 10, getMotorId(), Type.TEMPERATURE_INVERTER ) ); parsedData.add( new Raw( (data[4] | data[5] << 8) / 10, getMotorId(), Type.TEMPERATURE_IGBT ) ); parsedData.add( new Raw( data[6] | data[7] << 8, getMotorId(), Type.ERROR_INFO ) ); } public int getValueType() { for (int i = 0; i < 4; i++) { if (id == index_diff_1[i]) { return 1; } if (id == index_diff_2[i]) { return 2; } } return 0; } public Raw[] getParsedData() { return parsedData.toArray(new Raw[parsedData.size()]); } }
isonbpo/iSONHelpDesk
dist/out-tsc/src/app/sidebar/sidebar.component.js
<gh_stars>0 import * as tslib_1 from "tslib"; import { Component, ViewChild } from '@angular/core'; import { MatSidenav } from '@angular/material'; let SidebarComponent = class SidebarComponent { constructor() { this.isExpanded = true; this.showSubmenu = false; this.isShowing = false; this.showSubSubMenu = false; } mouseenter() { if (!this.isExpanded) { this.isShowing = true; } } mouseleave() { if (!this.isExpanded) { this.isShowing = false; } } ngOnInit() { } }; tslib_1.__decorate([ ViewChild('sidenav', { static: true }), tslib_1.__metadata("design:type", MatSidenav) ], SidebarComponent.prototype, "sidenav", void 0); SidebarComponent = tslib_1.__decorate([ Component({ selector: 'app-sidebar', templateUrl: './sidebar.component.html', styleUrls: ['./sidebar.component.scss'] }) ], SidebarComponent); export { SidebarComponent }; //# sourceMappingURL=sidebar.component.js.map
JackieMa000/problems
DSA/Cpp/test/dsa/lib/utils/algorithms/none_of_test.cpp
#include <list> #include <dsa/lib/libdef.h> #include <dsa/lib/utils/algorithm.hpp> #include <dsa/lib/utils/math.hpp> namespace dsa { namespace { TEST(NoneOfTest, case1) { int nums[] = {2, 4, 6, 8}; EXPECT_FALSE(dsa::none_of(nums, nums + arylen(nums), isEven)); EXPECT_TRUE(dsa::none_of(nums, nums, isEven)); } TEST(NoneOfTest, case2) { int nums[] = {2, 4, 5, 8}; EXPECT_FALSE(dsa::none_of(nums, nums + arylen(nums), isEven)); EXPECT_TRUE(dsa::none_of(nums, nums, isEven)); } TEST(NoneOfTest, statisAssert) { CONSTEXPR int ia[] = {1, 3, 6, 7}; CONSTEXPR int ib[] = {1, 3, 5, 7}; CONSTEXPR bool r1 = dsa::none_of(std::begin(ia), std::end(ia), isEven); CONSTEXPR bool r2 = dsa::none_of(std::begin(ib), std::end(ib), isEven); static_assert(!r1 && r2); } } }
Tom-TBT/QDSpy
QDSpy_stim_draw.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """ QDSpy module - routines to generate graphical objects as vertex lists This module is a graphics API independent. Copyright (c) 2013-2016 <NAME> All rights reserved. """ # --------------------------------------------------------------------- __author__ = "<EMAIL>" import numpy as np import QDSpy_stim as stm import QDSpy_stim_support as spp import Graphics.renderer_opengl as rdr # --------------------------------------------------------------------- def box2vert (_ob, _iob, _sc, _Stage, _stim, _nextiV): # Generate vertices for a box object from the description in _ob # (dx, dy) = _ob[stm.SO_field_size] (mx, my) = _sc[stm.SC_field_magXY][_iob] dx2 = dx *mx /2.0 dy2 = dy *my /2.0 rot_deg = _sc[stm.SC_field_rot][_iob] pxy = _sc[stm.SC_field_posXY][_iob] rect = [-dx2, -dy2, dx2, dy2] newVert = [rect[0], rect[1], rect[2], rect[1], rect[2], rect[3], rect[0], rect[3]] newVert = spp.rotateTranslate(newVert, rot_deg, pxy) newVert = spp.toInt(newVert) newiVTr = [_nextiV, _nextiV+1, _nextiV+2, _nextiV, _nextiV+2, _nextiV+3] if _ob[stm.SO_field_doRGBAByVert]: newRGBA = spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][0][0:4]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][1][0:4]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][2][0:4]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][3][0:4]) newRGBA2= spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][0][4:8]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][1][4:8]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][2][4:8]) +\ spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][3][4:8]) else: tmpRGBA = _ob[stm.SO_field_fgRGB][0:3] +(_ob[stm.SO_field_alpha],) newRGBA = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) tmpRGBA = _ob[stm.SO_field_fgRGB][3:6] +(_ob[stm.SO_field_alpha],) newRGBA2= len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) hList = [stm.StimObjType.box, dy,dy, mx,my, rot_deg, pxy] hStr = spp.getHashStr(hList.__str__()) return (newVert, newiVTr, newRGBA, newRGBA2, hStr, pxy, rot_deg) # --------------------------------------------------------------------- def ell2vert (_ob, _iob, _sc, _Stage, _stim, _nextiV): # Generate vertices for an ellipse object from the description in _ob # (dx, dy) = _ob[stm.SO_field_size] (mx, my) = _sc[stm.SC_field_magXY][_iob] rot_deg = _sc[stm.SC_field_rot][_iob] pxy = _sc[stm.SC_field_posXY][_iob] # Determine center and radii, then calculate number of triangles # and vertices # rx = dx *mx /2.0 ry = dy *my /2.0 rm = (rx+ry) /2.0 nTri = int(min(max(10, round(rm/1.5)), stm.Ellipse_maxTr)) nPnts = nTri +1 dAng = 2*np.pi/nTri # Center vertex, then points on perimeter # ang = 0 newVert = [0, 0] for i in range(1, nPnts): newVert.append(round(rx*np.sin(ang))) newVert.append(round(ry*np.cos(ang))) ang += dAng newVert = spp.rotateTranslate(newVert, rot_deg, pxy) newVert = spp.toInt(newVert) newiVTr = [] for i in range(nTri): newiVTr += [_nextiV, _nextiV+i+1, _nextiV+i+2] newiVTr[len(newiVTr)-1] = newiVTr[1] if _ob[stm.SO_field_doRGBAByVert]: # ************* # ************* # TODO: Currently uses only the first RGBA for the center and the # second RGBA for the circumfence. It would be better, if RGBA[1:] # were interpolated and arranged arround the circumfence ... # ************* # ************* RGBA0 = _ob[stm.SO_field_fgRGB][0][0:4] RGBA1 = _ob[stm.SO_field_fgRGB][1][0:4] newRGBA = spp.scaleRGB(_stim, RGBA0) tmpRGBA = (len(newVert)-1)//2 *spp.scaleRGB(_stim, RGBA1) newRGBA += tmpRGBA RGBA0 = _ob[stm.SO_field_fgRGB][0][4:8] RGBA1 = _ob[stm.SO_field_fgRGB][1][4:8] newRGBA2 = spp.scaleRGB(_stim, RGBA0) tmpRGBA = (len(newVert)-1)//2 *spp.scaleRGB(_stim, RGBA1) newRGBA2 += tmpRGBA else: tmpRGBA = _ob[stm.SO_field_fgRGB][0:3] +(_ob[stm.SO_field_alpha],) newRGBA = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) tmpRGBA = _ob[stm.SO_field_fgRGB][3:6] +(_ob[stm.SO_field_alpha],) newRGBA2 = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) hList = [stm.StimObjType.ellipse, dy,dy, mx,my, rot_deg, pxy] hStr = spp.getHashStr(hList.__str__()) return (newVert, newiVTr, newRGBA, newRGBA2, hStr, pxy, rot_deg) # --------------------------------------------------------------------- def sct2vert (_ob, _iob, _sc, _Stage, _stim, _nextiV): # Generate vertices for a sector object from the description in _ob # (r,offs,acenter,awidth,astep) = _ob[stm.SO_field_size] (mx, my) = _sc[stm.SC_field_magXY][_iob] rot_deg = _sc[stm.SC_field_rot][_iob] pxy = _sc[stm.SC_field_posXY][_iob] if astep == None: # If astep is not given, choose the best one # if awidth == 360: # It's a full circle # astep = stm.Sector_maxStep else: # Try to minimize the number of triangles needed while # preserving the precission # for astep in range(stm.Sector_maxStep, 0, -1): if (int(awidth) % astep) == 0: break nSteps = int(min(max(1, awidth/astep), stm.Sector_maxTr)) ''' spp.Log.write("DEBUG", "sct2vert: # steps={0}, angle={1}°, step angle={2}°" .format(nSteps, awidth, astep)) ''' acenter = -2*np.pi *acenter/360.0 +np.pi awidth = 2*np.pi *awidth/360.0 astep = 2*np.pi *astep/360.0 if offs > 0: # Is arc ... # nPnts = 2*nSteps +2 ang = acenter -awidth/2.0 i = 0 newVert = [] while i < (nPnts-1): newVert.append(r *np.sin(ang)) newVert.append(-r *np.cos(ang)) i += 1 newVert.append(offs *np.sin(ang)) newVert.append(-offs *np.cos(ang)) i += 1 ang += astep newiVTr = [] for i in range(nSteps*2): newiVTr += [_nextiV+i, _nextiV+i+1, _nextiV+i+2] if _ob[stm.SO_field_doRGBAByVert]: RGBAout = spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][0][0:4]) RGBAin = spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][1][0:4]) RGBAout2 = spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][0][4:8]) RGBAin2 = spp.scaleRGB(_stim, _ob[stm.SO_field_fgRGB][1][4:8]) newRGBA = [] newRGBA2 = [] for i in range(len(newVert)//4): newRGBA += RGBAout newRGBA += RGBAin newRGBA2 += RGBAout2 newRGBA2 += RGBAin2 else: tmpRGBA = _ob[stm.SO_field_fgRGB][0:3] +(_ob[stm.SO_field_alpha],) newRGBA = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) tmpRGBA = _ob[stm.SO_field_fgRGB][3:6] +(_ob[stm.SO_field_alpha],) newRGBA2 = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) else: # Is sector ... # nPnts = nSteps +2 ang = acenter -awidth/2.0 newVert = [0, 0] for i in range(1, nPnts): newVert.append(r *np.sin(ang)) newVert.append(-r *np.cos(ang)) ang += astep newiVTr = [] for i in range(nSteps +1): newiVTr += [_nextiV, _nextiV+i+1, _nextiV+i+2] #newiVTr[len(newiVTr)-1] = newiVTr[1] if _ob[stm.SO_field_doRGBAByVert]: RGBA0 = _ob[stm.SO_field_fgRGB][0][0:4] RGBA1 = _ob[stm.SO_field_fgRGB][1][0:4] newRGBA = spp.scaleRGB(_stim, RGBA0) tmpRGBA = (len(newVert)-1)//2 *spp.scaleRGB(_stim, RGBA1) newRGBA += tmpRGBA RGBA0 = _ob[stm.SO_field_fgRGB][0][4:8] RGBA1 = _ob[stm.SO_field_fgRGB][1][4:8] newRGBA = spp.scaleRGB(_stim, RGBA0) tmpRGBA = (len(newVert)-1)//2 *spp.scaleRGB(_stim, RGBA1) newRGBA2 += tmpRGBA else: tmpRGBA = _ob[stm.SO_field_fgRGB][0:3] +(_ob[stm.SO_field_alpha],) newRGBA = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) tmpRGBA = _ob[stm.SO_field_fgRGB][3:6] +(_ob[stm.SO_field_alpha],) newRGBA2 = len(newVert)//2 *spp.scaleRGB(_stim, tmpRGBA) newVert = spp.rotateTranslate(newVert, rot_deg, pxy) newVert = spp.toInt(newVert) hList = [stm.StimObjType.sector, r,offs,acenter,awidth,astep, mx,my, rot_deg, pxy] hStr = spp.getHashStr(hList.__str__()) return (newVert, newiVTr, newRGBA, newRGBA2, hStr, pxy, rot_deg) # --------------------------------------------------------------------- def marker2vert (_Stage, _Conf): # Generate vertices for the trigger marker # if _Stage.useScrOvl: dx2 = _Stage.dxScr12 /_Conf.markScrWidthFract/4 pxy = (_Stage.dxScr12//4, -_Stage.dyScr12//2) else: dx2 = _Stage.dxScr /_Conf.markScrWidthFract/2 pxy = (_Stage.dxScr//2-dx2, -_Stage.dyScr//2+dx2) ''' return rdr.vertFromRect([-dx2, -dx2, dx2, dx2], pxy, _Conf.markRGBA) ''' return rdr.vertFromRect([-dx2, -dx2, dx2, dx2], pxy, _Conf.markRGBA),\ rdr.vertFromRect([-dx2, -dx2, dx2, dx2], pxy, _Conf.antiMarkRGBA) # ---------------------------------------------------------------------
mayronceccon/work-at-olist-library
utils/file_read.py
<gh_stars>0 import csv import contextlib class FileRead: def __init__(self, file): self.__data = [] self.__file = file def execute(self): self.__open_file(self.__file) def get_data(self): return self.__data def __open_file(self, file_import): with open(file_import, newline="") as csvfile: self.__read_file(csvfile) def __read_file(self, csvfile): reader = csv.reader(csvfile, delimiter=";", quotechar='"') self.__list_register(reader) def __list_register(self, reader): keys = [] for (key, row) in enumerate(reader): if self.__first_line(key): keys = row continue self.__set_data(keys, row) def __first_line(self, key): if key == 0: return True return False def __set_data(self, keys, row): with contextlib.suppress(IndexError): data = zip(keys, row) self.__data.append(dict(data))
7dudtj/BOJ_myCode
DFS/16946_벽 부수고 이동하기 4/16946_벽 부수고 이동하기 4.java
<reponame>7dudtj/BOJ_myCode import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.Arrays; public class Main { // set static variables static int N, M; static int[][] map; static boolean[][] wall; static boolean[][] visited; static int[] dx = {0, 1, 0, -1}; static int[] dy = {-1, 0, 1, 0}; static int[] group; static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException{ // set needed components BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine(), " "); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); map = new int[N][M]; wall = new boolean[N][M]; visited = new boolean[N][M]; // get wall for (int i = 0; i < N; i++){ String s = br.readLine(); for (int j = 0; j < M; j++){ if (s.substring(j,j+1).equals("1")){ wall[i][j] = true; } } } // find "0" group int groupIdx = 1; for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ if (!wall[i][j] && !visited[i][j]){ dfs(i, j, groupIdx); groupIdx++; } } } // get group data group = new int[groupIdx]; for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ group[map[i][j]]++; } } // get answer for (int i = 0; i < N; i++){ for (int j = 0; j < M; j++){ if (!wall[i][j]) { sb.append("0"); } else{ int ans = count(i, j); sb.append((ans+1)%10); } } sb.append('\n'); } // print answer and end program System.out.print(sb); br.close(); return; } // dfs function private static void dfs(int i, int j, int groupIdx){ map[i][j] = groupIdx; visited[i][j] = true; for (int k = 0; k < 4; k++){ int ni = i + dx[k]; int nj = j + dy[k]; if (ni < 0 || nj < 0 || ni >= N || nj >= M) continue; if (!wall[ni][nj] && !visited[ni][nj]){ dfs(ni, nj, groupIdx); } } } // count function private static int count(int i, int j){ int[] list = new int[4]; int result = 0; for (int k = 0; k < 4; k++){ int ni = i + dx[k]; int nj = j + dy[k]; if (ni < 0 || nj < 0 || ni >= N || nj >= M) continue; list[k] = map[ni][nj]; } Arrays.sort(list); int prev = 0; for (int k = 0; k < 4; k++){ if (prev == list[k]) continue; if (list[k] != 0){ result += group[list[k]]; prev = list[k]; } } return result; } }
JuhoL/ASch
Utils/include/Utils_Types.hpp
<filename>Utils/include/Utils_Types.hpp //----------------------------------------------------------------------------------------------------------------------------- // Copyright (c) 2018 <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. //----------------------------------------------------------------------------------------------------------------------------- //! @file Utils_Types.hpp //! @author <NAME> <juho.lepisto(a)gmail.com> //! @date 12 May 2019 //! //! @brief Type definitions with some custom defines for unit testing purposes. #ifndef UTILS_TYPES_HPP_ #define UTILS_TYPES_HPP_ //----------------------------------------------------------------------------------------------------------------------------- // 1. Include Dependencies //----------------------------------------------------------------------------------------------------------------------------- #include <cstdint> //----------------------------------------------------------------------------------------------------------------------------- // 2. Typedefs, Structs, Enums and Constants //----------------------------------------------------------------------------------------------------------------------------- #if (UNIT_TEST == 1) #define static_mf static //!< When unit testing static_mf functions convert into virtual functions to enable mocking. #else #define static_mf static //!< In target build static_mf functions convert into static functions. #endif //----------------------------------------------------------------------------------------------------------------------------- // 3. Inline Functions //----------------------------------------------------------------------------------------------------------------------------- inline void Nop(void) { (void)0; } //----------------------------------------------------------------------------------------------------------------------------- // 4. Global Function Prototypes //----------------------------------------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------- // 5. Class Declaration //----------------------------------------------------------------------------------------------------------------------------- #endif // UTILS_TYPES_HPP_
phatblat/macOSPrivateFrameworks
PrivateFrameworks/PhotoLibraryServices/PLSimpleDCIMDirectory.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" @class NSFileManager, NSMutableIndexSet, NSObject<OS_dispatch_queue>, NSString, NSURL; @interface PLSimpleDCIMDirectory : NSObject { NSURL *_baseURL; NSString *_subDirSuffix; unsigned long long _directoryLimit; NSFileManager *_fileManager; NSMutableIndexSet *_availableFileNameNumbers; NSURL *_currentSubDirectory; unsigned long long _currentSubDirectoryNumber; NSString *_userInfoPath; BOOL _hasLoadedUserInfo; BOOL _representsCameraRoll; NSObject<OS_dispatch_queue> *_isolation; } + (id)cloudPlistName; + (id)cameraRollPlistName; + (id)migrateOldPlistToNewPlist:(id)arg1; @property(readonly) NSURL *directoryURL; // @synthesize directoryURL=_baseURL; @property BOOL representsCameraRoll; // @synthesize representsCameraRoll=_representsCameraRoll; - (void).cxx_destruct; - (void)reset; - (id)nextAvailableFileURLWithExtension:(id)arg1; - (id)init; - (id)initWithDirectoryURL:(id)arg1 subDirectorySuffix:(id)arg2 perDirectoryLimit:(unsigned long long)arg3 userInfoPath:(id)arg4; - (BOOL)_ensureDirectoryExists:(id)arg1; - (void)_loadUserInfoLastDirectoryNumber:(id *)arg1 lastFileNumber:(id *)arg2; - (void)_saveUserInfo; - (struct _NSRange)fileNameNumberRangeForDirNumber:(unsigned long long)arg1; - (id)availableFileNameNumbersInDirNumber:(unsigned long long)arg1; - (id)subDirURLForNumber:(unsigned long long)arg1 create:(BOOL)arg2 didCreate:(char *)arg3; @property(readonly, retain, nonatomic) NSURL *currentSubDirectory; @end
mauvealerts/Spelunky2X64DbgPlugin
include/QtHelpers/TreeViewMemoryFields.h
<filename>include/QtHelpers/TreeViewMemoryFields.h #pragma once #include "Data/EntityDB.h" #include "Data/MemoryMappedData.h" #include "QtHelpers/StyledItemDelegateHTML.h" #include "Spelunky2.h" #include "Views/ViewToolbar.h" #include <QDragEnterEvent> #include <QDropEvent> #include <QStandardItem> #include <QTreeView> #include <array> #include <memory> #include <unordered_map> namespace S2Plugin { class TreeViewMemoryFields : public QTreeView { Q_OBJECT public: TreeViewMemoryFields(ViewToolbar* toolbar, MemoryMappedData* mmd, QWidget* parent = nullptr); void setMemoryMappedData(MemoryMappedData* mmd); QStandardItem* addMemoryField(const MemoryField& field, const std::string& fieldNameOverride, QStandardItem* parent = nullptr); void clear(); void updateTableHeader(bool restoreColumnWidths = true); void setEnableChangeHighlighting(bool b) noexcept; void expandItem(QStandardItem* item); QStandardItem* lookupTreeViewItem(const std::string& fieldName, uint8_t column, QStandardItem* parent); void updateValueForField(const MemoryField& field, const std::string& fieldNameOverride, std::unordered_map<std::string, size_t>& offsets, size_t memoryOffsetDeltaReference = 0, QStandardItem* parent = nullptr, bool disableChangeHighlightingForField = false); protected: void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; void dropEvent(QDropEvent* event) override; void startDrag(Qt::DropActions supportedActions) override; signals: void memoryFieldValueUpdated(const QString& fieldName); void levelGenRoomsPointerClicked(const QString& fieldName); void entityOffsetDropped(size_t offset); private slots: void cellClicked(const QModelIndex& index); void cellCollapsed(const QModelIndex& index); private: ViewToolbar* mToolbar; MemoryMappedData* mMemoryMappedData; QStandardItemModel* mModel; std::unique_ptr<StyledItemDelegateHTML> mHTMLDelegate; std::array<uint32_t, 6> mSavedColumnWidths = {0}; bool mEnableChangeHighlighting = true; }; } // namespace S2Plugin
kkoskelin/ef-cms
shared/src/proxies/trialSessions/getTrialSessionDetailsProxy.js
const { get } = require('../requests'); /** * getTrialSessionDetailsInteractor * * @param {object} providers the providers object * @param {object} providers.applicationContext the application context * @param {string} providers.trialSessionId the id of the trial session to get the details * @returns {Promise<*>} the promise of the api call */ exports.getTrialSessionDetailsInteractor = ({ applicationContext, trialSessionId, }) => { return get({ applicationContext, endpoint: `/trial-sessions/${trialSessionId}`, }); };
sailzeng/zcelib
src/commlib/zcelib/zce_lock_process_mutex.cpp
<filename>src/commlib/zcelib/zce_lock_process_mutex.cpp #include "zce_predefine.h" #include "zce_os_adapt_mutex.h" #include "zce_os_adapt_time.h" #include "zce_os_adapt_rwlock.h" #include "zce_os_adapt_semaphore.h" #include "zce_os_adapt_error.h" #include "zce_log_logging.h" #include "zce_time_value.h" #include "zce_lock_process_mutex.h" //构造函数, //mutex_name 互斥量的名称,必选参数,在WIN下是互斥量的名称,在LINUX,是共享内存的文件名称, //(如果是WIN下的非递归锁,是个信号灯的名称) //WINDOWS的核心对象的名称被用于标识一个核心对象(互斥量,信号灯),而LINUX下的pthread_xxx同步对象,如果对象在共享内存里面, //那么就是进程间同步对象,当然还要注意属性PTHREAD_PROCESS_SHARED的设置 ZCE_Process_Mutex::ZCE_Process_Mutex (const char *mutex_name, bool recursive): lock_(NULL) { ZCE_ASSERT( mutex_name); int ret = 0; #if defined ZCE_OS_WINDOWS //第一次发现Windows 下居然还简单一点 lock_ = new pthread_mutex_t(); #elif defined ZCE_OS_LINUX // ret = posix_sharemem_.open(mutex_name, sizeof(pthread_mutex_t), false); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "ZCE_ShareMem_Posix::open", ret); return; } lock_ = reinterpret_cast<pthread_mutex_t *>( posix_sharemem_.addr()); #endif ret = zce::pthread_mutex_initex(lock_, true, recursive, true, mutex_name); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "zce::pthread_mutex_initex", ret); return; } } //析构函数, ZCE_Process_Mutex::~ZCE_Process_Mutex (void) { int ret = 0; ret = zce::pthread_mutex_destroy (lock_); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "zce::pthread_mutex_destroy", ret); return; } #if defined ZCE_OS_WINDOWS if (lock_) { delete lock_; lock_ = NULL; } #elif defined ZCE_OS_LINUX posix_sharemem_.close(); posix_sharemem_.remove(); lock_ = NULL; #endif } //锁定 void ZCE_Process_Mutex::lock() { int ret = 0; ret = zce::pthread_mutex_lock(lock_); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "zce::pthread_mutex_lock", ret); return; } } //尝试锁定 bool ZCE_Process_Mutex::try_lock() { int ret = 0; ret = zce::pthread_mutex_trylock(lock_); if (0 != ret) { return false; } return true; } //解锁, void ZCE_Process_Mutex::unlock() { int ret = 0; ret = zce::pthread_mutex_unlock(lock_); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "zce::pthread_mutex_unlock", ret); return; } } //绝对时间 bool ZCE_Process_Mutex::systime_lock(const ZCE_Time_Value &abs_time) { int ret = 0; ret = zce::pthread_mutex_timedlock(lock_, abs_time); if (0 != ret) { ZCE_TRACE_FAIL_RETURN(RS_ERROR, "zce::pthread_mutex_timedlock", ret); return false; } return true; } //相对时间 bool ZCE_Process_Mutex::duration_lock(const ZCE_Time_Value &relative_time) { timeval abs_time = zce::gettimeofday(); abs_time = zce::timeval_add(abs_time, relative_time); return systime_lock(abs_time); } //取出内部的锁的指针 pthread_mutex_t *ZCE_Process_Mutex::get_lock() { return lock_; }
matheus-stabile/orange-talents-02-template-ecommerce
ecommerce/src/main/java/br/com/zup/ecommerce/shared/services/MailerService.java
package br.com.zup.ecommerce.shared.services; public interface MailerService { void send(EmailMessage message); }
kostmetallist/prom-extended
src-Models/org/processmining/models/graphbased/directed/analysis/ShortestPathFactory.java
/** * */ package org.processmining.models.graphbased.directed.analysis; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.processmining.models.graphbased.directed.DirectedGraph; import org.processmining.models.graphbased.directed.DirectedGraphEdge; import org.processmining.models.graphbased.directed.DirectedGraphNode; /** * This class generate a shortest path from one node in a directed graph to * another. * * @author arya * @email <EMAIL> * @version Dec 12, 2008 */ public class ShortestPathFactory { public static int UNLIMITEDMAX = Integer.MAX_VALUE; private ShortestPathFactory() { } /** * Calculate shortest distance from a node to every other node in the graph. * Algorithm in use is Dijkstra's algorithm written in Introduction to * Algorithm, chapter 25. * * @param source * @param graph * @return */ private static <N extends DirectedGraphNode, E extends DirectedGraphEdge<? extends N, ? extends N>> int[][] calculateShortestDistanceDijkstra( N source, DirectedGraph<N, E> graph, ShortestPathInfo<N, E> shortestPathInfo) { // start of Dijkstra's algorithm Set<N> S = new HashSet<N>(); // to store set of vertices whose final shortest-path weights from the source have already been determined Set<N> Q = new HashSet<N>(); // to store queue that contains all the vertices in V - S, V is total vertices in graph int[] d = new int[graph.getNodes().size()]; // to store shortest-path estimate Arrays.fill(d, ShortestPathFactory.UNLIMITEDMAX); int[] phi = new int[d.length]; Arrays.fill(phi, -1); // -1 means that no node is before this node in a shortest path // initialize single source, as well as complete all mapping for (N node : graph.getNodes()) { Q.add(node); } // init source node d[shortestPathInfo.getIndexOf(source)] = 0; // start loop while (!Q.isEmpty()) { N currentNode = extractMin(d, Q, shortestPathInfo); if (currentNode == null) { break; } else { S.add(currentNode); Q.remove(currentNode); // update each vertex connected to indexMin int currentNodeIndex = shortestPathInfo.getIndexOf(currentNode); Collection<E> edges = graph.getOutEdges(currentNode); for (E edge : edges) { // do RELAX. Please notice that the weight of an arc is always 1 in our case if (d[shortestPathInfo.getIndexOf(edge.getTarget())] > (d[currentNodeIndex] + 1)) { d[shortestPathInfo.getIndexOf(edge.getTarget())] = d[currentNodeIndex] + 1; phi[shortestPathInfo.getIndexOf(edge.getTarget())] = currentNodeIndex; } } } } // result consist of 2 array : 1st array for shortestpath distance, 2nd array for nodes listing int[][] result = new int[2][]; result[0] = d; result[1] = phi; return result; } private static <N extends DirectedGraphNode, E extends DirectedGraphEdge<? extends N, ? extends N>> N extractMin( int[] d, Set<N> q, ShortestPathInfo<N, E> shortestPathInfo) { int minValue = ShortestPathFactory.UNLIMITEDMAX; N resultNode = null; // find the minimum value for (N node : q) { int currentNodeIndex = shortestPathInfo.getIndexOf(node); if ((d[currentNodeIndex] <= minValue) && (d[currentNodeIndex] != ShortestPathFactory.UNLIMITEDMAX)) { minValue = d[currentNodeIndex]; resultNode = node; } } return resultNode; } public static <N extends DirectedGraphNode, E extends DirectedGraphEdge<? extends N, ? extends N>> ShortestPathInfo<N, E> calculateAllShortestDistanceDijkstra( DirectedGraph<N, E> graph) { // create shortest path info ShortestPathInfo<N, E> shortestPathInfo = new ShortestPathInfo<N, E>(graph); // insert distances to shortest path info for (N node : graph.getNodes()) { int[][] temp = calculateShortestDistanceDijkstra(node, graph, shortestPathInfo); int currentNodeIndex = shortestPathInfo.getIndexOf(node); for (int i = 0; i < temp[0].length; i++) { if (temp[0][i] != ShortestPathFactory.UNLIMITEDMAX) { shortestPathInfo.setShortestPathLength(currentNodeIndex, i, temp[0][i]); shortestPathInfo.setLastOnShortestPath(currentNodeIndex, i, temp[1][i]); } } shortestPathInfo.setShortestPathLength(currentNodeIndex, currentNodeIndex, 0); // set distance to itself with zero } return shortestPathInfo; } }
Arvenwood/Bending
bending-api/src/main/java/pw/dotdash/bending/api/temp/TempBlock.java
<filename>bending-api/src/main/java/pw/dotdash/bending/api/temp/TempBlock.java package pw.dotdash.bending.api.temp; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.util.ResettableBuilder; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import java.time.Instant; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** * A block that exists for a short time before being reverted back to its * original state. * * @see TempBlockService */ public interface TempBlock { /** * Creates a new {@link Builder} to build a {@link TempBlock}. * * @return The builder */ static Builder builder() { return Sponge.getRegistry().createBuilder(Builder.class); } /** * Gets the location where the block is changed. * * @return The location */ Location<World> getLocation(); /** * Gets the block state that the block is reverted back to. * * @return The old block state */ BlockState getOldState(); /** * Gets the block state that the block is temporarily set to. * * @return The new block state */ BlockState getNewState(); /** * Gets the {@link Instant} of when the block will be reverted. * * @return The reversion epoch time */ Instant getRevertTime(); /** * Gets the epoch time of when the block will be reverted. * * @return The reversion epoch time */ long getRevertTimeMilli(); /** * Checks if the block has been reverted to its previous state. * * @return True if the block has been reverted */ boolean isReverted(); /** * Reverts the block to its previous state. * * @return True if the operation was successful */ boolean revert(); /** * Represents a builder to create a {@link TempBlock}. */ interface Builder extends ResettableBuilder<TempBlock, Builder> { /** * Sets the location used for saving and reverting. * * @param location The location * @return This builder, for chaining */ Builder location(Location<World> location); /** * Sets the block state that the location is temporarily set to. * * @param newState The new block state * @return This builder, for chaining */ Builder newState(BlockState newState); /** * Sets the block type that the location is temporarily set to. * * @param newType The new block type * @return This builder, for chaining * @see #newState(BlockState) */ default Builder newState(BlockType newType) { return newState(BlockState.builder().blockType(newType).build()); } /** * Sets the delay of how long until the block is reverted. * * @param duration The duration * @param unit The unit of duration * @return This builder, for chaining */ Builder revertDelay(long duration, TimeUnit unit); /** * Sets the callback that's ran when the block is reverted. * * @param onRevert The callback * @return This builder, for chaining */ Builder onRevert(Consumer<TempBlock> onRevert); /** * Builds a new {@link TempBlock}, provided that the * {@link #location(Location)} and {@link #newState(BlockState)} are * set. * * @return The generated temporary block * @see TempBlockService#register(TempBlock) */ TempBlock build(); @Override Builder from(TempBlock value) throws UnsupportedOperationException; } }
Strabox/vehicle-manager
src/test/java/com/pt/pires/service/integration/VehicleIntegratorServiceTest.java
package com.pt.pires.service.integration; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import javax.inject.Inject; import javax.inject.Named; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.core.io.ClassPathResource; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import com.pt.pires.VehicleManagerApplication; import com.pt.pires.domain.VehicleLicensed; import com.pt.pires.domain.VehicleUnlicensed; import com.pt.pires.domain.exceptions.ImpossibleSaveFileException; import com.pt.pires.domain.exceptions.VehicleManagerException; import com.pt.pires.service.VehicleManagerServiceTest; import com.pt.pires.services.external.IFileService; import com.pt.pires.services.integrator.IVehicleIntegratorService; import com.pt.pires.services.integrator.VehicleIntegratorService; import com.pt.pires.services.local.IVehicleService; import org.mockito.MockitoAnnotations; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = VehicleManagerApplication.class) @Transactional @Rollback public class VehicleIntegratorServiceTest extends VehicleManagerServiceTest { private static final String VEHICLE_EXISTING_NAME = "Calhambeco do noddy"; private static final String VEHICLE_DOESNT_EXIST_NAME = "Calhambeco do pussas"; private static final String IMAGE_PNG_TEST_RESOURCE_PATH = "/ImagePNG.png"; private static byte[] imagePNG = null; private static final String PDF_TEST_RESOURCE_PATH = "/filePDF.pdf"; private static byte[] filePDF = null; private IVehicleIntegratorService vehicleIntegratorService; @Inject @Named("vehicleService") private IVehicleService locaVehicleService; @Mock private IFileService fileService; @BeforeClass public static void populateFiles() { try { imagePNG = Files.readAllBytes( Paths.get(new ClassPathResource(IMAGE_PNG_TEST_RESOURCE_PATH).getFile().getAbsolutePath())); filePDF = Files.readAllBytes( Paths.get(new ClassPathResource(PDF_TEST_RESOURCE_PATH).getFile().getAbsolutePath())); } catch (IOException e) { System.err.println("[ERROR: Error reading test resource files]"); e.printStackTrace(); } } @Override @Before public void populate() throws VehicleManagerException { MockitoAnnotations.initMocks(this); //IMPORTANT: Setup Mockito annotations because !!! vehicleIntegratorService = new VehicleIntegratorService(locaVehicleService, fileService); newUnlicensedVehicle(VEHICLE_EXISTING_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE,VALID_FABRICATION_YEAR); } /* ================== CreateUnlicensedVehicle Integrator Service ==================== */ @Test public void createUnlicensedVehicleWithValidImage() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, true, imagePNG); VehicleUnlicensed v = obtainUnlicensedVehicle(VALID_VEHICLE_NAME); Mockito.verify(fileService,Mockito.times(1)).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, imagePNG); Assert.assertTrue(v.getName().equals(VALID_VEHICLE_NAME)); Assert.assertTrue(v.getBrand().equals(VALID_VEHICLE_BRAND)); } @Test public void createUnlicensedVehicleWithInvalidImage() throws VehicleManagerException { Mockito.doThrow(new ImpossibleSaveFileException()).when(fileService).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, filePDF); try { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, true, filePDF); } catch(ImpossibleSaveFileException e) { Assert.assertNull(obtainUnlicensedVehicle(VALID_VEHICLE_NAME)); } Mockito.verify(fileService,Mockito.times(1)).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, filePDF); } @Test public void createUnlicensedVehicleWithNoImage() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, false, null); Mockito.verify(fileService,Mockito.never()).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createUnlicensedVehicleNullVehicleName() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(null, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createUnlicensedVehicleNullBrand() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, null, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createUnlicensedVehicleNullDate() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, null, VALID_FABRICATION_YEAR, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createUnlicensedVehicleNullImage() throws VehicleManagerException { vehicleIntegratorService.createUnlicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_FABRICATION_YEAR, true, null); } /* ============= CreateLicensedVehicle Integrator Service ========================== */ @Test public void createLicensedVehicleWithValidImage() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, true, imagePNG); VehicleLicensed v = obtainLicensedVehicle(VALID_VEHICLE_NAME); Mockito.verify(fileService,Mockito.times(1)).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, imagePNG); Assert.assertTrue(v.getName().equals(VALID_VEHICLE_NAME)); Assert.assertTrue(v.getBrand().equals(VALID_VEHICLE_BRAND)); Assert.assertTrue(v.getLicense().getLicense().equals(VALID_LICENSE)); } @Test public void createLicensedVehicleWithInvalidImage() throws VehicleManagerException { Mockito.doThrow(new ImpossibleSaveFileException()).when(fileService).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, filePDF); try { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, true, filePDF); } catch(ImpossibleSaveFileException e) { Assert.assertNull(obtainLicensedVehicle(VALID_VEHICLE_NAME)); } Mockito.verify(fileService,Mockito.times(1)).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, filePDF); } @Test public void createLicensedVehicleWithNoImage() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, false, null); Mockito.verify(fileService,Mockito.never()).addOrReplaceVehiclePortraitImage(VALID_VEHICLE_NAME, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullVehicleName() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(null, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullBrand() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, null, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, false, null); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullAcquisitonDate() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, null, VALID_LICENSE, VALID_CURRENT_DATE, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullLicenseDate() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, null, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullLicense() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, null, VALID_CURRENT_DATE, true, imagePNG); } @Test(expected = IllegalArgumentException.class) public void createLicensedVehicleNullImage() throws VehicleManagerException { vehicleIntegratorService.createLicensedVehicle(VALID_VEHICLE_NAME, VALID_VEHICLE_BRAND, VALID_CURRENT_DATE, VALID_LICENSE, VALID_CURRENT_DATE, true, null); } /* =========================== RemoveVehicle Integrator Service ====================== */ @Test public void removeVehicleExisting() throws VehicleManagerException{ vehicleIntegratorService.removeVehicle(VEHICLE_EXISTING_NAME); Mockito.verify(fileService,Mockito.times(1)).removeVehicleFiles(VEHICLE_EXISTING_NAME); } @Test public void removeVehicleDoesntExist() throws VehicleManagerException{ vehicleIntegratorService.removeVehicle(VEHICLE_DOESNT_EXIST_NAME); Mockito.verify(fileService,Mockito.times(1)).removeVehicleFiles(VEHICLE_DOESNT_EXIST_NAME); } @Test(expected = IllegalArgumentException.class) public void removeVehicleNullVehicleName() throws VehicleManagerException{ vehicleIntegratorService.removeVehicle(null); } /* =================== AddOrUpdatePortraitImage Integrator Service ====================== */ @Test public void addOrUpdatePortraitImage() throws VehicleManagerException{ vehicleIntegratorService.addOrUpdateVehiclePortrait(VEHICLE_EXISTING_NAME, imagePNG); Mockito.verify(fileService,Mockito.times(1)).addOrReplaceVehiclePortraitImage(VEHICLE_EXISTING_NAME, imagePNG); } @Test(expected = IllegalArgumentException.class) public void addOrUpdatePortraitImageNullVehicleName() throws VehicleManagerException{ vehicleIntegratorService.addOrUpdateVehiclePortrait(null, imagePNG); Mockito.verify(fileService,Mockito.times(0)).addOrReplaceVehiclePortraitImage(null, imagePNG); } @Test(expected = IllegalArgumentException.class) public void addOrUpdatePortraitImageNullImage() throws VehicleManagerException{ vehicleIntegratorService.addOrUpdateVehiclePortrait(VEHICLE_EXISTING_NAME, null); Mockito.verify(fileService,Mockito.times(0)).addOrReplaceVehiclePortraitImage(VEHICLE_EXISTING_NAME, null); } /* =================== GetVehiclePortraitImage Integrator Service ====================== */ @Test public void getVehicleIntegratorService() throws VehicleManagerException{ vehicleIntegratorService.getVehiclePortraitImage(VEHICLE_EXISTING_NAME); Mockito.verify(fileService,Mockito.times(1)).getVehiclePortraitImage(VEHICLE_EXISTING_NAME); } @Test(expected = IllegalArgumentException.class) public void getVehicleIntegratorServiceNullVehicleName() throws VehicleManagerException{ vehicleIntegratorService.getVehiclePortraitImage(null); Mockito.verify(fileService,Mockito.times(0)).getVehiclePortraitImage(VEHICLE_EXISTING_NAME); } }
EffieChantzi/UCSC-Genome-Browser
kent/src/hg/cirm/cdw/lib/cdwTagStorm.c
/* cdwTagStorm - create a tag storm out of database contents. */ #include "common.h" #include "hash.h" #include "dystring.h" #include "cheapcgi.h" #include "jksql.h" #include "tagStorm.h" #include "intValTree.h" #include "cdw.h" #include "cdwLib.h" static void addPairedEndTags(struct tagStorm *tagStorm, struct tagStanza *stanza, struct cdwQaPairedEndFastq *pair, char *mateAccession) /* Add tags from pair to stanza, also add mateAccession */ { if (mateAccession != NULL) tagStanzaAdd(tagStorm, stanza, "paired_end_mate", mateAccession); tagStanzaAddDouble(tagStorm, stanza, "paired_end_concordance", pair->concordance); tagStanzaAddDouble(tagStorm, stanza, "paired_end_distance_mean", pair->distanceMean); tagStanzaAddDouble(tagStorm, stanza, "paired_end_distance_min", pair->distanceMin); tagStanzaAddDouble(tagStorm, stanza, "paired_end_distance_max", pair->distanceMax); tagStanzaAddDouble(tagStorm, stanza, "paired_end_distance_std", pair->distanceStd); } void addRepeatInfo(struct sqlConnection *conn, struct tagStorm *tagStorm, struct rbTree *fileTree, char *repeatClass, char *label) /* Add info for given repeat class to tag storm. */ { char query[256]; sqlSafef(query, sizeof(query), "select * from cdwQaRepeat where repeatClass='%s'", repeatClass); struct sqlResult *sr = sqlGetResult(conn, query); char **row; while ((row = sqlNextRow(sr)) != NULL) { struct cdwQaRepeat rep; cdwQaRepeatStaticLoad(row, &rep); struct tagStanza *stanza = intValTreeFind(fileTree, rep.fileId); if (stanza != NULL) { char tagName[128]; safef(tagName, sizeof(tagName), "map_to_%s", label); tagStanzaAddDouble(tagStorm, stanza, tagName, rep.mapRatio); } } sqlFreeResult(&sr); } void addContamInfo(struct sqlConnection *conn, struct tagStorm *tagStorm, struct rbTree *fileTree, int taxon, char *label) /* Add info for given contamination mapping to tag storm. */ { char query[256]; sqlSafef(query, sizeof(query), "select cdwQaContam.* from cdwQaContam,cdwQaContamTarget,cdwAssembly " "where cdwQaContam.qaContamTargetId = cdwQaContamTarget.id " "and cdwQaContamTarget.assemblyId = cdwAssembly.id " "and taxon=%d", taxon); struct sqlResult *sr = sqlGetResult(conn, query); char **row; while ((row = sqlNextRow(sr)) != NULL) { struct cdwQaContam item; cdwQaContamStaticLoad(row, &item); struct tagStanza *stanza = intValTreeFind(fileTree, item.fileId); if (stanza != NULL) { char tagName[128]; safef(tagName, sizeof(tagName), "map_to_%s", label); tagStanzaAddDouble(tagStorm, stanza, tagName, item.mapRatio); } } sqlFreeResult(&sr); } static void addReadSizeInfo(struct tagStorm *tagStorm, struct tagStanza *stanza, double readSizeMin, double readSizeMax, double readSizeMean, double readSizeStd) /* Store read size info in stanza */ { if (readSizeMin == readSizeMax) tagStanzaAddLongLong(tagStorm, stanza, "read_size", readSizeMin); else { tagStanzaAddDouble(tagStorm, stanza, "read_size_mean", readSizeMean); tagStanzaAddDouble(tagStorm, stanza, "read_size_min", readSizeMin); tagStanzaAddDouble(tagStorm, stanza, "read_size_max", readSizeMax); tagStanzaAddDouble(tagStorm, stanza, "read_size_std", readSizeStd); } } struct tagStorm *cdwTagStormRestricted(struct sqlConnection *conn, struct rbTree *restrictTo) /* Load cdwMetaTags.tags, cdwFile.tags, and select other fields into a tag * storm for searching */ { /* Build up a cache of cdwSubmitDir */ char query[512]; sqlSafef(query, sizeof(query), "select * from cdwSubmitDir"); struct cdwSubmitDir *dir, *dirList = cdwSubmitDirLoadByQuery(conn, query); struct rbTree *submitDirTree = intValTreeNew(); for (dir = dirList; dir != NULL; dir = dir->next) intValTreeAdd(submitDirTree, dir->id, dir); verbose(2, "cdwTagStorm: %d items in submitDirTree\n", submitDirTree->n); /* First pass through the cdwMetaTags table. Make up a high level stanza for each * row, and save a reference to it in metaTree. */ struct tagStorm *tagStorm = tagStormNew("constructed from cdwMetaTags and cdwFile"); struct rbTree *metaTree = intValTreeNew(); sqlSafef(query, sizeof(query), "select id,tags from cdwMetaTags"); struct sqlResult *sr = sqlGetResult(conn, query); char **row; while ((row = sqlNextRow(sr)) != NULL) { unsigned id = sqlUnsigned(row[0]); char *cgiVars = row[1]; struct tagStanza *stanza = tagStanzaNew(tagStorm, NULL); char *var, *val; while (cgiParseNext(&cgiVars, &var, &val)) { tagStanzaAdd(tagStorm, stanza, var, val); } intValTreeAdd(metaTree, id, stanza); } sqlFreeResult(&sr); verbose(2, "cdwTagStorm: %d items in metaTree\n", metaTree->n); /* Now go through the cdwFile table, adding its files as substanzas to * meta cdwMetaTags stanzas. */ sqlSafef(query, sizeof(query), "select cdwFile.*,cdwValidFile.* from cdwFile,cdwValidFile " "where cdwFile.id=cdwValidFile.fileId " "and (errorMessage='' or errorMessage is null)" ); sr = sqlGetResult(conn, query); struct rbTree *fileTree = intValTreeNew(); while ((row = sqlNextRow(sr)) != NULL) { struct cdwFile cf; struct cdwValidFile vf; cdwFileStaticLoad(row, &cf); cdwValidFileStaticLoad(row + CDWFILE_NUM_COLS, &vf); if (restrictTo != NULL && intValTreeFind(restrictTo, cf.id) == NULL) continue; /* Figure out file name independent of cdw location */ char name[FILENAME_LEN], extension[FILEEXT_LEN]; splitPath(cf.cdwFileName, NULL, name, extension); char fileName[PATH_LEN]; safef(fileName, sizeof(fileName), "%s%s", name, extension); struct tagStanza *metaStanza = intValTreeFind(metaTree, cf.metaTagsId); struct tagStanza *stanza = tagStanzaNew(tagStorm, metaStanza); intValTreeAdd(fileTree, cf.id, stanza); /** Add stuff we want in addition to what is in cf.tags */ /* Deprecated is important to know */ if (!isEmpty(cf.deprecated)) tagStanzaAdd(tagStorm, stanza, "deprecated", cf.deprecated); /* Basic file name info */ tagStanzaAdd(tagStorm, stanza, "file_name", fileName); tagStanzaAddLongLong(tagStorm, stanza, "file_size", cf.size); tagStanzaAdd(tagStorm, stanza, "md5", cf.md5); tagStanzaAddLongLong(tagStorm, stanza, "file_id", cf.id); /* Stuff gathered from submission */ tagStanzaAdd(tagStorm, stanza, "submit_file_name", cf.submitFileName); struct cdwSubmitDir *dir = intValTreeFind(submitDirTree, cf.submitDirId); if (dir != NULL) { tagStanzaAdd(tagStorm, stanza, "submit_dir", dir->url); } safef(fileName, sizeof(fileName), "%s%s", cdwRootDir, cf.cdwFileName); tagStanzaAdd(tagStorm, stanza, "cdw_file_name", fileName); tagStanzaAdd(tagStorm, stanza, "accession", vf.licensePlate); if (vf.itemCount != 0) tagStanzaAddLongLong(tagStorm, stanza, "item_count", vf.itemCount); if (vf.depth != 0) tagStanzaAddDouble(tagStorm, stanza, "seq_depth", vf.depth); if (vf.mapRatio != 0) tagStanzaAddDouble(tagStorm, stanza, "map_ratio", vf.mapRatio); /* Add tag field */ char *cgiVars = cf.tags; char *var,*val; while (cgiParseNext(&cgiVars, &var, &val)) tagStanzaAdd(tagStorm, stanza, var, val); } sqlFreeResult(&sr); verbose(2, "cdwTagStorm: %d items in fileTree\n", fileTree->n); /** Add selected tags from other tables as part of stanza tags. */ /* Add cdwFastqFile info */ sqlSafef(query, sizeof(query), "select * from cdwFastqFile"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwFastqFile *fq = cdwFastqFileLoad(row); struct tagStanza *stanza = intValTreeFind(fileTree, fq->fileId); if (stanza != NULL) { addReadSizeInfo(tagStorm, stanza, fq->readSizeMin, fq->readSizeMax, fq->readSizeMean, fq->readSizeStd); tagStanzaAdd(tagStorm, stanza, "fastq_qual_type", fq->qualType); tagStanzaAddDouble(tagStorm, stanza, "fastq_qual_mean", fq->qualMean); tagStanzaAddDouble(tagStorm, stanza, "at_ratio", fq->atRatio); cdwFastqFileFree(&fq); } } sqlFreeResult(&sr); /* Add cdwQaPairedEndFastq */ sqlSafef(query, sizeof(query), "select * from cdwQaPairedEndFastq where recordComplete != 0"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwQaPairedEndFastq pair; cdwQaPairedEndFastqStaticLoad(row, &pair); struct tagStanza *p1 = intValTreeFind(fileTree, pair.fileId1); struct tagStanza *p2 = intValTreeFind(fileTree, pair.fileId2); if (p1 != NULL && p2 != NULL) { char *acc1 = tagFindVal(p1, "accession"); char *acc2 = tagFindVal(p2, "accession"); addPairedEndTags(tagStorm, p1, &pair, acc2); addPairedEndTags(tagStorm, p2, &pair, acc1); } } sqlFreeResult(&sr); /* Build up in-memory random access data structure for enrichment targets */ struct rbTree *enrichTargetTree = intValTreeNew(); sqlSafef(query, sizeof(query), "select * from cdwQaEnrichTarget"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwQaEnrichTarget *target = cdwQaEnrichTargetLoad(row); intValTreeAdd(enrichTargetTree, target->id, target); } sqlFreeResult(&sr); /* Build up in-memory random access data structure for common_snp enrichments. We'll * use this later in the VCF bits. */ struct rbTree *snpEnrichTree = intValTreeNew(); /* Add cdwQaEnrich - here we'll supply exon, chrY, and whatever they put in their enriched_in * data, a subset of all */ sqlSafef(query, sizeof(query), "select * from cdwQaEnrich"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwQaEnrich rich; cdwQaEnrichStaticLoad(row, &rich); struct cdwQaEnrichTarget *target = intValTreeFind(enrichTargetTree, rich.qaEnrichTargetId); if (target != NULL) { char *targetName = target->name; if (sameString(targetName, "common_snp")) { struct cdwQaEnrich *keepRich = cloneMem(&rich, sizeof(rich)); intValTreeAdd(snpEnrichTree, keepRich->fileId, keepRich); } struct tagStanza *stanza = intValTreeFind(fileTree, rich.fileId); if (stanza != NULL) { char *enrichedIn = tagFindVal(stanza, "enriched_in"); boolean onTarget = FALSE; if (enrichedIn != NULL && sameWord(enrichedIn, targetName)) onTarget = TRUE; else if (sameWord(targetName, "exon")) onTarget = TRUE; else if (sameWord(targetName, "promoter")) onTarget = TRUE; else if (sameWord(targetName, "chrX")) onTarget = TRUE; else if (sameWord(targetName, "chrY")) onTarget = TRUE; if (onTarget) { char tagName[128]; safef(tagName, sizeof(tagName), "enrichment_%s", targetName); if (!tagFindVal(stanza, tagName)) tagStanzaAddDouble(tagStorm, stanza, tagName, rich.enrichment); } } } else verbose(2, "Missing on qaEnrichTargetId %u\n", rich.qaEnrichTargetId); } sqlFreeResult(&sr); /* Add cdwQaRepeat - here we'll supply rRNA, and total mapRatio out of the table */ addRepeatInfo(conn, tagStorm, fileTree, "rRNA", "ribosome"); addRepeatInfo(conn, tagStorm, fileTree, "total", "repeat"); /* Add contamination targets */ addContamInfo(conn, tagStorm, fileTree, 9606, "human"); addContamInfo(conn, tagStorm, fileTree, 10090, "mouse"); addContamInfo(conn, tagStorm, fileTree, 10116, "rat"); addContamInfo(conn, tagStorm, fileTree, 7227, "fly"); addContamInfo(conn, tagStorm, fileTree, 559292, "yeast"); addContamInfo(conn, tagStorm, fileTree, 6239, "worm"); addContamInfo(conn, tagStorm, fileTree, 562, "ecoli"); /* Add info from cdwBamFile */ sqlSafef(query, sizeof(query), "select * from cdwBamFile"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwBamFile bam; cdwBamFileStaticLoad(row, &bam); struct tagStanza *stanza = intValTreeFind(fileTree, bam.fileId); if (stanza != NULL) { tagStanzaAddLongLong(tagStorm, stanza, "paired_end_reads", bam.isPaired); tagStanzaAddLongLong(tagStorm, stanza, "sorted_by_target", bam.isSortedByTarget); addReadSizeInfo(tagStorm, stanza, bam.readSizeMin, bam.readSizeMax, bam.readSizeMean, bam.readSizeStd); tagStanzaAddDouble(tagStorm, stanza, "u4m_unique_ratio", bam.u4mUniqueRatio); tagStanzaAddLongLong(tagStorm, stanza, "map_target_base_count", bam.targetBaseCount); tagStanzaAddLongLong(tagStorm, stanza, "map_target_seq_count", bam.targetSeqCount); } } sqlFreeResult(&sr); /* Add info from cdwVcfFile */ sqlSafef(query, sizeof(query), "select * from cdwVcfFile"); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { struct cdwVcfFile vcf; cdwVcfFileStaticLoad(row, &vcf); struct tagStanza *stanza = intValTreeFind(fileTree, vcf.fileId); if (stanza != NULL) { tagStanzaAddLongLong(tagStorm, stanza, "vcf_genotype_count", vcf.genotypeCount); tagStanzaAddDouble(tagStorm, stanza, "vcf_pass_ratio", vcf.passRatio); tagStanzaAddDouble(tagStorm, stanza, "vcf_snp_ratio", vcf.snpRatio); tagStanzaAddLongLong(tagStorm, stanza, "vcf_genotype_count", vcf.genotypeCount); if (vcf.haploidCount > 0) tagStanzaAddDouble(tagStorm, stanza, "vcf_haploid_ratio", vcf.haploidRatio); if (vcf.phasedCount > 0) tagStanzaAddDouble(tagStorm, stanza, "vcf_phased_ratio", vcf.phasedRatio); if (vcf.gotDepth) tagStanzaAddDouble(tagStorm, stanza, "vcf_dp", vcf.depthMean); struct cdwQaEnrich *commonEnrich = intValTreeFind(snpEnrichTree, vcf.fileId); if (commonEnrich != NULL) { // Attempt to calculate coverage of data set by common snps double commonCov = (double)commonEnrich->targetBaseHits / vcf.sumOfSizes; tagStanzaAddDouble(tagStorm, stanza, "vcf_common_snp_ratio", commonCov); } } } sqlFreeResult(&sr); /* Clean up and go home */ rbTreeFree(&submitDirTree); rbTreeFree(&metaTree); rbTreeFree(&fileTree); tagStormReverseAll(tagStorm); return tagStorm; } struct tagStorm *cdwTagStorm(struct sqlConnection *conn) /* Load cdwMetaTags.tags, cdwFile.tags, and select other fields into a tag * storm for searching */ { return cdwTagStormRestricted(conn, NULL); } struct tagStorm *cdwUserTagStormFromList(struct sqlConnection *conn, struct cdwUser *user, struct cdwFile *validList ,struct rbTree *groupedFiles) /* Return tag storm just for files user has access to with the list * of validated files and the list of files the user shares group rights to * already calculated */ { struct rbTree *accessTree = cdwAccessTreeForUser(conn, user, validList, groupedFiles); struct tagStorm *tags = cdwTagStormRestricted(conn, accessTree); rbTreeFree(&accessTree); return tags; } struct tagStorm *cdwUserTagStorm(struct sqlConnection *conn, struct cdwUser *user) /* Return tag storm just for files user has access to. */ { struct cdwFile *validList = cdwFileLoadAllValid(conn); int userId = 0; if (user != NULL) userId = user->id; struct rbTree *groupedFiles = cdwFilesWithSharedGroup(conn, userId); struct tagStorm *tags = cdwUserTagStormFromList(conn, user, validList, groupedFiles); rbTreeFree(&groupedFiles); cdwFileFreeList(&validList); return tags; }
HydrologicEngineeringCenter/go-coastal
geometry/triangle.go
<filename>geometry/triangle.go package geometry import "errors" type Triangle struct { p1 *PointZ p2 *PointZ p3 *PointZ extent Extent } func CreateTriangle(a *PointZ, b *PointZ, c *PointZ) Triangle { var minx, miny, maxx, maxy float64 minx = 180 miny = 180 maxx = -180 maxy = -180 if maxx < a.X { maxx = a.X } if maxx < b.X { maxx = b.X } if maxx < c.X { maxx = c.X } if minx > a.X { minx = a.X } if minx > b.X { minx = b.X } if minx > c.X { minx = c.X } if maxy < a.Y { maxy = a.Y } if maxy < b.Y { maxy = b.Y } if maxy < c.Y { maxy = c.Y } if miny > a.Y { miny = a.Y } if miny > b.Y { miny = b.Y } if miny > c.Y { miny = c.Y } e := Extent{LowerLeft: Point{X: minx, Y: miny}, UpperRight: Point{X: maxx, Y: maxy}} return Triangle{p1: a, p2: b, p3: c, extent: e} } //https://codeplea.com/triangular-interpolation func (t Triangle) GetValue(x float64, y float64, zidx int) (float64, error) { invDenom := 1 / ((t.p2.Y-t.p3.Y)*(t.p1.X-t.p3.X) + (t.p3.X-t.p2.X)*(t.p1.Y-t.p3.Y)) w1 := ((t.p2.Y-t.p3.Y)*(x-t.p3.X) + (t.p3.X-t.p2.X)*(y-t.p3.Y)) * invDenom w2 := ((t.p3.Y-t.p1.Y)*(x-t.p3.X) + (t.p1.X-t.p3.X)*(y-t.p3.Y)) * invDenom w3 := 1.0 - w1 - w2 if w1 >= 0 && w2 >= 0 && w3 >= 0 { return (w1*t.p1.Z[zidx] + w2*t.p2.Z[zidx] + w3*t.p3.Z[zidx]), nil } return -9999, errors.New("Point Outside Triangle") } func (t Triangle) GetValues(x float64, y float64) ([]float64, error) { invDenom := 1 / ((t.p2.Y-t.p3.Y)*(t.p1.X-t.p3.X) + (t.p3.X-t.p2.X)*(t.p1.Y-t.p3.Y)) w1 := ((t.p2.Y-t.p3.Y)*(x-t.p3.X) + (t.p3.X-t.p2.X)*(y-t.p3.Y)) * invDenom w2 := ((t.p3.Y-t.p1.Y)*(x-t.p3.X) + (t.p1.X-t.p3.X)*(y-t.p3.Y)) * invDenom w3 := 1.0 - w1 - w2 lenz := len(t.p1.Z) vals := make([]float64, lenz) if w1 >= 0 && w2 >= 0 && w3 >= 0 { for i, z := range t.p1.Z { vals[i] = (w1*z + w2*t.p2.Z[i] + w3*t.p3.Z[i]) } return vals, nil } return []float64{-9999}, errors.New("Point Outside Triangle") } func (t *Triangle) Extent() Extent { return t.extent }
hanxiaobott/normal
src/main/java/com/example/self/normalpractice/proxy/jdk/SelfInvocationHandler.java
<reponame>hanxiaobott/normal package com.example.self.normalpractice.proxy.jdk; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * @description: * @author: hanxiaobo * @create: 2021-01-25 10:10 */ public class SelfInvocationHandler implements InvocationHandler { private Object object; public SelfInvocationHandler(Object object){ this.object = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) { System.out.println("方法执行之前"); Object invoke = null; try { invoke = method.invoke(object, args); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("方法执行之后"); return invoke; } }
osgirl/Adept
adept-api/src/main/java/adept/common/SyntacticTagFactory.java
package adept.common; /*- * #%L * adept-api * %% * Copyright (C) 2012 - 2017 <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. * #L% */ import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.InvalidPropertiesFormatException; import java.util.Properties; /** * A factory for creating SyntacticTag objects. */ public class SyntacticTagFactory { /** The syntactic tag catalog. */ private Properties syntacticTagCatalog; /** The instance map. */ private static HashMap<String,SyntacticTagFactory> instances = new HashMap<String, SyntacticTagFactory>(); /** * Instantiates a new syntactic tag factory. */ private SyntacticTagFactory() { } /** * Gets the single instance of SyntacticTagFactory. * * @param sTypeCatalog the type catalog * @return single instance of SyntacticTagFactory * @throws InvalidPropertiesFormatException the invalid properties format exception * @throws IOException Signals that an I/O exception has occurred. */ public static SyntacticTagFactory getInstance(String sTypeCatalog) throws InvalidPropertiesFormatException, IOException { SyntacticTagFactory stFactory; if (instances.get(sTypeCatalog) == null) { stFactory = new SyntacticTagFactory(); stFactory.loadSyntacticTagCatalog(sTypeCatalog); //insert into hashmap instances.put(sTypeCatalog, stFactory); } else { //System.out.println("Found a factory instance previously made!"); stFactory = instances.get(sTypeCatalog); } return stFactory; } /** * Gets the single instance of SyntacticTagFactory. * * @return single instance of SyntacticTagFactory * @throws InvalidPropertiesFormatException * the invalid properties format exception * @throws IOException * Signals that an I/O exception has occurred. */ public static SyntacticTagFactory getInstance() throws InvalidPropertiesFormatException, IOException { return getInstance("adept/common/SyntacticTagFactory.xml"); } /** * Gets the type. * * @param type * the type * @return the type */ public Type getType(String type) { String eType = syntacticTagCatalog.getProperty(type); if (eType == null) { return null; } return new Type(eType); } /** * Load part of speech tag catalog. * * @param catalogName the catalog name * @throws InvalidPropertiesFormatException the invalid properties format exception * @throws IOException Signals that an I/O exception has occurred. */ private void loadSyntacticTagCatalog(String catalogName) throws InvalidPropertiesFormatException, IOException { syntacticTagCatalog = new Properties(); InputStream is = this.getClass().getClassLoader().getResourceAsStream(catalogName); syntacticTagCatalog.loadFromXML(is); } }
KLumy/pacemaker-spa-client
src/common/utility/string.js
<gh_stars>1-10 export const startUpperCase = (string) => string.charAt(0).toUpperCase() + string.slice(1); export const removeTag = (string) => string.replace(/<(.|\n)*\/.*>/g, ''); export const excludeNonASCII = (string, extended = false) => string.replace(extended ? /[^\x00-\xFF]/g : /[^\x00-\x7F]/g, ''); export const checkIsASCII = (string, extended = false) => (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(string); export const regularizeString = (string) => excludeNonASCII(removeTag(string));
ksoderbl/thinmatrix-opengl-3d-game-tutorial-cpp-sdl2
src/particles/ParticleSystem.h
#ifndef PARTICLESYSTEM_H #define PARTICLESYSTEM_H #include "../Headers.h" #include "ParticleTexture.h" class ParticleSystem { public: ParticleSystem(ParticleTexture& texture, GLfloat pps, GLfloat speed, GLfloat gravityCompliant, GLfloat lifeLength, GLfloat scale); void setDirection(glm::vec3 direction, GLfloat deviation); void randomizeRotation(); /** * @param error * - A number between 0 and 1, where 0 means no error margin. */ void setSpeedError(GLfloat error) { this->speedError = error * averageSpeed; } /** * @param error * - A number between 0 and 1, where 0 means no error margin. */ void setLifeError(GLfloat error) { this->lifeError = error * averageLifeLength; } /** * @param error * - A number between 0 and 1, where 0 means no error margin. */ void setScaleError(float error) { this->scaleError = error * averageScale; } void generateParticles(glm::vec3 systemCenter); void emitParticle(glm::vec3& center); GLfloat generateValue(GLfloat average, GLfloat errorMargin); GLfloat generateRotation(); glm::vec3 generateRandomUnitVectorWithinCone(glm::vec3& coneDirection, GLfloat angle); glm::vec3 generateRandomUnitVector(); private: ParticleTexture& texture; GLfloat pps; GLfloat averageSpeed; GLfloat gravityCompliant; GLfloat averageLifeLength; GLfloat averageScale; GLfloat speedError; GLfloat lifeError; GLfloat scaleError = 0; bool randomRotation = false; glm::vec3 direction; bool haveDirection = false; GLfloat directionDeviation = 0; }; #endif
jeffbrown/Building-Microservices-with-Micronaut
Chapter02/micronaut-petclinic/pet-owner/src/main/java/com/packtpub/micronaut/service/PetTypeService.java
package com.packtpub.micronaut.service; import com.packtpub.micronaut.domain.PetType; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import java.util.Optional; /** * Service Interface for managing {@link com.packtpub.micronaut.domain.PetType}. */ public interface PetTypeService { /** * Save a petType. * * @param petType the entity to save. * @return the persisted entity. */ PetType save(PetType petType); /** * Get all the petTypes. * * @param pageable the pagination information. * @return the list of entities. */ Page<PetType> findAll(Pageable pageable); /** * Get the "id" petType. * * @param id the id of the entity. * @return the entity. */ Optional<PetType> findOne(Long id); /** * Delete the "id" petType. * * @param id the id of the entity. */ void delete(Long id); }
lonord/reeasy.js
bin/reeasy.js
<reponame>lonord/reeasy.js<filename>bin/reeasy.js #!/usr/bin/env node /* * Created on Fri Jun 30 2017 * * Copyright (c) 2017 <NAME>. <<EMAIL>> */ const program = require('commander') const path = require('path') const package = require('../package.json') const builder = require('../lib/builder') const server = require('../lib/server') let handled = false program .version(package.version) .usage('<dev|build|start>') program .command('build') .description('Run reeasy to build files for production') .option('-c, --config <value>', 'Custom reeasy config file') .option('-w, --cwd <value>', 'Custom working directory') .action((options) => { handled = true const cwd = options.cwd ? path.join(process.cwd(), options.cwd) : process.cwd() process.env.NODE_ENV = 'production' Promise.resolve() .then(() => builder.readConfig(options.config, cwd)) .then(config => builder.prepareWebpack(config, false, cwd)) .then(webpackConfig => builder.build(webpackConfig)) .catch(err => { console.error(err) }) }) program .command('start') .description('Run reeasy in development mode') .option('-p, --port <n>', 'Port to listen for http server') .option('-w, --cwd <value>', 'Custom working directory') .action((options) => { handled = true const cwd = options.cwd ? path.join(process.cwd(), options.cwd) : process.cwd() process.env.NODE_ENV = 'production' let port = parseInt(options.port) if (isNaN(port)) { port = process.env.PORT || 3000 } Promise.resolve() .then(() => builder.readConfig(options.config, cwd)) .then(config => builder.getProdMiddleware(config, cwd)) .then(middleWare => server.createServer(middleWare)) .then(app => app.listen(port)) .then(() => { console.log('> Ready on http://localhost:' + port) }) .catch(err => { console.error(err) }) }) program .command('dev') .description('Run reeasy in development mode, with HMR support') .option('-c, --config <value>', 'Custom reeasy config file') .option('-p, --port <n>', 'Port to listen for http server') .option('-w, --cwd <value>', 'Custom working directory') .action((options) => { handled = true const cwd = options.cwd ? path.join(process.cwd(), options.cwd) : process.cwd() process.env.NODE_ENV = 'development' let port = parseInt(options.port) if (isNaN(port)) { port = process.env.PORT || 3000 } Promise.resolve() .then(() => builder.readConfig(options.config, cwd)) .then(config => { return builder.prepareWebpack(config, true, cwd).then(webpackConfig => ({ webpackConfig: webpackConfig, config: config })) }) .then(result => builder.getDevMiddleware(result.webpackConfig, result.config, cwd)) .then(middleWare => server.createServer(middleWare)) .then(app => app.listen(port)) .then(() => { console.log('> Ready on http://localhost:' + port) }) .catch(err => { console.error(err) }) }) program.parse(process.argv); if (!handled) { program.help() }
fzf/qmk_toolbox
users/mguterl/mguterl.c
#include "mguterl.h"
yoolk/aop-client
lib/aop-client/config.rb
module AopClient class Config include ActiveModel::Validations ## Attributes attr_accessor :app_key attr_accessor :app_secret attr_accessor :api_entry attr_accessor :oauth_entry attr_accessor :access_token attr_accessor :sign_method attr_accessor :format attr_accessor :version ## Validations validates! :app_key, presence: true validates! :app_secret, presence: true validates! :api_entry, presence: true validates! :oauth_entry, presence: true def initialize(access_token=nil) self.access_token = <PASSWORD>_token.to_s self.sign_method = 'md5' self.format = 'json' self.version = '2.0' load_yml! if defined?(Rails) && yml_exists? valid? end def yml_exists? defined?(Rails.root) ? File.exist?(yml_path) : false end def yml begin @yml ||= YAML.load(ERB.new(IO.read(yml_path)).result)[Rails.env] rescue nil || {} rescue Psych::SyntaxError @yml = {} end end def yml_path Rails.root.join('config', 'aop-client.yml').to_s end def load_yml! self.app_key = yml['app_key'] self.app_secret = yml['app_secret'] self.api_entry = yml['api_entry'] self.oauth_entry = yml['oauth_entry'] end end end
wokalski/Distraction-Free-Xcode-plugin
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/DebuggerUI/DBGLabelExpressionEntry.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" @class NSString; @interface DBGLabelExpressionEntry : NSObject { BOOL _forceLanguageToObjectiveCPlusPlus; NSString *_label; NSString *_expressionFormat; NSString *_fallbackExpressionFormat; CDUnknownBlockType _formatValueBlock; NSString *_expression; NSString *_fallbackExpression; NSString *_expressionResult; } @property BOOL forceLanguageToObjectiveCPlusPlus; // @synthesize forceLanguageToObjectiveCPlusPlus=_forceLanguageToObjectiveCPlusPlus; @property(retain, nonatomic) NSString *expressionResult; // @synthesize expressionResult=_expressionResult; @property(retain) NSString *fallbackExpression; // @synthesize fallbackExpression=_fallbackExpression; @property(retain) NSString *expression; // @synthesize expression=_expression; @property(copy) CDUnknownBlockType formatValueBlock; // @synthesize formatValueBlock=_formatValueBlock; @property(retain) NSString *fallbackExpressionFormat; // @synthesize fallbackExpressionFormat=_fallbackExpressionFormat; @property(readonly) NSString *expressionFormat; // @synthesize expressionFormat=_expressionFormat; @property(readonly) NSString *label; // @synthesize label=_label; - (void).cxx_destruct; - (id)_initWithLabel:(id)arg1 expressionFormat:(id)arg2 fallbackExpressionFormat:(id)arg3; - (id)_initWithLabel:(id)arg1 expressionFormat:(id)arg2; @end
LoongPenguin/Linux_210
xboot/src/arch/arm32/mach-x210ii/include/s5pv210/reg-nand.h
#ifndef __S5PV210_REG_NAND_H__ #define __S5PV210_REG_NAND_H__ #define S5PV210_NFCONF (0xb0e00000) #define S5PV210_NFCONT (0xb0e00004) #define S5PV210_NFCMD (0xb0e00008) #define S5PV210_NFADDR (0xb0e0000c) #define S5PV210_NFDATA (0xb0e00010) #define S5PV210_NFMECCD0 (0xb0e00014) #define S5PV210_NFMECCD1 (0xb0e00018) #define S5PV210_NFSECCD (0xb0e0001c) #define S5PV210_NFSBLK (0xb0e00020) #define S5PV210_NFEBLK (0xb0e00024) #define S5PV210_NFSTAT (0xb0e00028) #define S5PV210_NFECCERR0 (0xb0e0002c) #define S5PV210_NFECCERR1 (0xb0e00030) #define S5PV210_NFMECC0 (0xb0e00034) #define S5PV210_NFMECC1 (0xb0e00038) #define S5PV210_NFSECC (0xb0e0003c) #define S5PV210_NFMLCBITPT (0xb0e00040) #define S5PV210_NFECCCONF (0xb0e20000) #define S5PV210_NFECCCONT (0xb0e20020) #define S5PV210_NFECCSTAT (0xb0e20030) #define S5PV210_NFECCSECSTAT (0xb0e20040) #define S5PV210_NFECCPRGECC0 (0xb0e20090) #define S5PV210_NFECCPRGECC1 (0xb0e20094) #define S5PV210_NFECCPRGECC2 (0xb0e20098) #define S5PV210_NFECCPRGECC3 (0xb0e2009c) #define S5PV210_NFECCPRGECC4 (0xb0e200a0) #define S5PV210_NFECCPRGECC5 (0xb0e200a4) #define S5PV210_NFECCPRGECC6 (0xb0e200a8) #define S5PV210_NFECCERL0 (0xb0e200c0) #define S5PV210_NFECCERL1 (0xb0e200c4) #define S5PV210_NFECCERL2 (0xb0e200c8) #define S5PV210_NFECCERL3 (0xb0e200cc) #define S5PV210_NFECCERL4 (0xb0e200d0) #define S5PV210_NFECCERL5 (0xb0e200d4) #define S5PV210_NFECCERL6 (0xb0e200d8) #define S5PV210_NFECCERL7 (0xb0e200dc) #define S5PV210_NFECCERP0 (0xb0e200f0) #define S5PV210_NFECCERP1 (0xb0e200f4) #define S5PV210_NFECCERP2 (0xb0e200f8) #define S5PV210_NFECCERP3 (0xb0e200fc) #define S5PV210_NFECCCONECC0 (0xb0e20110) #define S5PV210_NFECCCONECC1 (0xb0e20114) #define S5PV210_NFECCCONECC2 (0xb0e20118) #define S5PV210_NFECCCONECC3 (0xb0e2011c) #define S5PV210_NFECCCONECC4 (0xb0e20120) #define S5PV210_NFECCCONECC5 (0xb0e20124) #define S5PV210_NFECCCONECC6 (0xb0e20128) #endif /* __S5PV210_REG_NAND_H__ */
18702524730/servicerCenter
src/router/fillData/companyAuth.js
<reponame>18702524730/servicerCenter import {FillData} from 'views/'; export default { path: 'companyAuth', name: 'companyAuth', meta:{ name: '机构实名认证', permission: 'true' }, icon: 'inbox', component: FillData.companyAuth };
ac111897/AS91892
docs/search/functions_f.js
<reponame>ac111897/AS91892 var searchData= [ ['write_0',['Write',['../class_time_span_converter.html#ab672e779c15544cf88e4a927d73229e2',1,'TimeSpanConverter']]] ];
ethansaxenian/RosettaDecode
lang/C/sierpinski-triangle-4.c
int main() { sierpinski_triangle(4); return EXIT_SUCCESS; }
Akirix/akirix-suite
uber-app/app/routes/dashboard.js
<reponame>Akirix/akirix-suite import Ember from 'ember'; import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend( AuthenticatedRouteMixin, { model: function(){ return null; }, activate: function(){ document.title = "Dashboard"; this.transitionTo( 'dashboard.wire-summary' ); } } );
gyyang/olfaction_evolution
analytical/peter.py
import numpy as np import matplotlib.pyplot as plt from itertools import combinations from mpl_toolkits.mplot3d import Axes3D from sklearn.metrics.pairwise import euclidean_distances def get_labels(prototypes, odors): dist = euclidean_distances(prototypes, odors) label = np.argmin(dist, axis=0) return label n_samples = 200 n_proto = 4 n_pn = 5 n_kc = (n_pn-1) * (n_pn-2) k = 3 orn = np.random.uniform(low=0, high=1, size=[n_samples, n_pn]) proto_points = np.random.uniform(low=0, high=1, size=[n_proto, n_pn]) rand_labels = get_labels(proto_points, orn) colors = [np.array([55, 94, 151]) / 255., # blue np.array([251, 101, 66]) / 255., # orange np.array([255, 187, 0]) / 255., # red np.array([63, 104, 28]) / 255., ] # green rand_colors = [colors[i] for i in rand_labels] combs = list(combinations(range(n_pn), k)) matrix = np.zeros((n_pn, len(combs))) for i, comb in enumerate(combs): matrix[comb,i] = 1 kc = np.matmul(orn, matrix) ixs = [0, 1, 2] fig = plt.figure(figsize=[10,10]) axs = fig.add_subplot(211, projection='3d') mat = orn # for point, color in zip(mat, rand_colors): axs.scatter(mat[:,ixs[0]], mat[:,ixs[1]], zs= mat[:,ixs[2]], zdir='z', s=20, c=rand_colors, depthshade=True) axs = fig.add_subplot(212, projection='3d') mat = kc axs.scatter(mat[:,ixs[0]], mat[:,ixs[1]], zs= mat[:,ixs[2]], zdir='z', s=20, c=rand_colors, depthshade=True) plt.show()
marcelosalles/pyidf
tests/test_airloophvacoutdoorairsystemequipmentlist.py
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.air_distribution import AirLoopHvacOutdoorAirSystemEquipmentList log = logging.getLogger(__name__) class TestAirLoopHvacOutdoorAirSystemEquipmentList(unittest.TestCase): def setUp(self): self.fd, self.path = tempfile.mkstemp() def tearDown(self): os.remove(self.path) def test_create_airloophvacoutdoorairsystemequipmentlist(self): pyidf.validation_level = ValidationLevel.error obj = AirLoopHvacOutdoorAirSystemEquipmentList() # alpha var_name = "Name" obj.name = var_name # alpha var_component_1_object_type = "Component 1 Object Type" obj.component_1_object_type = var_component_1_object_type # alpha var_component_1_name = "Component 1 Name" obj.component_1_name = var_component_1_name # alpha var_component_2_object_type = "Component 2 Object Type" obj.component_2_object_type = var_component_2_object_type # alpha var_component_2_name = "Component 2 Name" obj.component_2_name = var_component_2_name # alpha var_component_3_object_type = "Component 3 Object Type" obj.component_3_object_type = var_component_3_object_type # alpha var_component_3_name = "Component 3 Name" obj.component_3_name = var_component_3_name # alpha var_component_4_object_type = "Component 4 Object Type" obj.component_4_object_type = var_component_4_object_type # alpha var_component_4_name = "Component 4 Name" obj.component_4_name = var_component_4_name # alpha var_component_5_object_type = "Component 5 Object Type" obj.component_5_object_type = var_component_5_object_type # alpha var_component_5_name = "Component 5 Name" obj.component_5_name = var_component_5_name # alpha var_component_6_object_type = "Component 6 Object Type" obj.component_6_object_type = var_component_6_object_type # alpha var_component_6_name = "Component 6 Name" obj.component_6_name = var_component_6_name # alpha var_component_7_object_type = "Component 7 Object Type" obj.component_7_object_type = var_component_7_object_type # alpha var_component_7_name = "Component 7 Name" obj.component_7_name = var_component_7_name # alpha var_component_8_object_type = "Component 8 Object Type" obj.component_8_object_type = var_component_8_object_type # alpha var_component_8_name = "Component 8 Name" obj.component_8_name = var_component_8_name # alpha var_component_9_object_type = "Component 9 Object Type" obj.component_9_object_type = var_component_9_object_type # alpha var_component_9_name = "Component 9 Name" obj.component_9_name = var_component_9_name idf = IDF() idf.add(obj) idf.save(self.path, check=False) with open(self.path, mode='r') as f: for line in f: log.debug(line.strip()) idf2 = IDF(self.path) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].name, var_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_1_object_type, var_component_1_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_1_name, var_component_1_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_2_object_type, var_component_2_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_2_name, var_component_2_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_3_object_type, var_component_3_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_3_name, var_component_3_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_4_object_type, var_component_4_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_4_name, var_component_4_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_5_object_type, var_component_5_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_5_name, var_component_5_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_6_object_type, var_component_6_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_6_name, var_component_6_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_7_object_type, var_component_7_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_7_name, var_component_7_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_8_object_type, var_component_8_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_8_name, var_component_8_name) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_9_object_type, var_component_9_object_type) self.assertEqual(idf2.airloophvacoutdoorairsystemequipmentlists[0].component_9_name, var_component_9_name)
Boriscx/-
src/main/java/com/cy/pj/sys/aspect/SysExceptionAspect.java
<reponame>Boriscx/-<gh_stars>0 package com.cy.pj.sys.aspect; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Order(1) @Slf4j @Aspect @Component public class SysExceptionAspect { // @AfterThrowing(value = "bean(*ServiceImpl)", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Exception e) { MethodSignature ms = (MethodSignature) joinPoint.getSignature(); String methodName = ms.getName(); log.error("{} exception msg is {}", methodName, e.getMessage()); } }
creazydev/epidemic-simulator
src/main/java/com/github/epidemicsimulator/EpidemicSimulatorApplication.java
package com.github.epidemicsimulator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class EpidemicSimulatorApplication { public static void main(String[] args) { SpringApplication.run(EpidemicSimulatorApplication.class, args); } }
RUAN0007/Hybrid-Blockchain-Database-Systems
tso/examples/benchmark.go
<reponame>RUAN0007/Hybrid-Blockchain-Database-Systems package main import ( "fmt" "hybrid/tso" "sync" "time" "gopkg.in/alecthomas/kingpin.v2" ) var ( tsoAddr = kingpin.Flag("addr", "tso server address").Default(":7070").String() concurrency = kingpin.Flag("concurrency", "client num").Default("20").Int() reqNum = kingpin.Flag("req-num", "request num").Default("1000000").Int() ) func main() { kingpin.Parse() avaReqNum := *reqNum / (*concurrency) wg := &sync.WaitGroup{} for i := 0; i < *concurrency; i++ { wg.Add(1) go func() { defer wg.Done() cli, err := tso.NewClient(*tsoAddr) if err != nil { panic(err) } defer cli.Close() for j := 0; j < avaReqNum; j++ { if _, err := cli.TS(); err != nil { panic(err) } } }() } start := time.Now() wg.Wait() fmt.Printf("%v clients %v requests: %v req/s\n", *concurrency, *reqNum, int64(float64(*reqNum)/time.Since(start).Seconds())) }
nkedel/jetty.project
jetty-websocket/javax-websocket-client-impl/src/main/java/org/eclipse/jetty/websocket/jsr356/endpoints/JsrEndpointImpl.java
<filename>jetty-websocket/javax-websocket-client-impl/src/main/java/org/eclipse/jetty/websocket/jsr356/endpoints/JsrEndpointImpl.java // // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.jsr356.endpoints; import org.eclipse.jetty.websocket.api.WebSocketPolicy; import org.eclipse.jetty.websocket.common.events.EventDriver; import org.eclipse.jetty.websocket.common.events.EventDriverImpl; public class JsrEndpointImpl implements EventDriverImpl { @Override public EventDriver create(Object websocket, WebSocketPolicy policy) { if (!(websocket instanceof EndpointInstance)) { throw new IllegalStateException(String.format("Websocket %s must be an %s", websocket.getClass().getName(), EndpointInstance.class.getName())); } return new JsrEndpointEventDriver(policy, (EndpointInstance)websocket); } @Override public String describeRule() { return "class extends " + javax.websocket.Endpoint.class.getName(); } @Override public boolean supports(Object websocket) { if (!(websocket instanceof EndpointInstance)) { return false; } EndpointInstance ei = (EndpointInstance)websocket; Object endpoint = ei.getEndpoint(); return (endpoint instanceof javax.websocket.Endpoint); } }
importlib/klib
master/core/third/cxxtools/src/mime.cpp
/* * Copyright (C) 2007 <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cxxtools/mime.h> #include <cxxtools/base64stream.h> #include <cxxtools/quotedprintablestream.h> #include <cxxtools/log.h> #include <stdlib.h> #include <vector> #include <sstream> #include <fstream> #include <stdexcept> log_define("cxxtools.mime") namespace cxxtools { Mimepart::Mimepart(const std::string& contentType_, ContentTransferEncoding contentTransferEncoding_) : contentTransferEncoding(contentTransferEncoding_) { setHeader("Content-Type", contentType_); } void Mimepart::addData(std::istream& in) { std::ostringstream data; data << in.rdbuf(); body += data.str(); } Mimepart& Mime::addPart(const std::string& data, const std::string& contentType, ContentTransferEncoding contentTransferEncoding) { log_debug("add part " << data.size() << " bytes, contentType \"" << contentType << "\" content transfer encoding " << contentTransferEncoding); parts.push_back(Mimepart(contentType, contentTransferEncoding)); parts.back().setData(data); return parts.back(); } Mimepart& Mime::addPart(std::istream& in, const std::string& contentType, ContentTransferEncoding contentTransferEncoding) { log_debug("add part from stream, contentType \"" << contentType << "\" content transfer encoding " << contentTransferEncoding); parts.push_back(Mimepart(contentType, contentTransferEncoding)); std::ostringstream body; body << in.rdbuf(); log_debug("part has " << body.str().size() << " bytes"); parts.back().setData(body.str()); return parts.back(); } Mimepart& Mime::addTextFile(const std::string& contentType, const std::string& filename) { std::ifstream in(filename.c_str()); if (!in) throw std::runtime_error("cannot open file \"" + filename + '"'); return addTextFile(contentType, filename, in); } Mimepart& Mime::addBinaryFile(const std::string& contentType, const std::string& filename) { std::ifstream in(filename.c_str()); if (!in) throw std::runtime_error("cannot open file \"" + filename + '"'); return addBinaryFile(contentType, filename, in); } std::ostream& operator<< (std::ostream& out, const Mimepart& mimePart) { // print headers for (Mimepart::HeadersType::const_iterator it = mimePart.headers.begin(); it != mimePart.headers.end(); ++it) out << it->first << ": " << it->second << '\n'; // encode data if (mimePart.contentTransferEncoding == Mimepart::quotedPrintable) { out << "Content-Transfer-Encoding: quoted-printable\n\n"; QuotedPrintable_ostream enc(out); enc << mimePart.getBody(); out << '\n'; } else if (mimePart.contentTransferEncoding == Mimepart::base64) { out << "Content-Transfer-Encoding: base64\n\n"; Base64ostream enc(out); enc << mimePart.getBody(); enc.terminate(); out << "\n\n"; } else { std::ostringstream msg; msg << "unknown Content-Transfer-Encoding " << mimePart.contentTransferEncoding; log_error(msg.str()); throw std::runtime_error(msg.str()); } return out; } std::ostream& operator<< (std::ostream& out, const Mime& mime) { // build string parts typedef std::vector<std::string> SpartsType; SpartsType sparts; for (Mime::PartsType::const_iterator pit = mime.parts.begin(); pit != mime.parts.end(); ++pit) { std::ostringstream out; out << *pit; sparts.push_back(out.str()); } // choose suitable boundary std::string boundary; time_t t; time(&t); while (true) { std::ostringstream h; h << std::hex << t; boundary = "=Boundary=" + h.str() + "="; for (SpartsType::const_iterator it = sparts.begin(); it != sparts.end(); ++it) if (it->find(boundary) != std::string::npos) continue; t += rand(); break; } // print headers out << "MIME-Version: 1.0\n" "Content-Type: multipart/mixed; boundary=\"" << boundary << "\"\n"; for (Mime::HeadersType::const_iterator it = mime.headers.begin(); it != mime.headers.end(); ++it) out << it->first << ": " << it->second << '\n'; out << '\n'; // print parts for (SpartsType::const_iterator it = sparts.begin(); it != sparts.end(); ++it) out << "--" << boundary << '\n' << *it; out << "--" << boundary << "--\n"; return out; } }
s-aska/Justaway-for-Android-Original
Justaway/src/main/java/info/justaway/listener/RemoveAccountListener.java
<gh_stars>10-100 package info.justaway.listener; import twitter4j.auth.AccessToken; public interface RemoveAccountListener { void removeAccount(AccessToken accessToken); }
lucas-barros/cadhub
docs/src/pages/index.js
<reponame>lucas-barros/cadhub import React from 'react' import clsx from 'clsx' import Layout from '@theme/Layout' import Link from '@docusaurus/Link' import useDocusaurusContext from '@docusaurus/useDocusaurusContext' import useBaseUrl from '@docusaurus/useBaseUrl' import styles from './styles.module.css' export default function Home() { const context = useDocusaurusContext() const { siteConfig = {} } = context return ( <Layout title={`Learn with ${siteConfig.title}`} description="The premier to learn Code-CAD" > <header className={clsx( 'bg-gradient-to-r from-red-300 via-red-200 to-pink-100', styles.heroBanner )} > <div className="container"> <h1 className="font-ropa-sans text-6xl pb-8 text-indigo-600"> {siteConfig.title} </h1> <p className="font-ropa-sans text-indigo-700 max-w-3xl mx-auto text-lg"> Cadhub is a community hub for Code-CAD projects aiming to push the paradigm forward. </p> <p className="font-ropa-sans text-indigo-700 max-w-3xl mx-auto text-lg"> Code-CAD is the premier way to design parts, it fits into software-dev work-flow and is right level of abstraction having, parts defined as auditable scripts. </p> <p className="font-ropa-sans text-indigo-700 max-w-3xl mx-auto text-lg pb-6"> We have beta integrations with OpenSCAD and CadQuery. The best way to learn more is to: </p> <div className={styles.buttons}> <Link className={clsx( 'font-mono border-indigo-100 border rounded-md py-2 px-4 bg-pink-200 text-indigo-800 font-bold shadow hover:shadow-md', styles.getStarted )} to={useBaseUrl('docs/')} > Get Started </Link> </div> </div> </header> <main> <div className="max-w-6xl mx-auto px-2 pb-32"> <h2 className="text-indigo-700 text-5xl font-roboto my-16 tracking-widest font-light"> What's the potential of code-cad? </h2> <MarketingPoint leadingPoint="Communication" title="Tech-drawing and CAD as communication medium" > <p className="max-w-2xl"> Have you ever started frantically reaching for a pen when trying to explain an idea? </p> <p className="pt-4"> Engineers love drawings and CAD extends that, though now communicating with machines is just as important as with colleagues. What better way to do that than with a deterministic, expressive and auditable script? </p> </MarketingPoint> <div className="mt-24"> <div className="text-2xl text-pink-400 font-bold tracking-widest"> Extensible </div> <h3 className="text-indigo-700 text-4xl mt-4"> If <span className="line-through">it bleeds</span> it's text, we can <span className="line-through">kill</span> hack it </h3> <div className="text-gray-600 max-w-3xl text-2xl font-light mt-4"> <ul className="list-disc pl-6"> <li>Build your own helper functions and abstractions</li> <li> Trigger{' '} <a href="/blog/testing-code-cad"> FEM </a>{' '} or regenerate tool paths with a CI/CD process </li> <li> Auto-generate a{' '} <a href="/blog/codecad-artifacts"> BOM </a> </li> <li> Integrate it into your{' '} <a href="https://www.ptc.com/en/technologies/plm">PLM</a>{' '} tools </li> <li> <a href="/blog/3d-diffs"> 3d-diffs </a> </li> </ul> </div> </div> <MarketingPoint leadingPoint="Git Good" title="All of the benefits of version control" > <p> Team coordination doesn't get any better than git. Multiple people working on a complex assembly without treading on each other -- what else is there to say? </p> </MarketingPoint> <MarketingPoint leadingPoint="Rise of the developer" title="Leverage a growing industry" > <p> Software is taking over the world, and so are developers. In the U.S. developers are 1.4M strong and are predicted to increase their{' '} <a href="https://www.bls.gov/ooh/computer-and-information-technology/software-developers.htm"> ranks by 22% </a>{' '} over the next 10 years. As coders proliferate, so will the number of areas in which they operate, including CAD. </p> </MarketingPoint> </div> </main> </Layout> ) } function MarketingPoint({ leadingPoint, title, children }) { return ( <div className="mt-24"> <div className="text-2xl text-pink-400 font-bold tracking-widest"> {leadingPoint} </div> <h3 className="text-indigo-700 text-4xl mt-4">{title}</h3> <div className="text-gray-600 max-w-3xl text-2xl font-light mt-4"> {children} </div> </div> ) }
jokokoloko/ghost
src/style.js
// Hero export const HERO_OPACITY = 'opacity-30'; export const HERO_TINT = 'dark-50'; export const HERO_COLOR = 4;
JuzamDjinn91/NES-Snake
gfx/level4_nam.h
/** * @file level4_nam.h * @brief This header file contains the nametable (background) of level map 4. * Created with NES Screen Tool 2.04 (Option Nametable -> Save nametable and attributes -> RLE packed as C header (.h). * * @author <NAME> * */ const unsigned char level4_nam[383]={ 0x01,0x00,0x01,0x20,0x33,0x23,0x2f,0x32,0x25,0x1a,0x10,0x01,0x02,0x0f,0x10,0x14, 0x10,0x00,0x01,0x31,0x43,0x01,0x3d,0x44,0x44,0x43,0x43,0x00,0x01,0x0c,0x43,0x43, 0x00,0x01,0x0c,0x43,0x01,0x03,0x00,0x01,0x0c,0x43,0x43,0x00,0x01,0x0c,0x43,0x01, 0x03,0x00,0x01,0x0c,0x43,0x43,0x00,0x01,0x0c,0x43,0x01,0x03,0x00,0x01,0x0c,0x43, 0x43,0x00,0x01,0x0c,0x43,0x01,0x0a,0x00,0x00,0x43,0x01,0x09,0x00,0x00,0x43,0x44, 0x43,0x01,0x02,0x44,0x44,0x43,0x01,0x0a,0x00,0x00,0x43,0x01,0x09,0x00,0x00,0x43, 0x44,0x01,0x05,0x43,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x0d,0x43,0x43, 0x00,0x01,0x04,0x43,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x0d,0x43,0x43, 0x00,0x01,0x04,0x43,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x01, 0x02,0x44,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x01,0x03,0x00,0x01,0x04, 0x43,0x43,0x00,0x01,0x04,0x43,0x00,0x00,0x43,0x00,0x01,0x04,0x43,0x43,0x00,0x01, 0x04,0x43,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x00,0x00,0x43, 0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x01,0x03,0x00,0x01,0x0b,0x43,0x00, 0x00,0x43,0x00,0x01,0x0b,0x43,0x01,0x03,0x00,0x01,0x0b,0x43,0x00,0x00,0x43,0x00, 0x01,0x0b,0x43,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x00,0x00, 0x43,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43,0x01,0x03,0x00,0x01,0x04,0x43, 0x43,0x00,0x01,0x04,0x44,0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x04,0x43, 0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x0d,0x43,0x43,0x00,0x01,0x04,0x43, 0x01,0x03,0x00,0x01,0x04,0x43,0x43,0x00,0x01,0x0d,0x43,0x43,0x00,0x01,0x04,0x43, 0x01,0x0a,0x00,0x00,0x43,0x01,0x09,0x00,0x00,0x43,0x01,0x11,0x00,0x00,0x43,0x01, 0x09,0x00,0x00,0x43,0x01,0x0a,0x00,0x01,0x0c,0x44,0x44,0x00,0x01,0x0c,0x43,0x01, 0x03,0x00,0x01,0x0c,0x44,0x44,0x00,0x01,0x0c,0x43,0x01,0x03,0x00,0x01,0x0c,0x44, 0x44,0x00,0x01,0x0c,0x43,0x01,0x03,0x00,0x01,0x0c,0x44,0x44,0x00,0x01,0x0c,0x43, 0x01,0x2e,0x44,0x43,0x01,0x05,0x44,0x43,0x01,0x0a,0x00,0x01,0x3f,0x01,0x00 };
jrfaller/maracas
test-data/comp-changes/client/src/mainclient/methodNowAbstract/MethodNowAbstractExt.java
package mainclient.methodNowAbstract; import main.methodNowAbstract.MethodNowAbstract; public class MethodNowAbstractExt extends MethodNowAbstract { @Override public int methodStayAbstract() { return 0; } public int methodNowAbstractClientSuperKey() { return super.methodNowAbstract(); } public int methodNowAbstractClientNoSuperKey() { return methodNowAbstract(); } }
braymar/afl
qemu_mode/qemu-2.10.0/roms/u-boot/board/sbc8641d/sbc8641d.c
<reponame>braymar/afl<gh_stars>1-10 /* * Copyright 2007 Wind River Systemes, Inc. <www.windriver.com> * Copyright 2007 Embedded Specialties, Inc. * <NAME> <EMAIL> * * Copyright 2004 Freescale Semiconductor. * <NAME> * <NAME> (<EMAIL>) * * (C) Copyright 2002 <NAME> <<EMAIL>> * * SPDX-License-Identifier: GPL-2.0+ */ #include <common.h> #include <command.h> #include <pci.h> #include <asm/processor.h> #include <asm/immap_86xx.h> #include <asm/fsl_pci.h> #include <fsl_ddr_sdram.h> #include <asm/fsl_serdes.h> #include <libfdt.h> #include <fdt_support.h> DECLARE_GLOBAL_DATA_PTR; long int fixed_sdram (void); int board_early_init_f (void) { return 0; } int checkboard (void) { puts ("Board: Wind River SBC8641D\n"); return 0; } int dram_init(void) { long dram_size = 0; #if defined(CONFIG_SPD_EEPROM) dram_size = fsl_ddr_sdram(); #else dram_size = fixed_sdram (); #endif debug (" DDR: "); gd->ram_size = dram_size; return 0; } #if defined(CONFIG_SYS_DRAM_TEST) int testdram (void) { uint *pstart = (uint *) CONFIG_SYS_MEMTEST_START; uint *pend = (uint *) CONFIG_SYS_MEMTEST_END; uint *p; puts ("SDRAM test phase 1:\n"); for (p = pstart; p < pend; p++) *p = 0xaaaaaaaa; for (p = pstart; p < pend; p++) { if (*p != 0xaaaaaaaa) { printf ("SDRAM test fails at: %08x\n", (uint) p); return 1; } } puts ("SDRAM test phase 2:\n"); for (p = pstart; p < pend; p++) *p = 0x55555555; for (p = pstart; p < pend; p++) { if (*p != 0x55555555) { printf ("SDRAM test fails at: %08x\n", (uint) p); return 1; } } puts ("SDRAM test passed.\n"); return 0; } #endif #if !defined(CONFIG_SPD_EEPROM) /* * Fixed sdram init -- doesn't use serial presence detect. */ long int fixed_sdram (void) { #if !defined(CONFIG_SYS_RAMBOOT) volatile immap_t *immap = (immap_t *) CONFIG_SYS_IMMR; volatile struct ccsr_ddr *ddr = &immap->im_ddr1; ddr->cs0_bnds = CONFIG_SYS_DDR_CS0_BNDS; ddr->cs1_bnds = CONFIG_SYS_DDR_CS1_BNDS; ddr->cs2_bnds = CONFIG_SYS_DDR_CS2_BNDS; ddr->cs3_bnds = CONFIG_SYS_DDR_CS3_BNDS; ddr->cs0_config = CONFIG_SYS_DDR_CS0_CONFIG; ddr->cs1_config = CONFIG_SYS_DDR_CS1_CONFIG; ddr->cs2_config = CONFIG_SYS_DDR_CS2_CONFIG; ddr->cs3_config = CONFIG_SYS_DDR_CS3_CONFIG; ddr->timing_cfg_3 = CONFIG_SYS_DDR_TIMING_3; ddr->timing_cfg_0 = CONFIG_SYS_DDR_TIMING_0; ddr->timing_cfg_1 = CONFIG_SYS_DDR_TIMING_1; ddr->timing_cfg_2 = CONFIG_SYS_DDR_TIMING_2; ddr->sdram_cfg = CONFIG_SYS_DDR_CFG_1A; ddr->sdram_cfg_2 = CONFIG_SYS_DDR_CFG_2; ddr->sdram_mode = CONFIG_SYS_DDR_MODE_1; ddr->sdram_mode_2 = CONFIG_SYS_DDR_MODE_2; ddr->sdram_md_cntl = CONFIG_SYS_DDR_MODE_CTL; ddr->sdram_interval = CONFIG_SYS_DDR_INTERVAL; ddr->sdram_data_init = CONFIG_SYS_DDR_DATA_INIT; ddr->sdram_clk_cntl = CONFIG_SYS_DDR_CLK_CTRL; asm ("sync;isync"); udelay (500); ddr->sdram_cfg = CONFIG_SYS_DDR_CFG_1B; asm ("sync; isync"); udelay (500); ddr = &immap->im_ddr2; ddr->cs0_bnds = CONFIG_SYS_DDR2_CS0_BNDS; ddr->cs1_bnds = CONFIG_SYS_DDR2_CS1_BNDS; ddr->cs2_bnds = CONFIG_SYS_DDR2_CS2_BNDS; ddr->cs3_bnds = CONFIG_SYS_DDR2_CS3_BNDS; ddr->cs0_config = CONFIG_SYS_DDR2_CS0_CONFIG; ddr->cs1_config = CONFIG_SYS_DDR2_CS1_CONFIG; ddr->cs2_config = CONFIG_SYS_DDR2_CS2_CONFIG; ddr->cs3_config = CONFIG_SYS_DDR2_CS3_CONFIG; ddr->timing_cfg_3 = CONFIG_SYS_DDR2_EXT_REFRESH; ddr->timing_cfg_0 = CONFIG_SYS_DDR2_TIMING_0; ddr->timing_cfg_1 = CONFIG_SYS_DDR2_TIMING_1; ddr->timing_cfg_2 = CONFIG_SYS_DDR2_TIMING_2; ddr->sdram_cfg = CONFIG_SYS_DDR2_CFG_1A; ddr->sdram_cfg_2 = CONFIG_SYS_DDR2_CFG_2; ddr->sdram_mode = CONFIG_SYS_DDR2_MODE_1; ddr->sdram_mode_2 = CONFIG_SYS_DDR2_MODE_2; ddr->sdram_md_cntl = CONFIG_SYS_DDR2_MODE_CTL; ddr->sdram_interval = CONFIG_SYS_DDR2_INTERVAL; ddr->sdram_data_init = CONFIG_SYS_DDR2_DATA_INIT; ddr->sdram_clk_cntl = CONFIG_SYS_DDR2_CLK_CTRL; asm ("sync;isync"); udelay (500); ddr->sdram_cfg = CONFIG_SYS_DDR2_CFG_1B; asm ("sync; isync"); udelay (500); #endif return CONFIG_SYS_SDRAM_SIZE * 1024 * 1024; } #endif /* !defined(CONFIG_SPD_EEPROM) */ #if defined(CONFIG_PCI) /* * Initialize PCI Devices, report devices found. */ void pci_init_board(void) { fsl_pcie_init_board(0); } #endif /* CONFIG_PCI */ #if defined(CONFIG_OF_BOARD_SETUP) int ft_board_setup(void *blob, bd_t *bd) { ft_cpu_setup(blob, bd); FT_FSL_PCI_SETUP; return 0; } #endif void sbc8641d_reset_board (void) { puts ("Resetting board....\n"); } /* * get_board_sys_clk * Clock is fixed at 1GHz on this board. Used for CONFIG_SYS_CLK_FREQ */ unsigned long get_board_sys_clk (ulong dummy) { int i; ulong val = 0; i = 5; i &= 0x07; switch (i) { case 0: val = 33000000; break; case 1: val = 40000000; break; case 2: val = 50000000; break; case 3: val = 66000000; break; case 4: val = 83000000; break; case 5: val = 100000000; break; case 6: val = 134000000; break; case 7: val = 166000000; break; } return val; } void board_reset(void) { #ifdef CONFIG_SYS_RESET_ADDRESS ulong addr = CONFIG_SYS_RESET_ADDRESS; /* flush and disable I/D cache */ __asm__ __volatile__ ("mfspr 3, 1008" ::: "r3"); __asm__ __volatile__ ("ori 5, 5, 0xcc00" ::: "r5"); __asm__ __volatile__ ("ori 4, 3, 0xc00" ::: "r4"); __asm__ __volatile__ ("andc 5, 3, 5" ::: "r5"); __asm__ __volatile__ ("sync"); __asm__ __volatile__ ("mtspr 1008, 4"); __asm__ __volatile__ ("isync"); __asm__ __volatile__ ("sync"); __asm__ __volatile__ ("mtspr 1008, 5"); __asm__ __volatile__ ("isync"); __asm__ __volatile__ ("sync"); /* * SRR0 has system reset vector, SRR1 has default MSR value * rfi restores MSR from SRR1 and sets the PC to the SRR0 value */ __asm__ __volatile__ ("mtspr 26, %0" :: "r" (addr)); __asm__ __volatile__ ("li 4, (1 << 6)" ::: "r4"); __asm__ __volatile__ ("mtspr 27, 4"); __asm__ __volatile__ ("rfi"); #endif }
RicardoAugusto-RCD/exercicios_python
exercicios/ex084a.py
# Faça um programa que leia nome e peso de várias pessoa, guardando tudo em uma lista. No final, mostre: # a) Quantas pessoa foram cadastradas. # b) Uma listagem com as pessoa mais pesadas. # c) Uma listagem com as pessoa mais leves. temp = [] princ = [] mai = men = 0 while True: temp.append(str(input('Nome: '))) temp.append(float(input('Peso: '))) if len(princ) == 0: mai = men = temp[1] else: if temp[1] > mai: mai = temp[1] if temp[1] < men: men = temp[1] princ.append(temp[:]) temp.clear() resp = str(input('Quer continuar? [S/N]')) if resp in 'Nn': break print('—' * 50) print(f'Ao todo, você cadastrou {len(princ)} pessoas') print(f'O maior peso foi de {mai}kg. Peso de ', end='') for p in princ: if p[1] == mai: print(f'[{p[0]}] ', end='') print() print(f'O menor peso foi de {men}kg. Peso de ', end='') for p in princ: if p[1] == men: print(f'[{p[0]}] ', end='') print() print('—' * 50)
Horizon-Blue/playground
Solutions-to-Books/C++Primer/Chapter09/9.49.cpp
// A letter has an ascender if, as with d or f, // part of the letter extends above the middle of // the line. A letter has a descender if, as with p // or g, part of the letter extends below the line. // Write a program that reads a file containing words // and reports the longest word that contains neither // ascenders nor descenders. #include <fstream> #include <iostream> #include <string> using namespace std; inline bool qualify(const string& s) { return s.find_first_not_of("aceimnorsuvwxz") == string::npos; } int main() { string name_of_file; cout << "Enter the name of the file:\n"; cin >> name_of_file; ifstream infile(name_of_file); size_t maxlength = 0; string result; for(string temp; infile >> temp;) { if(qualify(temp) && temp.size() > maxlength) { result = temp; maxlength = temp.size(); } } cout << "The longest word that contains neither " << "ascenders nor descenders is " << result << endl; return 0; }
SachiSakurane/libmk2
include/mk2/debug.hpp
// // Created by SachiSakurane on 2019-03-27. // #pragma once #include <mk2/debug/build_type.hpp> #include <mk2/debug/debug_log.hpp>